Fixes listen/TCP bug
[akaros.git] / kern / src / net / tcp.c
1 // INFERNO
2 #include <vfs.h>
3 #include <kfs.h>
4 #include <slab.h>
5 #include <kmalloc.h>
6 #include <kref.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <assert.h>
10 #include <error.h>
11 #include <cpio.h>
12 #include <pmap.h>
13 #include <smp.h>
14 #include <ip.h>
15
16 #include <vfs.h>
17 #include <kfs.h>
18 #include <slab.h>
19 #include <kmalloc.h>
20 #include <kref.h>
21 #include <string.h>
22 #include <stdio.h>
23 #include <assert.h>
24 #include <error.h>
25 #include <cpio.h>
26 #include <pmap.h>
27 #include <smp.h>
28 #include <ip.h>
29
30 enum {
31         QMAX = 64 * 1024 - 1,
32         IP_TCPPROTO = 6,
33
34         TCP4_IPLEN = 8,
35         TCP4_PHDRSIZE = 12,
36         TCP4_HDRSIZE = 20,
37         TCP4_TCBPHDRSZ = 40,
38         TCP4_PKT = TCP4_IPLEN + TCP4_PHDRSIZE,
39
40         TCP6_IPLEN = 0,
41         TCP6_PHDRSIZE = 40,
42         TCP6_HDRSIZE = 20,
43         TCP6_TCBPHDRSZ = 60,
44         TCP6_PKT = TCP6_IPLEN + TCP6_PHDRSIZE,
45
46         TcptimerOFF = 0,
47         TcptimerON = 1,
48         TcptimerDONE = 2,
49         MAX_TIME = (1 << 20),   /* Forever */
50         TCP_ACK = 50,   /* Timed ack sequence in ms */
51         MAXBACKMS = 9 * 60 * 1000,      /* longest backoff time (ms) before hangup */
52
53         URG = 0x20,     /* Data marked urgent */
54         ACK = 0x10,     /* Acknowledge is valid */
55         PSH = 0x08,     /* Whole data pipe is pushed */
56         RST = 0x04,     /* Reset connection */
57         SYN = 0x02,     /* Pkt. is synchronise */
58         FIN = 0x01,     /* Start close down */
59
60         EOLOPT = 0,
61         NOOPOPT = 1,
62         MSSOPT = 2,
63         MSS_LENGTH = 4, /* Mean segment size */
64         WSOPT = 3,
65         WS_LENGTH = 3,  /* Bits to scale window size by */
66         MSL2 = 10,
67         MSPTICK = 50,   /* Milliseconds per timer tick */
68         DEF_MSS = 1460, /* Default mean segment */
69         DEF_MSS6 = 1280,        /* Default mean segment (min) for v6 */
70         DEF_RTT = 500,  /* Default round trip */
71         DEF_KAT = 120000,       /* Default time (ms) between keep alives */
72         TCP_LISTEN = 0, /* Listen connection */
73         TCP_CONNECT = 1,        /* Outgoing connection */
74         SYNACK_RXTIMER = 250,   /* ms between SYNACK retransmits */
75
76         TCPREXMTTHRESH = 3,     /* dupack threshhold for rxt */
77
78         FORCE = 1,
79         CLONE = 2,
80         RETRAN = 4,
81         ACTIVE = 8,
82         SYNACK = 16,
83
84         LOGAGAIN = 3,
85         LOGDGAIN = 2,
86
87         Closed = 0,     /* Connection states */
88         Listen,
89         Syn_sent,
90         Syn_received,
91         Established,
92         Finwait1,
93         Finwait2,
94         Close_wait,
95         Closing,
96         Last_ack,
97         Time_wait,
98
99         Maxlimbo = 1000,        /* maximum procs waiting for response to SYN ACK */
100         NLHT = 256,     /* hash table size, must be a power of 2 */
101         LHTMASK = NLHT - 1,
102
103         HaveWS = 1 << 8,
104 };
105
106 /* Must correspond to the enumeration above */
107 char *tcpstates[] = {
108         "Closed", "Listen", "Syn_sent", "Syn_received",
109         "Established", "Finwait1", "Finwait2", "Close_wait",
110         "Closing", "Last_ack", "Time_wait"
111 };
112
113 typedef struct Tcptimer Tcptimer;
114 struct Tcptimer {
115         Tcptimer *next;
116         Tcptimer *prev;
117         Tcptimer *readynext;
118         int state;
119         int start;
120         int count;
121         void (*func) (void *);
122         void *arg;
123 };
124
125 /*
126  *  v4 and v6 pseudo headers used for
127  *  checksuming tcp
128  */
129 typedef struct Tcp4hdr Tcp4hdr;
130 struct Tcp4hdr {
131         uint8_t vihl;                           /* Version and header length */
132         uint8_t tos;                            /* Type of service */
133         uint8_t length[2];                      /* packet length */
134         uint8_t id[2];                          /* Identification */
135         uint8_t frag[2];                        /* Fragment information */
136         uint8_t Unused;
137         uint8_t proto;
138         uint8_t tcplen[2];
139         uint8_t tcpsrc[4];
140         uint8_t tcpdst[4];
141         uint8_t tcpsport[2];
142         uint8_t tcpdport[2];
143         uint8_t tcpseq[4];
144         uint8_t tcpack[4];
145         uint8_t tcpflag[2];
146         uint8_t tcpwin[2];
147         uint8_t tcpcksum[2];
148         uint8_t tcpurg[2];
149         /* Options segment */
150         uint8_t tcpopt[1];
151 };
152
153 typedef struct Tcp6hdr Tcp6hdr;
154 struct Tcp6hdr {
155         uint8_t vcf[4];
156         uint8_t ploadlen[2];
157         uint8_t proto;
158         uint8_t ttl;
159         uint8_t tcpsrc[IPaddrlen];
160         uint8_t tcpdst[IPaddrlen];
161         uint8_t tcpsport[2];
162         uint8_t tcpdport[2];
163         uint8_t tcpseq[4];
164         uint8_t tcpack[4];
165         uint8_t tcpflag[2];
166         uint8_t tcpwin[2];
167         uint8_t tcpcksum[2];
168         uint8_t tcpurg[2];
169         /* Options segment */
170         uint8_t tcpopt[1];
171 };
172
173 /*
174  *  this represents the control info
175  *  for a single packet.  It is derived from
176  *  a packet in ntohtcp{4,6}() and stuck into
177  *  a packet in htontcp{4,6}().
178  */
179 typedef struct Tcp Tcp;
180 struct Tcp {
181         uint16_t source;
182         uint16_t dest;
183         uint32_t seq;
184         uint32_t ack;
185         uint8_t flags;
186         uint16_t ws;                            /* window scale option (if not zero) */
187         uint32_t wnd;
188         uint16_t urg;
189         uint16_t mss;                           /* max segment size option (if not zero) */
190         uint16_t len;                           /* size of data */
191 };
192
193 /*
194  *  this header is malloc'd to thread together fragments
195  *  waiting to be coalesced
196  */
197 typedef struct Reseq Reseq;
198 struct Reseq {
199         Reseq *next;
200         Tcp seg;
201         struct block *bp;
202         uint16_t length;
203 };
204
205 /*
206  *  the qlock in the Conv locks this structure
207  */
208 typedef struct Tcpctl Tcpctl;
209 struct Tcpctl {
210         uint8_t state;                          /* Connection state */
211         uint8_t type;                           /* Listening or active connection */
212         uint8_t code;                           /* Icmp code */
213         struct {
214                 uint32_t una;                   /* Unacked data pointer */
215                 uint32_t nxt;                   /* Next sequence expected */
216                 uint32_t ptr;                   /* Data pointer */
217                 uint32_t wnd;                   /* Tcp send window */
218                 uint32_t urg;                   /* Urgent data pointer */
219                 uint32_t wl2;
220                 int scale;                              /* how much to right shift window in xmitted packets */
221                 /* to implement tahoe and reno TCP */
222                 uint32_t dupacks;               /* number of duplicate acks rcvd */
223                 int recovery;                   /* loss recovery flag */
224                 uint32_t rxt;                   /* right window marker for recovery */
225         } snd;
226         struct {
227                 uint32_t nxt;                   /* Receive pointer to next uint8_t slot */
228                 uint32_t wnd;                   /* Receive window incoming */
229                 uint32_t urg;                   /* Urgent pointer */
230                 int blocked;
231                 int una;                                /* unacked data segs */
232                 int scale;                              /* how much to left shift window in rcved packets */
233         } rcv;
234         uint32_t iss;                           /* Initial sequence number */
235         int sawwsopt;                           /* true if we saw a wsopt on the incoming SYN */
236         uint32_t cwind;                         /* Congestion window */
237         int scale;                                      /* desired snd.scale */
238         uint16_t ssthresh;                      /* Slow start threshold */
239         int resent;                                     /* Bytes just resent */
240         int irs;                                        /* Initial received squence */
241         uint16_t mss;                           /* Mean segment size */
242         int rerecv;                                     /* Overlap of data rerecevived */
243         uint32_t window;                        /* Recevive window */
244         uint8_t backoff;                        /* Exponential backoff counter */
245         int backedoff;                          /* ms we've backed off for rexmits */
246         uint8_t flags;                          /* State flags */
247         Reseq *reseq;                           /* Resequencing queue */
248         Tcptimer timer;                         /* Activity timer */
249         Tcptimer acktimer;                      /* Acknowledge timer */
250         Tcptimer rtt_timer;                     /* Round trip timer */
251         Tcptimer katimer;                       /* keep alive timer */
252         uint32_t rttseq;                        /* Round trip sequence */
253         int srtt;                                       /* Shortened round trip */
254         int mdev;                                       /* Mean deviation of round trip */
255         int kacounter;                          /* count down for keep alive */
256         unsigned int sndsyntime;        /* time syn sent */
257         uint32_t time;                          /* time Finwait2 or Syn_received was sent */
258         int nochecksum;                         /* non-zero means don't send checksums */
259         int flgcnt;                                     /* number of flags in the sequence (FIN,SEQ) */
260
261         union {
262                 Tcp4hdr tcp4hdr;
263                 Tcp6hdr tcp6hdr;
264         } protohdr;                                     /* prototype header */
265 };
266
267 /*
268  *  New calls are put in limbo rather than having a conversation structure
269  *  allocated.  Thus, a SYN attack results in lots of limbo'd calls but not
270  *  any real Conv structures mucking things up.  Calls in limbo rexmit their
271  *  SYN ACK every SYNACK_RXTIMER ms up to 4 times, i.e., they disappear after 1 second.
272  *
273  *  In particular they aren't on a listener's queue so that they don't figure
274  *  in the input queue limit.
275  *
276  *  If 1/2 of a T3 was attacking SYN packets, we'ld have a permanent queue
277  *  of 70000 limbo'd calls.  Not great for a linear list but doable.  Therefore
278  *  there is no hashing of this list.
279  */
280 typedef struct Limbo Limbo;
281 struct Limbo {
282         Limbo *next;
283
284         uint8_t laddr[IPaddrlen];
285         uint8_t raddr[IPaddrlen];
286         uint16_t lport;
287         uint16_t rport;
288         uint32_t irs;                           /* initial received sequence */
289         uint32_t iss;                           /* initial sent sequence */
290         uint16_t mss;                           /* mss from the other end */
291         uint16_t rcvscale;                      /* how much to scale rcvd windows */
292         uint16_t sndscale;                      /* how much to scale sent windows */
293         uint32_t lastsend;                      /* last time we sent a synack */
294         uint8_t version;                        /* v4 or v6 */
295         uint8_t rexmits;                        /* number of retransmissions */
296 };
297
298 int tcp_irtt = DEF_RTT;                 /* Initial guess at round trip time */
299 uint16_t tcp_mss = DEF_MSS;             /* Maximum segment size to be sent */
300
301 enum {
302         /* MIB stats */
303         MaxConn,
304         ActiveOpens,
305         PassiveOpens,
306         EstabResets,
307         CurrEstab,
308         InSegs,
309         OutSegs,
310         RetransSegs,
311         RetransTimeouts,
312         InErrs,
313         OutRsts,
314
315         /* non-MIB stats */
316         CsumErrs,
317         HlenErrs,
318         LenErrs,
319         OutOfOrder,
320
321         Nstats
322 };
323
324 static char *statnames[] = {
325         [MaxConn] "MaxConn",
326         [ActiveOpens] "ActiveOpens",
327         [PassiveOpens] "PassiveOpens",
328         [EstabResets] "EstabResets",
329         [CurrEstab] "CurrEstab",
330         [InSegs] "InSegs",
331         [OutSegs] "OutSegs",
332         [RetransSegs] "RetransSegs",
333         [RetransTimeouts] "RetransTimeouts",
334         [InErrs] "InErrs",
335         [OutRsts] "OutRsts",
336         [CsumErrs] "CsumErrs",
337         [HlenErrs] "HlenErrs",
338         [LenErrs] "LenErrs",
339         [OutOfOrder] "OutOfOrder",
340 };
341
342 typedef struct Tcppriv Tcppriv;
343 struct tcppriv {
344         /* List of active timers */
345         qlock_t tl;
346         Tcptimer *timers;
347
348         /* hash table for matching conversations */
349         struct Ipht ht;
350
351         /* calls in limbo waiting for an ACK to our SYN ACK */
352         int nlimbo;
353         Limbo *lht[NLHT];
354
355         /* for keeping track of tcpackproc */
356         qlock_t apl;
357         int ackprocstarted;
358
359         uint32_t stats[Nstats];
360 };
361
362 /*
363  *  Setting tcpporthogdefense to non-zero enables Dong Lin's
364  *  solution to hijacked systems staking out port's as a form
365  *  of DoS attack.
366  *
367  *  To avoid stateless Conv hogs, we pick a sequence number at random.  If
368  *  it that number gets acked by the other end, we shut down the connection.
369  *  Look for tcpporthogedefense in the code.
370  */
371 int tcpporthogdefense = 0;
372
373 int addreseq(Tcpctl *, struct tcppriv *, Tcp *, struct block *, uint16_t);
374 void getreseq(Tcpctl *, Tcp *, struct block **, uint16_t *);
375 void localclose(struct conv *, char *unused_char_p_t);
376 void procsyn(struct conv *, Tcp *);
377 void tcpiput(struct Proto *, struct Ipifc *, struct block *);
378 void tcpoutput(struct conv *);
379 int tcptrim(Tcpctl *, Tcp *, struct block **, uint16_t *);
380 void tcpstart(struct conv *, int);
381 void tcptimeout(void *);
382 void tcpsndsyn(struct conv *, Tcpctl *);
383 void tcprcvwin(struct conv *);
384 void tcpacktimer(void *);
385 void tcpkeepalive(void *);
386 void tcpsetkacounter(Tcpctl *);
387 void tcprxmit(struct conv *);
388 void tcpsettimer(Tcpctl *);
389 void tcpsynackrtt(struct conv *);
390 void tcpsetscale(struct conv *, Tcpctl *, uint16_t, uint16_t);
391
392 static void limborexmit(struct Proto *);
393 static void limbo(struct conv *, uint8_t * unused_uint8_p_t, uint8_t *, Tcp *,
394                                   int);
395
396 void tcpsetstate(struct conv *s, uint8_t newstate)
397 {
398         Tcpctl *tcb;
399         uint8_t oldstate;
400         struct tcppriv *tpriv;
401
402         tpriv = s->p->priv;
403
404         tcb = (Tcpctl *) s->ptcl;
405
406         oldstate = tcb->state;
407         if (oldstate == newstate)
408                 return;
409
410         if (oldstate == Established)
411                 tpriv->stats[CurrEstab]--;
412         if (newstate == Established)
413                 tpriv->stats[CurrEstab]++;
414
415         /**
416         print( "%d/%d %s->%s CurrEstab=%d\n", s->lport, s->rport,
417                 tcpstates[oldstate], tcpstates[newstate], tpriv->tstats.tcpCurrEstab );
418         **/
419
420         switch (newstate) {
421                 case Closed:
422                         qclose(s->rq);
423                         qclose(s->wq);
424                         qclose(s->eq);
425                         break;
426
427                 case Close_wait:        /* Remote closes */
428                         qhangup(s->rq, NULL);
429                         break;
430         }
431
432         tcb->state = newstate;
433
434         if (oldstate == Syn_sent && newstate != Closed)
435                 Fsconnected(s, NULL);
436 }
437
438 static char *tcpconnect(struct conv *c, char **argv, int argc)
439 {
440         char *e;
441
442         e = Fsstdconnect(c, argv, argc);
443         if (e != NULL)
444                 return e;
445         tcpstart(c, TCP_CONNECT);
446
447         return NULL;
448 }
449
450 static int tcpstate(struct conv *c, char *state, int n)
451 {
452         Tcpctl *s;
453
454         s = (Tcpctl *) (c->ptcl);
455
456         return snprintf(state, n,
457                                         "%s qin %d qout %d srtt %d mdev %d cwin %lu swin %lu>>%d rwin %lu>>%d timer.start %d timer.count %d rerecv %d katimer.start %d katimer.count %d\n",
458                                         tcpstates[s->state],
459                                         c->rq ? qlen(c->rq) : 0,
460                                         c->wq ? qlen(c->wq) : 0,
461                                         s->srtt, s->mdev,
462                                         s->cwind, s->snd.wnd, s->rcv.scale, s->rcv.wnd,
463                                         s->snd.scale, s->timer.start, s->timer.count, s->rerecv,
464                                         s->katimer.start, s->katimer.count);
465 }
466
467 static int tcpinuse(struct conv *c)
468 {
469         Tcpctl *s;
470
471         s = (Tcpctl *) (c->ptcl);
472         return s->state != Closed;
473 }
474
475 static char *tcpannounce(struct conv *c, char **argv, int argc)
476 {
477         char *e;
478
479         e = Fsstdannounce(c, argv, argc);
480         if (e != NULL)
481                 return e;
482         tcpstart(c, TCP_LISTEN);
483         Fsconnected(c, NULL);
484
485         return NULL;
486 }
487
488 /*
489  *  tcpclose is always called with the q locked
490  */
491 static void tcpclose(struct conv *c)
492 {
493         Tcpctl *tcb;
494
495         tcb = (Tcpctl *) c->ptcl;
496
497         qhangup(c->rq, NULL);
498         qhangup(c->wq, NULL);
499         qhangup(c->eq, NULL);
500         qflush(c->rq);
501
502         switch (tcb->state) {
503                 case Listen:
504                         /*
505                          *  reset any incoming calls to this listener
506                          */
507                         Fsconnected(c, "Hangup");
508
509                         localclose(c, NULL);
510                         break;
511                 case Closed:
512                 case Syn_sent:
513                         localclose(c, NULL);
514                         break;
515                 case Syn_received:
516                 case Established:
517                         tcb->flgcnt++;
518                         tcb->snd.nxt++;
519                         tcpsetstate(c, Finwait1);
520                         tcpoutput(c);
521                         break;
522                 case Close_wait:
523                         tcb->flgcnt++;
524                         tcb->snd.nxt++;
525                         tcpsetstate(c, Last_ack);
526                         tcpoutput(c);
527                         break;
528         }
529 }
530
531 void tcpkick(void *x)
532 {
533         ERRSTACK(1);
534         struct conv *s = x;
535         Tcpctl *tcb;
536
537         tcb = (Tcpctl *) s->ptcl;
538
539         if (waserror()) {
540                 qunlock(&s->qlock);
541                 nexterror();
542         }
543         qlock(&s->qlock);
544
545         switch (tcb->state) {
546                 case Syn_sent:
547                 case Syn_received:
548                 case Established:
549                 case Close_wait:
550                         /*
551                          * Push data
552                          */
553                         tcprcvwin(s);
554                         tcpoutput(s);
555                         break;
556                 default:
557                         localclose(s, "Hangup");
558                         break;
559         }
560
561         qunlock(&s->qlock);
562         poperror();
563 }
564
565 void tcprcvwin(struct conv *s)
566 {       /* Call with tcb locked */
567         int w;
568         Tcpctl *tcb;
569
570         tcb = (Tcpctl *) s->ptcl;
571         w = tcb->window - qlen(s->rq);
572         if (w < 0)
573                 w = 0;
574         tcb->rcv.wnd = w;
575         if (w == 0)
576                 tcb->rcv.blocked = 1;
577 }
578
579 void tcpacktimer(void *v)
580 {
581         ERRSTACK(1);
582         Tcpctl *tcb;
583         struct conv *s;
584
585         s = v;
586         tcb = (Tcpctl *) s->ptcl;
587
588         if (waserror()) {
589                 qunlock(&s->qlock);
590                 nexterror();
591         }
592         qlock(&s->qlock);
593         if (tcb->state != Closed) {
594                 tcb->flags |= FORCE;
595                 tcprcvwin(s);
596                 tcpoutput(s);
597         }
598         qunlock(&s->qlock);
599         poperror();
600 }
601
602 static void tcpcreate(struct conv *c)
603 {
604         c->rq = qopen(QMAX, Qcoalesce, tcpacktimer, c);
605         c->wq = qopen((3 * QMAX) / 2, Qkick, tcpkick, c);
606 }
607
608 static void timerstate(struct tcppriv *priv, Tcptimer * t, int newstate)
609 {
610         if (newstate != TcptimerON) {
611                 if (t->state == TcptimerON) {
612                         // unchain
613                         if (priv->timers == t) {
614                                 priv->timers = t->next;
615                                 if (t->prev != NULL)
616                                         panic("timerstate1");
617                         }
618                         if (t->next)
619                                 t->next->prev = t->prev;
620                         if (t->prev)
621                                 t->prev->next = t->next;
622                         t->next = t->prev = NULL;
623                 }
624         } else {
625                 if (t->state != TcptimerON) {
626                         // chain
627                         if (t->prev != NULL || t->next != NULL)
628                                 panic("timerstate2");
629                         t->prev = NULL;
630                         t->next = priv->timers;
631                         if (t->next)
632                                 t->next->prev = t;
633                         priv->timers = t;
634                 }
635         }
636         t->state = newstate;
637 }
638
639 void tcpackproc(void *a)
640 {
641         ERRSTACK(1);
642         Tcptimer *t, *tp, *timeo;
643         struct Proto *tcp;
644         struct tcppriv *priv;
645         int loop;
646
647         tcp = a;
648         priv = tcp->priv;
649
650         for (;;) {
651                 udelay_sched(MSPTICK * 1000);
652
653                 qlock(&priv->tl);
654                 timeo = NULL;
655                 loop = 0;
656                 for (t = priv->timers; t != NULL; t = tp) {
657                         if (loop++ > 10000)
658                                 panic("tcpackproc1");
659                         tp = t->next;
660                         if (t->state == TcptimerON) {
661                                 t->count--;
662                                 if (t->count == 0) {
663                                         timerstate(priv, t, TcptimerDONE);
664                                         t->readynext = timeo;
665                                         timeo = t;
666                                 }
667                         }
668                 }
669                 qunlock(&priv->tl);
670
671                 loop = 0;
672                 for (t = timeo; t != NULL; t = t->readynext) {
673                         if (loop++ > 10000)
674                                 panic("tcpackproc2");
675                         if (t->state == TcptimerDONE && t->func != NULL) {
676                                 /* discard error style */
677                                 if (!waserror())
678                                         (*t->func) (t->arg);
679                                 poperror();
680                         }
681                 }
682
683                 limborexmit(tcp);
684         }
685 }
686
687 void tcpgo(struct tcppriv *priv, Tcptimer * t)
688 {
689         if (t == NULL || t->start == 0)
690                 return;
691
692         qlock(&priv->tl);
693         t->count = t->start;
694         timerstate(priv, t, TcptimerON);
695         qunlock(&priv->tl);
696 }
697
698 void tcphalt(struct tcppriv *priv, Tcptimer * t)
699 {
700         if (t == NULL)
701                 return;
702
703         qlock(&priv->tl);
704         timerstate(priv, t, TcptimerOFF);
705         qunlock(&priv->tl);
706 }
707
708 int backoff(int n)
709 {
710         return 1 << n;
711 }
712
713 void localclose(struct conv *s, char *reason)
714 {       /* called with tcb locked */
715         Tcpctl *tcb;
716         Reseq *rp, *rp1;
717         struct tcppriv *tpriv;
718
719         tpriv = s->p->priv;
720         tcb = (Tcpctl *) s->ptcl;
721
722         iphtrem(&tpriv->ht, s);
723
724         tcphalt(tpriv, &tcb->timer);
725         tcphalt(tpriv, &tcb->rtt_timer);
726         tcphalt(tpriv, &tcb->acktimer);
727         tcphalt(tpriv, &tcb->katimer);
728
729         /* Flush reassembly queue; nothing more can arrive */
730         for (rp = tcb->reseq; rp != NULL; rp = rp1) {
731                 rp1 = rp->next;
732                 freeblist(rp->bp);
733                 kfree(rp);
734         }
735         tcb->reseq = NULL;
736
737         if (tcb->state == Syn_sent)
738                 Fsconnected(s, reason);
739
740         qhangup(s->rq, reason);
741         qhangup(s->wq, reason);
742
743         tcpsetstate(s, Closed);
744
745         /* listener will check the rq state */
746         if (s->state == Announced)
747                 rendez_wakeup(&s->listenr);
748 }
749
750 /* mtu (- TCP + IP hdr len) of 1st hop */
751 int tcpmtu(struct Proto *tcp, uint8_t * addr, int version, int *scale)
752 {
753         struct Ipifc *ifc;
754         int mtu;
755
756         ifc = findipifc(tcp->f, addr, 0);
757         switch (version) {
758                 default:
759                 case V4:
760                         mtu = DEF_MSS;
761                         if (ifc != NULL)
762                                 mtu = ifc->maxtu - ifc->m->hsize - (TCP4_PKT + TCP4_HDRSIZE);
763                         break;
764                 case V6:
765                         mtu = DEF_MSS6;
766                         if (ifc != NULL)
767                                 mtu = ifc->maxtu - ifc->m->hsize - (TCP6_PKT + TCP6_HDRSIZE);
768                         break;
769         }
770         if (ifc != NULL) {
771                 if (ifc->mbps > 100)
772                         *scale = HaveWS | 3;
773                 else if (ifc->mbps > 10)
774                         *scale = HaveWS | 1;
775                 else
776                         *scale = HaveWS | 0;
777         } else
778                 *scale = HaveWS | 0;
779
780         return mtu;
781 }
782
783 void inittcpctl(struct conv *s, int mode)
784 {
785         Tcpctl *tcb;
786         Tcp4hdr *h4;
787         Tcp6hdr *h6;
788         int mss;
789
790         tcb = (Tcpctl *) s->ptcl;
791
792         memset(tcb, 0, sizeof(Tcpctl));
793
794         tcb->ssthresh = 65535;
795         tcb->srtt = tcp_irtt << LOGAGAIN;
796         tcb->mdev = 0;
797
798         /* setup timers */
799         tcb->timer.start = tcp_irtt / MSPTICK;
800         tcb->timer.func = tcptimeout;
801         tcb->timer.arg = s;
802         tcb->rtt_timer.start = MAX_TIME;
803         tcb->acktimer.start = TCP_ACK / MSPTICK;
804         tcb->acktimer.func = tcpacktimer;
805         tcb->acktimer.arg = s;
806         tcb->katimer.start = DEF_KAT / MSPTICK;
807         tcb->katimer.func = tcpkeepalive;
808         tcb->katimer.arg = s;
809
810         mss = DEF_MSS;
811
812         /* create a prototype(pseudo) header */
813         if (mode != TCP_LISTEN) {
814                 if (ipcmp(s->laddr, IPnoaddr) == 0)
815                         findlocalip(s->p->f, s->laddr, s->raddr);
816
817                 switch (s->ipversion) {
818                         case V4:
819                                 h4 = &tcb->protohdr.tcp4hdr;
820                                 memset(h4, 0, sizeof(*h4));
821                                 h4->proto = IP_TCPPROTO;
822                                 hnputs(h4->tcpsport, s->lport);
823                                 hnputs(h4->tcpdport, s->rport);
824                                 v6tov4(h4->tcpsrc, s->laddr);
825                                 v6tov4(h4->tcpdst, s->raddr);
826                                 break;
827                         case V6:
828                                 h6 = &tcb->protohdr.tcp6hdr;
829                                 memset(h6, 0, sizeof(*h6));
830                                 h6->proto = IP_TCPPROTO;
831                                 hnputs(h6->tcpsport, s->lport);
832                                 hnputs(h6->tcpdport, s->rport);
833                                 ipmove(h6->tcpsrc, s->laddr);
834                                 ipmove(h6->tcpdst, s->raddr);
835                                 mss = DEF_MSS6;
836                                 break;
837                         default:
838                                 panic("inittcpctl: version %d", s->ipversion);
839                 }
840         }
841
842         tcb->mss = tcb->cwind = mss;
843
844         /* default is no window scaling */
845         tcb->window = QMAX;
846         tcb->rcv.wnd = QMAX;
847         tcb->rcv.scale = 0;
848         tcb->snd.scale = 0;
849         qsetlimit(s->rq, QMAX);
850 }
851
852 /*
853  *  called with s qlocked
854  */
855 void tcpstart(struct conv *s, int mode)
856 {
857         Tcpctl *tcb;
858         struct tcppriv *tpriv;
859         char kpname[KNAMELEN];
860
861         tpriv = s->p->priv;
862
863         if (tpriv->ackprocstarted == 0) {
864                 qlock(&tpriv->apl);
865                 if (tpriv->ackprocstarted == 0) {
866                         snprintf(kpname, sizeof(kpname), "#I%dtcpack", s->p->f->dev);
867                         ktask(kpname, tcpackproc, s->p);
868                         tpriv->ackprocstarted = 1;
869                 }
870                 qunlock(&tpriv->apl);
871         }
872
873         tcb = (Tcpctl *) s->ptcl;
874
875         inittcpctl(s, mode);
876
877         iphtadd(&tpriv->ht, s);
878         switch (mode) {
879                 case TCP_LISTEN:
880                         tpriv->stats[PassiveOpens]++;
881                         tcb->flags |= CLONE;
882                         tcpsetstate(s, Listen);
883                         break;
884
885                 case TCP_CONNECT:
886                         tpriv->stats[ActiveOpens]++;
887                         tcb->flags |= ACTIVE;
888                         tcpsndsyn(s, tcb);
889                         tcpsetstate(s, Syn_sent);
890                         tcpoutput(s);
891                         break;
892         }
893 }
894
895 static char *tcpflag(uint16_t flag)
896 {
897         static char buf[128];
898
899         snprintf(buf, sizeof(buf), "%d", flag >> 10);   /* Head len */
900         if (flag & URG)
901                 snprintf(buf, sizeof(buf), "%s%s", buf, " URG");
902         if (flag & ACK)
903                 snprintf(buf, sizeof(buf), "%s%s", buf, " ACK");
904         if (flag & PSH)
905                 snprintf(buf, sizeof(buf), "%s%s", buf, " PSH");
906         if (flag & RST)
907                 snprintf(buf, sizeof(buf), "%s%s", buf, " RST");
908         if (flag & SYN)
909                 snprintf(buf, sizeof(buf), "%s%s", buf, " SYN");
910         if (flag & FIN)
911                 snprintf(buf, sizeof(buf), "%s%s", buf, " FIN");
912
913         return buf;
914 }
915
916 struct block *htontcp6(Tcp * tcph, struct block *data, Tcp6hdr * ph,
917                                            Tcpctl * tcb)
918 {
919         int dlen;
920         Tcp6hdr *h;
921         uint16_t csum;
922         uint16_t hdrlen, optpad = 0;
923         uint8_t *opt;
924
925         hdrlen = TCP6_HDRSIZE;
926         if (tcph->flags & SYN) {
927                 if (tcph->mss)
928                         hdrlen += MSS_LENGTH;
929                 if (tcph->ws)
930                         hdrlen += WS_LENGTH;
931                 optpad = hdrlen & 3;
932                 if (optpad)
933                         optpad = 4 - optpad;
934                 hdrlen += optpad;
935         }
936
937         if (data) {
938                 dlen = blocklen(data);
939                 data = padblock(data, hdrlen + TCP6_PKT);
940                 if (data == NULL)
941                         return NULL;
942         } else {
943                 dlen = 0;
944                 data = allocb(hdrlen + TCP6_PKT + 64);  /* the 64 pad is to meet mintu's */
945                 if (data == NULL)
946                         return NULL;
947                 data->wp += hdrlen + TCP6_PKT;
948         }
949
950         /* copy in pseudo ip header plus port numbers */
951         h = (Tcp6hdr *) (data->rp);
952         memmove(h, ph, TCP6_TCBPHDRSZ);
953
954         /* compose pseudo tcp header, do cksum calculation */
955         hnputl(h->vcf, hdrlen + dlen);
956         h->ploadlen[0] = h->ploadlen[1] = h->proto = 0;
957         h->ttl = ph->proto;
958
959         /* copy in variable bits */
960         hnputl(h->tcpseq, tcph->seq);
961         hnputl(h->tcpack, tcph->ack);
962         hnputs(h->tcpflag, (hdrlen << 10) | tcph->flags);
963         hnputs(h->tcpwin, tcph->wnd >> (tcb != NULL ? tcb->snd.scale : 0));
964         hnputs(h->tcpurg, tcph->urg);
965
966         if (tcph->flags & SYN) {
967                 opt = h->tcpopt;
968                 if (tcph->mss != 0) {
969                         *opt++ = MSSOPT;
970                         *opt++ = MSS_LENGTH;
971                         hnputs(opt, tcph->mss);
972                         opt += 2;
973                 }
974                 if (tcph->ws != 0) {
975                         *opt++ = WSOPT;
976                         *opt++ = WS_LENGTH;
977                         *opt++ = tcph->ws;
978                 }
979                 while (optpad-- > 0)
980                         *opt++ = NOOPOPT;
981         }
982
983         if (tcb != NULL && tcb->nochecksum) {
984                 h->tcpcksum[0] = h->tcpcksum[1] = 0;
985         } else {
986                 csum = ptclcsum(data, TCP6_IPLEN, hdrlen + dlen + TCP6_PHDRSIZE);
987                 hnputs(h->tcpcksum, csum);
988         }
989
990         /* move from pseudo header back to normal ip header */
991         memset(h->vcf, 0, 4);
992         h->vcf[0] = IP_VER6;
993         hnputs(h->ploadlen, hdrlen + dlen);
994         h->proto = ph->proto;
995
996         return data;
997 }
998
999 struct block *htontcp4(Tcp * tcph, struct block *data, Tcp4hdr * ph,
1000                                            Tcpctl * tcb)
1001 {
1002         int dlen;
1003         Tcp4hdr *h;
1004         uint16_t csum;
1005         uint16_t hdrlen, optpad = 0;
1006         uint8_t *opt;
1007
1008         hdrlen = TCP4_HDRSIZE;
1009         if (tcph->flags & SYN) {
1010                 if (tcph->mss)
1011                         hdrlen += MSS_LENGTH;
1012                 if (tcph->ws)
1013                         hdrlen += WS_LENGTH;
1014                 optpad = hdrlen & 3;
1015                 if (optpad)
1016                         optpad = 4 - optpad;
1017                 hdrlen += optpad;
1018         }
1019
1020         if (data) {
1021                 dlen = blocklen(data);
1022                 data = padblock(data, hdrlen + TCP4_PKT);
1023                 if (data == NULL)
1024                         return NULL;
1025         } else {
1026                 dlen = 0;
1027                 data = allocb(hdrlen + TCP4_PKT + 64);  /* the 64 pad is to meet mintu's */
1028                 if (data == NULL)
1029                         return NULL;
1030                 data->wp += hdrlen + TCP4_PKT;
1031         }
1032
1033         /* copy in pseudo ip header plus port numbers */
1034         h = (Tcp4hdr *) (data->rp);
1035         memmove(h, ph, TCP4_TCBPHDRSZ);
1036
1037         /* copy in variable bits */
1038         hnputs(h->tcplen, hdrlen + dlen);
1039         hnputl(h->tcpseq, tcph->seq);
1040         hnputl(h->tcpack, tcph->ack);
1041         hnputs(h->tcpflag, (hdrlen << 10) | tcph->flags);
1042         hnputs(h->tcpwin, tcph->wnd >> (tcb != NULL ? tcb->snd.scale : 0));
1043         hnputs(h->tcpurg, tcph->urg);
1044
1045         if (tcph->flags & SYN) {
1046                 opt = h->tcpopt;
1047                 if (tcph->mss != 0) {
1048                         *opt++ = MSSOPT;
1049                         *opt++ = MSS_LENGTH;
1050                         hnputs(opt, tcph->mss);
1051                         opt += 2;
1052                 }
1053                 if (tcph->ws != 0) {
1054                         *opt++ = WSOPT;
1055                         *opt++ = WS_LENGTH;
1056                         *opt++ = tcph->ws;
1057                 }
1058                 while (optpad-- > 0)
1059                         *opt++ = NOOPOPT;
1060         }
1061
1062         if (tcb != NULL && tcb->nochecksum) {
1063                 h->tcpcksum[0] = h->tcpcksum[1] = 0;
1064         } else {
1065                 csum = ptclcsum(data, TCP4_IPLEN, hdrlen + dlen + TCP4_PHDRSIZE);
1066                 hnputs(h->tcpcksum, csum);
1067         }
1068
1069         return data;
1070 }
1071
1072 int ntohtcp6(Tcp * tcph, struct block **bpp)
1073 {
1074         Tcp6hdr *h;
1075         uint8_t *optr;
1076         uint16_t hdrlen;
1077         uint16_t optlen;
1078         int n;
1079
1080         *bpp = pullupblock(*bpp, TCP6_PKT + TCP6_HDRSIZE);
1081         if (*bpp == NULL)
1082                 return -1;
1083
1084         h = (Tcp6hdr *) ((*bpp)->rp);
1085         tcph->source = nhgets(h->tcpsport);
1086         tcph->dest = nhgets(h->tcpdport);
1087         tcph->seq = nhgetl(h->tcpseq);
1088         tcph->ack = nhgetl(h->tcpack);
1089         hdrlen = (h->tcpflag[0] >> 2) & ~3;
1090         if (hdrlen < TCP6_HDRSIZE) {
1091                 freeblist(*bpp);
1092                 return -1;
1093         }
1094
1095         tcph->flags = h->tcpflag[1];
1096         tcph->wnd = nhgets(h->tcpwin);
1097         tcph->urg = nhgets(h->tcpurg);
1098         tcph->mss = 0;
1099         tcph->ws = 0;
1100         tcph->len = nhgets(h->ploadlen) - hdrlen;
1101
1102         *bpp = pullupblock(*bpp, hdrlen + TCP6_PKT);
1103         if (*bpp == NULL)
1104                 return -1;
1105
1106         optr = h->tcpopt;
1107         n = hdrlen - TCP6_HDRSIZE;
1108         while (n > 0 && *optr != EOLOPT) {
1109                 if (*optr == NOOPOPT) {
1110                         n--;
1111                         optr++;
1112                         continue;
1113                 }
1114                 optlen = optr[1];
1115                 if (optlen < 2 || optlen > n)
1116                         break;
1117                 switch (*optr) {
1118                         case MSSOPT:
1119                                 if (optlen == MSS_LENGTH)
1120                                         tcph->mss = nhgets(optr + 2);
1121                                 break;
1122                         case WSOPT:
1123                                 if (optlen == WS_LENGTH && *(optr + 2) <= 14)
1124                                         tcph->ws = HaveWS | *(optr + 2);
1125                                 break;
1126                 }
1127                 n -= optlen;
1128                 optr += optlen;
1129         }
1130         return hdrlen;
1131 }
1132
1133 int ntohtcp4(Tcp * tcph, struct block **bpp)
1134 {
1135         Tcp4hdr *h;
1136         uint8_t *optr;
1137         uint16_t hdrlen;
1138         uint16_t optlen;
1139         int n;
1140
1141         *bpp = pullupblock(*bpp, TCP4_PKT + TCP4_HDRSIZE);
1142         if (*bpp == NULL)
1143                 return -1;
1144
1145         h = (Tcp4hdr *) ((*bpp)->rp);
1146         tcph->source = nhgets(h->tcpsport);
1147         tcph->dest = nhgets(h->tcpdport);
1148         tcph->seq = nhgetl(h->tcpseq);
1149         tcph->ack = nhgetl(h->tcpack);
1150
1151         hdrlen = (h->tcpflag[0] >> 2) & ~3;
1152         if (hdrlen < TCP4_HDRSIZE) {
1153                 freeblist(*bpp);
1154                 return -1;
1155         }
1156
1157         tcph->flags = h->tcpflag[1];
1158         tcph->wnd = nhgets(h->tcpwin);
1159         tcph->urg = nhgets(h->tcpurg);
1160         tcph->mss = 0;
1161         tcph->ws = 0;
1162         tcph->len = nhgets(h->length) - (hdrlen + TCP4_PKT);
1163
1164         *bpp = pullupblock(*bpp, hdrlen + TCP4_PKT);
1165         if (*bpp == NULL)
1166                 return -1;
1167
1168         optr = h->tcpopt;
1169         n = hdrlen - TCP4_HDRSIZE;
1170         while (n > 0 && *optr != EOLOPT) {
1171                 if (*optr == NOOPOPT) {
1172                         n--;
1173                         optr++;
1174                         continue;
1175                 }
1176                 optlen = optr[1];
1177                 if (optlen < 2 || optlen > n)
1178                         break;
1179                 switch (*optr) {
1180                         case MSSOPT:
1181                                 if (optlen == MSS_LENGTH)
1182                                         tcph->mss = nhgets(optr + 2);
1183                                 break;
1184                         case WSOPT:
1185                                 if (optlen == WS_LENGTH && *(optr + 2) <= 14)
1186                                         tcph->ws = HaveWS | *(optr + 2);
1187                                 break;
1188                 }
1189                 n -= optlen;
1190                 optr += optlen;
1191         }
1192         return hdrlen;
1193 }
1194
1195 /*
1196  *  For outgiing calls, generate an initial sequence
1197  *  number and put a SYN on the send queue
1198  */
1199 void tcpsndsyn(struct conv *s, Tcpctl * tcb)
1200 {
1201         tcb->iss = (nrand(1 << 16) << 16) | nrand(1 << 16);
1202         tcb->rttseq = tcb->iss;
1203         tcb->snd.wl2 = tcb->iss;
1204         tcb->snd.una = tcb->iss;
1205         tcb->snd.ptr = tcb->rttseq;
1206         tcb->snd.nxt = tcb->rttseq;
1207         tcb->flgcnt++;
1208         tcb->flags |= FORCE;
1209         tcb->sndsyntime = NOW;
1210
1211         /* set desired mss and scale */
1212         tcb->mss = tcpmtu(s->p, s->laddr, s->ipversion, &tcb->scale);
1213 }
1214
1215 void
1216 sndrst(struct Proto *tcp, uint8_t * source, uint8_t * dest,
1217            uint16_t length, Tcp * seg, uint8_t version, char *reason)
1218 {
1219         struct block *hbp;
1220         uint8_t rflags;
1221         struct tcppriv *tpriv;
1222         Tcp4hdr ph4;
1223         Tcp6hdr ph6;
1224
1225         netlog(tcp->f, Logtcp, "sndrst: %s", reason);
1226
1227         tpriv = tcp->priv;
1228
1229         if (seg->flags & RST)
1230                 return;
1231
1232         /* make pseudo header */
1233         switch (version) {
1234                 case V4:
1235                         memset(&ph4, 0, sizeof(ph4));
1236                         ph4.vihl = IP_VER4;
1237                         v6tov4(ph4.tcpsrc, dest);
1238                         v6tov4(ph4.tcpdst, source);
1239                         ph4.proto = IP_TCPPROTO;
1240                         hnputs(ph4.tcplen, TCP4_HDRSIZE);
1241                         hnputs(ph4.tcpsport, seg->dest);
1242                         hnputs(ph4.tcpdport, seg->source);
1243                         break;
1244                 case V6:
1245                         memset(&ph6, 0, sizeof(ph6));
1246                         ph6.vcf[0] = IP_VER6;
1247                         ipmove(ph6.tcpsrc, dest);
1248                         ipmove(ph6.tcpdst, source);
1249                         ph6.proto = IP_TCPPROTO;
1250                         hnputs(ph6.ploadlen, TCP6_HDRSIZE);
1251                         hnputs(ph6.tcpsport, seg->dest);
1252                         hnputs(ph6.tcpdport, seg->source);
1253                         break;
1254                 default:
1255                         panic("sndrst: version %d", version);
1256         }
1257
1258         tpriv->stats[OutRsts]++;
1259         rflags = RST;
1260
1261         /* convince the other end that this reset is in band */
1262         if (seg->flags & ACK) {
1263                 seg->seq = seg->ack;
1264                 seg->ack = 0;
1265         } else {
1266                 rflags |= ACK;
1267                 seg->ack = seg->seq;
1268                 seg->seq = 0;
1269                 if (seg->flags & SYN)
1270                         seg->ack++;
1271                 seg->ack += length;
1272                 if (seg->flags & FIN)
1273                         seg->ack++;
1274         }
1275         seg->flags = rflags;
1276         seg->wnd = 0;
1277         seg->urg = 0;
1278         seg->mss = 0;
1279         seg->ws = 0;
1280         switch (version) {
1281                 case V4:
1282                         hbp = htontcp4(seg, NULL, &ph4, NULL);
1283                         if (hbp == NULL)
1284                                 return;
1285                         ipoput4(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1286                         break;
1287                 case V6:
1288                         hbp = htontcp6(seg, NULL, &ph6, NULL);
1289                         if (hbp == NULL)
1290                                 return;
1291                         ipoput6(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1292                         break;
1293                 default:
1294                         panic("sndrst2: version %d", version);
1295         }
1296 }
1297
1298 /*
1299  *  send a reset to the remote side and close the conversation
1300  *  called with s qlocked
1301  */
1302 char *tcphangup(struct conv *s)
1303 {
1304         ERRSTACK(2);
1305         Tcp seg;
1306         Tcpctl *tcb;
1307         struct block *hbp;
1308
1309         tcb = (Tcpctl *) s->ptcl;
1310         if (waserror()) {
1311                 poperror();
1312                 return commonerror();
1313         }
1314         if (ipcmp(s->raddr, IPnoaddr)) {
1315                 /* discard error style, poperror regardless */
1316                 if (!waserror()) {
1317                         seg.flags = RST | ACK;
1318                         seg.ack = tcb->rcv.nxt;
1319                         tcb->rcv.una = 0;
1320                         seg.seq = tcb->snd.ptr;
1321                         seg.wnd = 0;
1322                         seg.urg = 0;
1323                         seg.mss = 0;
1324                         seg.ws = 0;
1325                         switch (s->ipversion) {
1326                                 case V4:
1327                                         tcb->protohdr.tcp4hdr.vihl = IP_VER4;
1328                                         hbp = htontcp4(&seg, NULL, &tcb->protohdr.tcp4hdr, tcb);
1329                                         ipoput4(s->p->f, hbp, 0, s->ttl, s->tos, s);
1330                                         break;
1331                                 case V6:
1332                                         tcb->protohdr.tcp6hdr.vcf[0] = IP_VER6;
1333                                         hbp = htontcp6(&seg, NULL, &tcb->protohdr.tcp6hdr, tcb);
1334                                         ipoput6(s->p->f, hbp, 0, s->ttl, s->tos, s);
1335                                         break;
1336                                 default:
1337                                         panic("tcphangup: version %d", s->ipversion);
1338                         }
1339                 }
1340                 poperror();
1341         }
1342         localclose(s, NULL);
1343         poperror();
1344         return NULL;
1345 }
1346
1347 /*
1348  *  (re)send a SYN ACK
1349  */
1350 int sndsynack(struct Proto *tcp, Limbo * lp)
1351 {
1352         struct block *hbp;
1353         Tcp4hdr ph4;
1354         Tcp6hdr ph6;
1355         Tcp seg;
1356         int scale;
1357
1358         /* make pseudo header */
1359         switch (lp->version) {
1360                 case V4:
1361                         memset(&ph4, 0, sizeof(ph4));
1362                         ph4.vihl = IP_VER4;
1363                         v6tov4(ph4.tcpsrc, lp->laddr);
1364                         v6tov4(ph4.tcpdst, lp->raddr);
1365                         ph4.proto = IP_TCPPROTO;
1366                         hnputs(ph4.tcplen, TCP4_HDRSIZE);
1367                         hnputs(ph4.tcpsport, lp->lport);
1368                         hnputs(ph4.tcpdport, lp->rport);
1369                         break;
1370                 case V6:
1371                         memset(&ph6, 0, sizeof(ph6));
1372                         ph6.vcf[0] = IP_VER6;
1373                         ipmove(ph6.tcpsrc, lp->laddr);
1374                         ipmove(ph6.tcpdst, lp->raddr);
1375                         ph6.proto = IP_TCPPROTO;
1376                         hnputs(ph6.ploadlen, TCP6_HDRSIZE);
1377                         hnputs(ph6.tcpsport, lp->lport);
1378                         hnputs(ph6.tcpdport, lp->rport);
1379                         break;
1380                 default:
1381                         panic("sndrst: version %d", lp->version);
1382         }
1383
1384         seg.seq = lp->iss;
1385         seg.ack = lp->irs + 1;
1386         seg.flags = SYN | ACK;
1387         seg.urg = 0;
1388         seg.mss = tcpmtu(tcp, lp->laddr, lp->version, &scale);
1389         seg.wnd = QMAX;
1390
1391         /* if the other side set scale, we should too */
1392         if (lp->rcvscale) {
1393                 seg.ws = scale;
1394                 lp->sndscale = scale;
1395         } else {
1396                 seg.ws = 0;
1397                 lp->sndscale = 0;
1398         }
1399
1400         switch (lp->version) {
1401                 case V4:
1402                         hbp = htontcp4(&seg, NULL, &ph4, NULL);
1403                         if (hbp == NULL)
1404                                 return -1;
1405                         ipoput4(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1406                         break;
1407                 case V6:
1408                         hbp = htontcp6(&seg, NULL, &ph6, NULL);
1409                         if (hbp == NULL)
1410                                 return -1;
1411                         ipoput6(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1412                         break;
1413                 default:
1414                         panic("sndsnack: version %d", lp->version);
1415         }
1416         lp->lastsend = NOW;
1417         return 0;
1418 }
1419
1420 #define hashipa(a, p) ( ( (a)[IPaddrlen-2] + (a)[IPaddrlen-1] + p )&LHTMASK )
1421
1422 /*
1423  *  put a call into limbo and respond with a SYN ACK
1424  *
1425  *  called with proto locked
1426  */
1427 static void
1428 limbo(struct conv *s, uint8_t * source, uint8_t * dest, Tcp * seg, int version)
1429 {
1430         Limbo *lp, **l;
1431         struct tcppriv *tpriv;
1432         int h;
1433
1434         tpriv = s->p->priv;
1435         h = hashipa(source, seg->source);
1436
1437         for (l = &tpriv->lht[h]; *l != NULL; l = &lp->next) {
1438                 lp = *l;
1439                 if (lp->lport != seg->dest || lp->rport != seg->source
1440                         || lp->version != version)
1441                         continue;
1442                 if (ipcmp(lp->raddr, source) != 0)
1443                         continue;
1444                 if (ipcmp(lp->laddr, dest) != 0)
1445                         continue;
1446
1447                 /* each new SYN restarts the retransmits */
1448                 lp->irs = seg->seq;
1449                 break;
1450         }
1451         lp = *l;
1452         if (lp == NULL) {
1453                 if (tpriv->nlimbo >= Maxlimbo && tpriv->lht[h]) {
1454                         lp = tpriv->lht[h];
1455                         tpriv->lht[h] = lp->next;
1456                         lp->next = NULL;
1457                 } else {
1458                         lp = kzmalloc(sizeof(*lp), 0);
1459                         if (lp == NULL)
1460                                 return;
1461                         tpriv->nlimbo++;
1462                 }
1463                 *l = lp;
1464                 lp->version = version;
1465                 ipmove(lp->laddr, dest);
1466                 ipmove(lp->raddr, source);
1467                 lp->lport = seg->dest;
1468                 lp->rport = seg->source;
1469                 lp->mss = seg->mss;
1470                 lp->rcvscale = seg->ws;
1471                 lp->irs = seg->seq;
1472                 lp->iss = (nrand(1 << 16) << 16) | nrand(1 << 16);
1473         }
1474
1475         if (sndsynack(s->p, lp) < 0) {
1476                 *l = lp->next;
1477                 tpriv->nlimbo--;
1478                 kfree(lp);
1479         }
1480 }
1481
1482 /*
1483  *  resend SYN ACK's once every SYNACK_RXTIMER ms.
1484  */
1485 static void limborexmit(struct Proto *tcp)
1486 {
1487         struct tcppriv *tpriv;
1488         Limbo **l, *lp;
1489         int h;
1490         int seen;
1491         uint32_t now;
1492
1493         tpriv = tcp->priv;
1494
1495         if (!canqlock(&tcp->qlock))
1496                 return;
1497         seen = 0;
1498         now = NOW;
1499         for (h = 0; h < NLHT && seen < tpriv->nlimbo; h++) {
1500                 for (l = &tpriv->lht[h]; *l != NULL && seen < tpriv->nlimbo;) {
1501                         lp = *l;
1502                         seen++;
1503                         if (now - lp->lastsend < (lp->rexmits + 1) * SYNACK_RXTIMER)
1504                                 continue;
1505
1506                         /* time it out after 1 second */
1507                         if (++(lp->rexmits) > 5) {
1508                                 tpriv->nlimbo--;
1509                                 *l = lp->next;
1510                                 kfree(lp);
1511                                 continue;
1512                         }
1513
1514                         /* if we're being attacked, don't bother resending SYN ACK's */
1515                         if (tpriv->nlimbo > 100)
1516                                 continue;
1517
1518                         if (sndsynack(tcp, lp) < 0) {
1519                                 tpriv->nlimbo--;
1520                                 *l = lp->next;
1521                                 kfree(lp);
1522                                 continue;
1523                         }
1524
1525                         l = &lp->next;
1526                 }
1527         }
1528         qunlock(&tcp->qlock);
1529 }
1530
1531 /*
1532  *  lookup call in limbo.  if found, throw it out.
1533  *
1534  *  called with proto locked
1535  */
1536 static void
1537 limborst(struct conv *s, Tcp * segp, uint8_t * src, uint8_t * dst,
1538                  uint8_t version)
1539 {
1540         Limbo *lp, **l;
1541         int h;
1542         struct tcppriv *tpriv;
1543
1544         tpriv = s->p->priv;
1545
1546         /* find a call in limbo */
1547         h = hashipa(src, segp->source);
1548         for (l = &tpriv->lht[h]; *l != NULL; l = &lp->next) {
1549                 lp = *l;
1550                 if (lp->lport != segp->dest || lp->rport != segp->source
1551                         || lp->version != version)
1552                         continue;
1553                 if (ipcmp(lp->laddr, dst) != 0)
1554                         continue;
1555                 if (ipcmp(lp->raddr, src) != 0)
1556                         continue;
1557
1558                 /* RST can only follow the SYN */
1559                 if (segp->seq == lp->irs + 1) {
1560                         tpriv->nlimbo--;
1561                         *l = lp->next;
1562                         kfree(lp);
1563                 }
1564                 break;
1565         }
1566 }
1567
1568 /*
1569  *  come here when we finally get an ACK to our SYN-ACK.
1570  *  lookup call in limbo.  if found, create a new conversation
1571  *
1572  *  called with proto locked
1573  */
1574 static struct conv *tcpincoming(struct conv *s, Tcp * segp, uint8_t * src,
1575                                                                 uint8_t * dst, uint8_t version)
1576 {
1577         struct conv *new;
1578         Tcpctl *tcb;
1579         struct tcppriv *tpriv;
1580         Tcp4hdr *h4;
1581         Tcp6hdr *h6;
1582         Limbo *lp, **l;
1583         int h;
1584
1585         /* unless it's just an ack, it can't be someone coming out of limbo */
1586         if ((segp->flags & SYN) || (segp->flags & ACK) == 0)
1587                 return NULL;
1588
1589         tpriv = s->p->priv;
1590
1591         /* find a call in limbo */
1592         h = hashipa(src, segp->source);
1593         for (l = &tpriv->lht[h]; (lp = *l) != NULL; l = &lp->next) {
1594                 netlog(s->p->f, Logtcp,
1595                            "tcpincoming s %I,0x%x/%I,0x%x d %I,0x%x/%I,0x%x v %d/%d", src,
1596                            segp->source, lp->raddr, lp->rport, dst, segp->dest, lp->laddr,
1597                            lp->lport, version, lp->version);
1598
1599                 if (lp->lport != segp->dest || lp->rport != segp->source
1600                         || lp->version != version)
1601                         continue;
1602                 if (ipcmp(lp->laddr, dst) != 0)
1603                         continue;
1604                 if (ipcmp(lp->raddr, src) != 0)
1605                         continue;
1606
1607                 /* we're assuming no data with the initial SYN */
1608                 if (segp->seq != lp->irs + 1 || segp->ack != lp->iss + 1) {
1609                         netlog(s->p->f, Logtcp, "tcpincoming s 0x%lx/0x%lx a 0x%lx 0x%lx",
1610                                    segp->seq, lp->irs + 1, segp->ack, lp->iss + 1);
1611                         lp = NULL;
1612                 } else {
1613                         tpriv->nlimbo--;
1614                         *l = lp->next;
1615                 }
1616                 break;
1617         }
1618         if (lp == NULL)
1619                 return NULL;
1620
1621         new = Fsnewcall(s, src, segp->source, dst, segp->dest, version);
1622         if (new == NULL)
1623                 return NULL;
1624
1625         memmove(new->ptcl, s->ptcl, sizeof(Tcpctl));
1626         tcb = (Tcpctl *) new->ptcl;
1627         tcb->flags &= ~CLONE;
1628         tcb->timer.arg = new;
1629         tcb->timer.state = TcptimerOFF;
1630         tcb->acktimer.arg = new;
1631         tcb->acktimer.state = TcptimerOFF;
1632         tcb->katimer.arg = new;
1633         tcb->katimer.state = TcptimerOFF;
1634         tcb->rtt_timer.arg = new;
1635         tcb->rtt_timer.state = TcptimerOFF;
1636
1637         tcb->irs = lp->irs;
1638         tcb->rcv.nxt = tcb->irs + 1;
1639         tcb->rcv.urg = tcb->rcv.nxt;
1640
1641         tcb->iss = lp->iss;
1642         tcb->rttseq = tcb->iss;
1643         tcb->snd.wl2 = tcb->iss;
1644         tcb->snd.una = tcb->iss + 1;
1645         tcb->snd.ptr = tcb->iss + 1;
1646         tcb->snd.nxt = tcb->iss + 1;
1647         tcb->flgcnt = 0;
1648         tcb->flags |= SYNACK;
1649
1650         /* our sending max segment size cannot be bigger than what he asked for */
1651         if (lp->mss != 0 && lp->mss < tcb->mss)
1652                 tcb->mss = lp->mss;
1653
1654         /* window scaling */
1655         tcpsetscale(new, tcb, lp->rcvscale, lp->sndscale);
1656
1657         /* the congestion window always starts out as a single segment */
1658         tcb->snd.wnd = segp->wnd;
1659         tcb->cwind = tcb->mss;
1660
1661         /* set initial round trip time */
1662         tcb->sndsyntime = lp->lastsend + lp->rexmits * SYNACK_RXTIMER;
1663         tcpsynackrtt(new);
1664
1665         kfree(lp);
1666
1667         /* set up proto header */
1668         switch (version) {
1669                 case V4:
1670                         h4 = &tcb->protohdr.tcp4hdr;
1671                         memset(h4, 0, sizeof(*h4));
1672                         h4->proto = IP_TCPPROTO;
1673                         hnputs(h4->tcpsport, new->lport);
1674                         hnputs(h4->tcpdport, new->rport);
1675                         v6tov4(h4->tcpsrc, dst);
1676                         v6tov4(h4->tcpdst, src);
1677                         break;
1678                 case V6:
1679                         h6 = &tcb->protohdr.tcp6hdr;
1680                         memset(h6, 0, sizeof(*h6));
1681                         h6->proto = IP_TCPPROTO;
1682                         hnputs(h6->tcpsport, new->lport);
1683                         hnputs(h6->tcpdport, new->rport);
1684                         ipmove(h6->tcpsrc, dst);
1685                         ipmove(h6->tcpdst, src);
1686                         break;
1687                 default:
1688                         panic("tcpincoming: version %d", new->ipversion);
1689         }
1690
1691         tcpsetstate(new, Established);
1692
1693         iphtadd(&tpriv->ht, new);
1694
1695         return new;
1696 }
1697
1698 int seq_within(uint32_t x, uint32_t low, uint32_t high)
1699 {
1700         if (low <= high) {
1701                 if (low <= x && x <= high)
1702                         return 1;
1703         } else {
1704                 if (x >= low || x <= high)
1705                         return 1;
1706         }
1707         return 0;
1708 }
1709
1710 int seq_lt(uint32_t x, uint32_t y)
1711 {
1712         return (int)(x - y) < 0;
1713 }
1714
1715 int seq_le(uint32_t x, uint32_t y)
1716 {
1717         return (int)(x - y) <= 0;
1718 }
1719
1720 int seq_gt(uint32_t x, uint32_t y)
1721 {
1722         return (int)(x - y) > 0;
1723 }
1724
1725 int seq_ge(uint32_t x, uint32_t y)
1726 {
1727         return (int)(x - y) >= 0;
1728 }
1729
1730 /*
1731  *  use the time between the first SYN and it's ack as the
1732  *  initial round trip time
1733  */
1734 void tcpsynackrtt(struct conv *s)
1735 {
1736         Tcpctl *tcb;
1737         int delta;
1738         struct tcppriv *tpriv;
1739
1740         tcb = (Tcpctl *) s->ptcl;
1741         tpriv = s->p->priv;
1742
1743         delta = NOW - tcb->sndsyntime;
1744         tcb->srtt = delta << LOGAGAIN;
1745         tcb->mdev = delta << LOGDGAIN;
1746
1747         /* halt round trip timer */
1748         tcphalt(tpriv, &tcb->rtt_timer);
1749 }
1750
1751 void update(struct conv *s, Tcp * seg)
1752 {
1753         int rtt, delta;
1754         Tcpctl *tcb;
1755         uint32_t acked;
1756         uint32_t expand;
1757         struct tcppriv *tpriv;
1758
1759         tpriv = s->p->priv;
1760         tcb = (Tcpctl *) s->ptcl;
1761
1762         /* if everything has been acked, force output(?) */
1763         if (seq_gt(seg->ack, tcb->snd.nxt)) {
1764                 tcb->flags |= FORCE;
1765                 return;
1766         }
1767
1768         /* added by Dong Lin for fast retransmission */
1769         if (seg->ack == tcb->snd.una
1770                 && tcb->snd.una != tcb->snd.nxt
1771                 && seg->len == 0 && seg->wnd == tcb->snd.wnd) {
1772
1773                 /* this is a pure ack w/o window update */
1774                 netlog(s->p->f, Logtcprxmt, "dupack %lu ack %lu sndwnd %d advwin %d\n",
1775                            tcb->snd.dupacks, seg->ack, tcb->snd.wnd, seg->wnd);
1776
1777                 if (++tcb->snd.dupacks == TCPREXMTTHRESH) {
1778                         /*
1779                          *  tahoe tcp rxt the packet, half sshthresh,
1780                          *  and set cwnd to one packet
1781                          */
1782                         tcb->snd.recovery = 1;
1783                         tcb->snd.rxt = tcb->snd.nxt;
1784                         netlog(s->p->f, Logtcprxmt, "fast rxt %lu, nxt %lu\n", tcb->snd.una,
1785                                    tcb->snd.nxt);
1786                         tcprxmit(s);
1787                 } else {
1788                         /* do reno tcp here. */
1789                 }
1790         }
1791
1792         /*
1793          *  update window
1794          */
1795         if (seq_gt(seg->ack, tcb->snd.wl2)
1796                 || (tcb->snd.wl2 == seg->ack && seg->wnd > tcb->snd.wnd)) {
1797                 tcb->snd.wnd = seg->wnd;
1798                 tcb->snd.wl2 = seg->ack;
1799         }
1800
1801         if (!seq_gt(seg->ack, tcb->snd.una)) {
1802                 /*
1803                  *  don't let us hangup if sending into a closed window and
1804                  *  we're still getting acks
1805                  */
1806                 if ((tcb->flags & RETRAN) && tcb->snd.wnd == 0) {
1807                         tcb->backedoff = MAXBACKMS / 4;
1808                 }
1809                 return;
1810         }
1811
1812         /*
1813          *  any positive ack turns off fast rxt,
1814          *  (should we do new-reno on partial acks?)
1815          */
1816         if (!tcb->snd.recovery || seq_ge(seg->ack, tcb->snd.rxt)) {
1817                 tcb->snd.dupacks = 0;
1818                 tcb->snd.recovery = 0;
1819         } else
1820                 netlog(s->p->f, Logtcp, "rxt next %lu, cwin %u\n", seg->ack,
1821                            tcb->cwind);
1822
1823         /* Compute the new send window size */
1824         acked = seg->ack - tcb->snd.una;
1825
1826         /* avoid slow start and timers for SYN acks */
1827         if ((tcb->flags & SYNACK) == 0) {
1828                 tcb->flags |= SYNACK;
1829                 acked--;
1830                 tcb->flgcnt--;
1831                 goto done;
1832         }
1833
1834         /* slow start as long as we're not recovering from lost packets */
1835         if (tcb->cwind < tcb->snd.wnd && !tcb->snd.recovery) {
1836                 if (tcb->cwind < tcb->ssthresh) {
1837                         expand = tcb->mss;
1838                         if (acked < expand)
1839                                 expand = acked;
1840                 } else
1841                         expand = ((int)tcb->mss * tcb->mss) / tcb->cwind;
1842
1843                 if (tcb->cwind + expand < tcb->cwind)
1844                         expand = tcb->snd.wnd - tcb->cwind;
1845                 if (tcb->cwind + expand > tcb->snd.wnd)
1846                         expand = tcb->snd.wnd - tcb->cwind;
1847                 tcb->cwind += expand;
1848         }
1849
1850         /* Adjust the timers according to the round trip time */
1851         if (tcb->rtt_timer.state == TcptimerON && seq_ge(seg->ack, tcb->rttseq)) {
1852                 tcphalt(tpriv, &tcb->rtt_timer);
1853                 if ((tcb->flags & RETRAN) == 0) {
1854                         tcb->backoff = 0;
1855                         tcb->backedoff = 0;
1856                         rtt = tcb->rtt_timer.start - tcb->rtt_timer.count;
1857                         if (rtt == 0)
1858                                 rtt = 1;        /* otherwise all close systems will rexmit in 0 time */
1859                         rtt *= MSPTICK;
1860                         if (tcb->srtt == 0) {
1861                                 tcb->srtt = rtt << LOGAGAIN;
1862                                 tcb->mdev = rtt << LOGDGAIN;
1863                         } else {
1864                                 delta = rtt - (tcb->srtt >> LOGAGAIN);
1865                                 tcb->srtt += delta;
1866                                 if (tcb->srtt <= 0)
1867                                         tcb->srtt = 1;
1868
1869                                 delta = abs(delta) - (tcb->mdev >> LOGDGAIN);
1870                                 tcb->mdev += delta;
1871                                 if (tcb->mdev <= 0)
1872                                         tcb->mdev = 1;
1873                         }
1874                         tcpsettimer(tcb);
1875                 }
1876         }
1877
1878 done:
1879         if (qdiscard(s->wq, acked) < acked)
1880                 tcb->flgcnt--;
1881
1882         tcb->snd.una = seg->ack;
1883         if (seq_gt(seg->ack, tcb->snd.urg))
1884                 tcb->snd.urg = seg->ack;
1885
1886         if (tcb->snd.una != tcb->snd.nxt)
1887                 tcpgo(tpriv, &tcb->timer);
1888         else
1889                 tcphalt(tpriv, &tcb->timer);
1890
1891         if (seq_lt(tcb->snd.ptr, tcb->snd.una))
1892                 tcb->snd.ptr = tcb->snd.una;
1893
1894         tcb->flags &= ~RETRAN;
1895         tcb->backoff = 0;
1896         tcb->backedoff = 0;
1897 }
1898
1899 void tcpiput(struct Proto *tcp, struct Ipifc *unused, struct block *bp)
1900 {
1901         ERRSTACK(1);
1902         Tcp seg;
1903         Tcp4hdr *h4;
1904         Tcp6hdr *h6;
1905         int hdrlen;
1906         Tcpctl *tcb;
1907         uint16_t length;
1908         uint8_t source[IPaddrlen], dest[IPaddrlen];
1909         struct conv *s;
1910         struct Fs *f;
1911         struct tcppriv *tpriv;
1912         uint8_t version;
1913
1914         f = tcp->f;
1915         tpriv = tcp->priv;
1916
1917         tpriv->stats[InSegs]++;
1918
1919         h4 = (Tcp4hdr *) (bp->rp);
1920         h6 = (Tcp6hdr *) (bp->rp);
1921
1922         if ((h4->vihl & 0xF0) == IP_VER4) {
1923                 version = V4;
1924                 length = nhgets(h4->length);
1925                 v4tov6(dest, h4->tcpdst);
1926                 v4tov6(source, h4->tcpsrc);
1927
1928                 h4->Unused = 0;
1929                 hnputs(h4->tcplen, length - TCP4_PKT);
1930                 if (!(bp->flag & Btcpck) && (h4->tcpcksum[0] || h4->tcpcksum[1]) &&
1931                         ptclcsum(bp, TCP4_IPLEN, length - TCP4_IPLEN)) {
1932                         tpriv->stats[CsumErrs]++;
1933                         tpriv->stats[InErrs]++;
1934                         netlog(f, Logtcp, "bad tcp proto cksum\n");
1935                         freeblist(bp);
1936                         return;
1937                 }
1938
1939                 hdrlen = ntohtcp4(&seg, &bp);
1940                 if (hdrlen < 0) {
1941                         tpriv->stats[HlenErrs]++;
1942                         tpriv->stats[InErrs]++;
1943                         netlog(f, Logtcp, "bad tcp hdr len\n");
1944                         return;
1945                 }
1946
1947                 /* trim the packet to the size claimed by the datagram */
1948                 length -= hdrlen + TCP4_PKT;
1949                 bp = trimblock(bp, hdrlen + TCP4_PKT, length);
1950                 if (bp == NULL) {
1951                         tpriv->stats[LenErrs]++;
1952                         tpriv->stats[InErrs]++;
1953                         netlog(f, Logtcp, "tcp len < 0 after trim\n");
1954                         return;
1955                 }
1956         } else {
1957                 int ttl = h6->ttl;
1958                 int proto = h6->proto;
1959
1960                 version = V6;
1961                 length = nhgets(h6->ploadlen);
1962                 ipmove(dest, h6->tcpdst);
1963                 ipmove(source, h6->tcpsrc);
1964
1965                 h6->ploadlen[0] = h6->ploadlen[1] = h6->proto = 0;
1966                 h6->ttl = proto;
1967                 hnputl(h6->vcf, length);
1968                 if ((h6->tcpcksum[0] || h6->tcpcksum[1]) &&
1969                         ptclcsum(bp, TCP6_IPLEN, length + TCP6_PHDRSIZE)) {
1970                         tpriv->stats[CsumErrs]++;
1971                         tpriv->stats[InErrs]++;
1972                         netlog(f, Logtcp, "bad tcp proto cksum\n");
1973                         freeblist(bp);
1974                         return;
1975                 }
1976                 h6->ttl = ttl;
1977                 h6->proto = proto;
1978                 hnputs(h6->ploadlen, length);
1979
1980                 hdrlen = ntohtcp6(&seg, &bp);
1981                 if (hdrlen < 0) {
1982                         tpriv->stats[HlenErrs]++;
1983                         tpriv->stats[InErrs]++;
1984                         netlog(f, Logtcp, "bad tcp hdr len\n");
1985                         return;
1986                 }
1987
1988                 /* trim the packet to the size claimed by the datagram */
1989                 length -= hdrlen;
1990                 bp = trimblock(bp, hdrlen + TCP6_PKT, length);
1991                 if (bp == NULL) {
1992                         tpriv->stats[LenErrs]++;
1993                         tpriv->stats[InErrs]++;
1994                         netlog(f, Logtcp, "tcp len < 0 after trim\n");
1995                         return;
1996                 }
1997         }
1998
1999         /* lock protocol while searching for a conversation */
2000         qlock(&tcp->qlock);
2001
2002         /* Look for a matching conversation */
2003         s = iphtlook(&tpriv->ht, source, seg.source, dest, seg.dest);
2004         if (s == NULL) {
2005                 netlog(f, Logtcp, "iphtlook failed");
2006 reset:
2007                 qunlock(&tcp->qlock);
2008                 sndrst(tcp, source, dest, length, &seg, version, "no conversation");
2009                 freeblist(bp);
2010                 return;
2011         }
2012
2013         /* if it's a listener, look for the right flags and get a new conv */
2014         tcb = (Tcpctl *) s->ptcl;
2015         if (tcb->state == Listen) {
2016                 if (seg.flags & RST) {
2017                         limborst(s, &seg, source, dest, version);
2018                         qunlock(&tcp->qlock);
2019                         freeblist(bp);
2020                         return;
2021                 }
2022
2023                 /* if this is a new SYN, put the call into limbo */
2024                 if ((seg.flags & SYN) && (seg.flags & ACK) == 0) {
2025                         limbo(s, source, dest, &seg, version);
2026                         qunlock(&tcp->qlock);
2027                         freeblist(bp);
2028                         return;
2029                 }
2030
2031                 /*
2032                  *  if there's a matching call in limbo, tcpincoming will
2033                  *  return it in state Syn_received
2034                  */
2035                 s = tcpincoming(s, &seg, source, dest, version);
2036                 if (s == NULL)
2037                         goto reset;
2038         }
2039
2040         /* The rest of the input state machine is run with the control block
2041          * locked and implements the state machine directly out of the RFC.
2042          * Out-of-band data is ignored - it was always a bad idea.
2043          */
2044         tcb = (Tcpctl *) s->ptcl;
2045         if (waserror()) {
2046                 qunlock(&s->qlock);
2047                 nexterror();
2048         }
2049         qlock(&s->qlock);
2050         qunlock(&tcp->qlock);
2051
2052         /* fix up window */
2053         seg.wnd <<= tcb->rcv.scale;
2054
2055         /* every input packet in puts off the keep alive time out */
2056         tcpsetkacounter(tcb);
2057
2058         switch (tcb->state) {
2059                 case Closed:
2060                         sndrst(tcp, source, dest, length, &seg, version,
2061                                    "sending to Closed");
2062                         goto raise;
2063                 case Syn_sent:
2064                         if (seg.flags & ACK) {
2065                                 if (!seq_within(seg.ack, tcb->iss + 1, tcb->snd.nxt)) {
2066                                         sndrst(tcp, source, dest, length, &seg, version,
2067                                                    "bad seq in Syn_sent");
2068                                         goto raise;
2069                                 }
2070                         }
2071                         if (seg.flags & RST) {
2072                                 if (seg.flags & ACK)
2073                                         localclose(s, Econrefused);
2074                                 goto raise;
2075                         }
2076
2077                         if (seg.flags & SYN) {
2078                                 procsyn(s, &seg);
2079                                 if (seg.flags & ACK) {
2080                                         update(s, &seg);
2081                                         tcpsynackrtt(s);
2082                                         tcpsetstate(s, Established);
2083                                         tcpsetscale(s, tcb, seg.ws, tcb->scale);
2084                                 } else {
2085                                         tcb->time = NOW;
2086                                         tcpsetstate(s, Syn_received);   /* DLP - shouldn't this be a reset? */
2087                                 }
2088
2089                                 if (length != 0 || (seg.flags & FIN))
2090                                         break;
2091
2092                                 freeblist(bp);
2093                                 goto output;
2094                         } else
2095                                 freeblist(bp);
2096
2097                         qunlock(&s->qlock);
2098                         poperror();
2099                         return;
2100                 case Syn_received:
2101                         /* doesn't matter if it's the correct ack, we're just trying to set timing */
2102                         if (seg.flags & ACK)
2103                                 tcpsynackrtt(s);
2104                         break;
2105         }
2106
2107         /*
2108          *  One DOS attack is to open connections to us and then forget about them,
2109          *  thereby tying up a conv at no long term cost to the attacker.
2110          *  This is an attempt to defeat these stateless DOS attacks.  See
2111          *  corresponding code in tcpsendka().
2112          */
2113         if (tcb->state != Syn_received && (seg.flags & RST) == 0) {
2114                 if (tcpporthogdefense
2115                         && seq_within(seg.ack, tcb->snd.una - (1 << 31),
2116                                                   tcb->snd.una - (1 << 29))) {
2117                         printd("stateless hog %I.%d->%I.%d f 0x%x 0x%lx - 0x%lx - 0x%lx\n",
2118                                    source, seg.source, dest, seg.dest, seg.flags,
2119                                    tcb->snd.una - (1 << 31), seg.ack, tcb->snd.una - (1 << 29));
2120                         localclose(s, "stateless hog");
2121                 }
2122         }
2123
2124         /* Cut the data to fit the receive window */
2125         if (tcptrim(tcb, &seg, &bp, &length) == -1) {
2126                 netlog(f, Logtcp, "tcp len < 0, %lu %d\n", seg.seq, length);
2127                 update(s, &seg);
2128                 if (qlen(s->wq) + tcb->flgcnt == 0 && tcb->state == Closing) {
2129                         tcphalt(tpriv, &tcb->rtt_timer);
2130                         tcphalt(tpriv, &tcb->acktimer);
2131                         tcphalt(tpriv, &tcb->katimer);
2132                         tcpsetstate(s, Time_wait);
2133                         tcb->timer.start = MSL2 * (1000 / MSPTICK);
2134                         tcpgo(tpriv, &tcb->timer);
2135                 }
2136                 if (!(seg.flags & RST)) {
2137                         tcb->flags |= FORCE;
2138                         goto output;
2139                 }
2140                 qunlock(&s->qlock);
2141                 poperror();
2142                 return;
2143         }
2144
2145         /* Cannot accept so answer with a rst */
2146         if (length && tcb->state == Closed) {
2147                 sndrst(tcp, source, dest, length, &seg, version, "sending to Closed");
2148                 goto raise;
2149         }
2150
2151         /* The segment is beyond the current receive pointer so
2152          * queue the data in the resequence queue
2153          */
2154         if (seg.seq != tcb->rcv.nxt)
2155                 if (length != 0 || (seg.flags & (SYN | FIN))) {
2156                         update(s, &seg);
2157                         if (addreseq(tcb, tpriv, &seg, bp, length) < 0)
2158                                 printd("reseq %I.%d -> %I.%d\n", s->raddr, s->rport, s->laddr,
2159                                            s->lport);
2160                         tcb->flags |= FORCE;
2161                         goto output;
2162                 }
2163
2164         /*
2165          *  keep looping till we've processed this packet plus any
2166          *  adjacent packets in the resequence queue
2167          */
2168         for (;;) {
2169                 if (seg.flags & RST) {
2170                         if (tcb->state == Established) {
2171                                 tpriv->stats[EstabResets]++;
2172                                 if (tcb->rcv.nxt != seg.seq)
2173                                         printd
2174                                                 ("out of order RST rcvd: %I.%d -> %I.%d, rcv.nxt 0x%lx seq 0x%lx\n",
2175                                                  s->raddr, s->rport, s->laddr, s->lport, tcb->rcv.nxt,
2176                                                  seg.seq);
2177                         }
2178                         localclose(s, Econrefused);
2179                         goto raise;
2180                 }
2181
2182                 if ((seg.flags & ACK) == 0)
2183                         goto raise;
2184
2185                 switch (tcb->state) {
2186                         case Syn_received:
2187                                 if (!seq_within(seg.ack, tcb->snd.una + 1, tcb->snd.nxt)) {
2188                                         sndrst(tcp, source, dest, length, &seg, version,
2189                                                    "bad seq in Syn_received");
2190                                         goto raise;
2191                                 }
2192                                 update(s, &seg);
2193                                 tcpsetstate(s, Established);
2194                         case Established:
2195                         case Close_wait:
2196                                 update(s, &seg);
2197                                 break;
2198                         case Finwait1:
2199                                 update(s, &seg);
2200                                 if (qlen(s->wq) + tcb->flgcnt == 0) {
2201                                         tcphalt(tpriv, &tcb->rtt_timer);
2202                                         tcphalt(tpriv, &tcb->acktimer);
2203                                         tcpsetkacounter(tcb);
2204                                         tcb->time = NOW;
2205                                         tcpsetstate(s, Finwait2);
2206                                         tcb->katimer.start = MSL2 * (1000 / MSPTICK);
2207                                         tcpgo(tpriv, &tcb->katimer);
2208                                 }
2209                                 break;
2210                         case Finwait2:
2211                                 update(s, &seg);
2212                                 break;
2213                         case Closing:
2214                                 update(s, &seg);
2215                                 if (qlen(s->wq) + tcb->flgcnt == 0) {
2216                                         tcphalt(tpriv, &tcb->rtt_timer);
2217                                         tcphalt(tpriv, &tcb->acktimer);
2218                                         tcphalt(tpriv, &tcb->katimer);
2219                                         tcpsetstate(s, Time_wait);
2220                                         tcb->timer.start = MSL2 * (1000 / MSPTICK);
2221                                         tcpgo(tpriv, &tcb->timer);
2222                                 }
2223                                 break;
2224                         case Last_ack:
2225                                 update(s, &seg);
2226                                 if (qlen(s->wq) + tcb->flgcnt == 0) {
2227                                         localclose(s, NULL);
2228                                         goto raise;
2229                                 }
2230                         case Time_wait:
2231                                 tcb->flags |= FORCE;
2232                                 if (tcb->timer.state != TcptimerON)
2233                                         tcpgo(tpriv, &tcb->timer);
2234                 }
2235
2236                 if ((seg.flags & URG) && seg.urg) {
2237                         if (seq_gt(seg.urg + seg.seq, tcb->rcv.urg)) {
2238                                 tcb->rcv.urg = seg.urg + seg.seq;
2239                                 pullblock(&bp, seg.urg);
2240                         }
2241                 } else if (seq_gt(tcb->rcv.nxt, tcb->rcv.urg))
2242                         tcb->rcv.urg = tcb->rcv.nxt;
2243
2244                 if (length == 0) {
2245                         if (bp != NULL)
2246                                 freeblist(bp);
2247                 } else {
2248                         switch (tcb->state) {
2249                                 default:
2250                                         /* Ignore segment text */
2251                                         if (bp != NULL)
2252                                                 freeblist(bp);
2253                                         break;
2254
2255                                 case Syn_received:
2256                                 case Established:
2257                                 case Finwait1:
2258                                         /* If we still have some data place on
2259                                          * receive queue
2260                                          */
2261                                         if (bp) {
2262                                                 bp = packblock(bp);
2263                                                 if (bp == NULL)
2264                                                         panic("tcp packblock");
2265                                                 qpassnolim(s->rq, bp);
2266                                                 bp = NULL;
2267
2268                                                 /*
2269                                                  *  Force an ack every 2 data messages.  This is
2270                                                  *  a hack for rob to make his home system run
2271                                                  *  faster.
2272                                                  *
2273                                                  *  this also keeps the standard TCP congestion
2274                                                  *  control working since it needs an ack every
2275                                                  *  2 max segs worth.  This is not quite that,
2276                                                  *  but under a real stream is equivalent since
2277                                                  *  every packet has a max seg in it.
2278                                                  */
2279                                                 if (++(tcb->rcv.una) >= 2)
2280                                                         tcb->flags |= FORCE;
2281                                         }
2282                                         tcb->rcv.nxt += length;
2283
2284                                         /*
2285                                          *  update our rcv window
2286                                          */
2287                                         tcprcvwin(s);
2288
2289                                         /*
2290                                          *  turn on the acktimer if there's something
2291                                          *  to ack
2292                                          */
2293                                         if (tcb->acktimer.state != TcptimerON)
2294                                                 tcpgo(tpriv, &tcb->acktimer);
2295
2296                                         break;
2297                                 case Finwait2:
2298                                         /* no process to read the data, send a reset */
2299                                         if (bp != NULL)
2300                                                 freeblist(bp);
2301                                         sndrst(tcp, source, dest, length, &seg, version,
2302                                                    "send to Finwait2");
2303                                         qunlock(&s->qlock);
2304                                         poperror();
2305                                         return;
2306                         }
2307                 }
2308
2309                 if (seg.flags & FIN) {
2310                         tcb->flags |= FORCE;
2311
2312                         switch (tcb->state) {
2313                                 case Syn_received:
2314                                 case Established:
2315                                         tcb->rcv.nxt++;
2316                                         tcpsetstate(s, Close_wait);
2317                                         break;
2318                                 case Finwait1:
2319                                         tcb->rcv.nxt++;
2320                                         if (qlen(s->wq) + tcb->flgcnt == 0) {
2321                                                 tcphalt(tpriv, &tcb->rtt_timer);
2322                                                 tcphalt(tpriv, &tcb->acktimer);
2323                                                 tcphalt(tpriv, &tcb->katimer);
2324                                                 tcpsetstate(s, Time_wait);
2325                                                 tcb->timer.start = MSL2 * (1000 / MSPTICK);
2326                                                 tcpgo(tpriv, &tcb->timer);
2327                                         } else
2328                                                 tcpsetstate(s, Closing);
2329                                         break;
2330                                 case Finwait2:
2331                                         tcb->rcv.nxt++;
2332                                         tcphalt(tpriv, &tcb->rtt_timer);
2333                                         tcphalt(tpriv, &tcb->acktimer);
2334                                         tcphalt(tpriv, &tcb->katimer);
2335                                         tcpsetstate(s, Time_wait);
2336                                         tcb->timer.start = MSL2 * (1000 / MSPTICK);
2337                                         tcpgo(tpriv, &tcb->timer);
2338                                         break;
2339                                 case Close_wait:
2340                                 case Closing:
2341                                 case Last_ack:
2342                                         break;
2343                                 case Time_wait:
2344                                         tcpgo(tpriv, &tcb->timer);
2345                                         break;
2346                         }
2347                 }
2348
2349                 /*
2350                  *  get next adjacent segment from the resequence queue.
2351                  *  dump/trim any overlapping segments
2352                  */
2353                 for (;;) {
2354                         if (tcb->reseq == NULL)
2355                                 goto output;
2356
2357                         if (seq_ge(tcb->rcv.nxt, tcb->reseq->seg.seq) == 0)
2358                                 goto output;
2359
2360                         getreseq(tcb, &seg, &bp, &length);
2361
2362                         if (tcptrim(tcb, &seg, &bp, &length) == 0)
2363                                 break;
2364                 }
2365         }
2366 output:
2367         tcpoutput(s);
2368         qunlock(&s->qlock);
2369         poperror();
2370         return;
2371 raise:
2372         qunlock(&s->qlock);
2373         poperror();
2374         freeblist(bp);
2375         tcpkick(s);
2376 }
2377
2378 /*
2379  *  always enters and exits with the s locked.  We drop
2380  *  the lock to ipoput the packet so some care has to be
2381  *  taken by callers.
2382  */
2383 void tcpoutput(struct conv *s)
2384 {
2385         Tcp seg;
2386         int msgs;
2387         Tcpctl *tcb;
2388         struct block *hbp, *bp;
2389         int sndcnt, n;
2390         uint32_t ssize, dsize, usable, sent;
2391         struct Fs *f;
2392         struct tcppriv *tpriv;
2393         uint8_t version;
2394
2395         f = s->p->f;
2396         tpriv = s->p->priv;
2397         version = s->ipversion;
2398
2399         for (msgs = 0; msgs < 100; msgs++) {
2400                 tcb = (Tcpctl *) s->ptcl;
2401
2402                 switch (tcb->state) {
2403                         case Listen:
2404                         case Closed:
2405                         case Finwait2:
2406                                 return;
2407                 }
2408
2409                 /* force an ack when a window has opened up */
2410                 if (tcb->rcv.blocked && tcb->rcv.wnd > 0) {
2411                         tcb->rcv.blocked = 0;
2412                         tcb->flags |= FORCE;
2413                 }
2414
2415                 sndcnt = qlen(s->wq) + tcb->flgcnt;
2416                 sent = tcb->snd.ptr - tcb->snd.una;
2417
2418                 /* Don't send anything else until our SYN has been acked */
2419                 if (tcb->snd.ptr != tcb->iss && (tcb->flags & SYNACK) == 0)
2420                         break;
2421
2422                 /* Compute usable segment based on offered window and limit
2423                  * window probes to one
2424                  */
2425                 if (tcb->snd.wnd == 0) {
2426                         if (sent != 0) {
2427                                 if ((tcb->flags & FORCE) == 0)
2428                                         break;
2429 //              tcb->snd.ptr = tcb->snd.una;
2430                         }
2431                         usable = 1;
2432                 } else {
2433                         usable = tcb->cwind;
2434                         if (tcb->snd.wnd < usable)
2435                                 usable = tcb->snd.wnd;
2436                         usable -= sent;
2437                 }
2438                 ssize = sndcnt - sent;
2439                 if (ssize && usable < 2)
2440                         netlog(s->p->f, Logtcp, "throttled snd.wnd %lu cwind %lu\n",
2441                                    tcb->snd.wnd, tcb->cwind);
2442                 if (usable < ssize)
2443                         ssize = usable;
2444                 if (tcb->mss < ssize)
2445                         ssize = tcb->mss;
2446                 dsize = ssize;
2447                 seg.urg = 0;
2448
2449                 if (ssize == 0)
2450                         if ((tcb->flags & FORCE) == 0)
2451                                 break;
2452
2453                 tcb->flags &= ~FORCE;
2454                 tcprcvwin(s);
2455
2456                 /* By default we will generate an ack */
2457                 tcphalt(tpriv, &tcb->acktimer);
2458                 tcb->rcv.una = 0;
2459                 seg.source = s->lport;
2460                 seg.dest = s->rport;
2461                 seg.flags = ACK;
2462                 seg.mss = 0;
2463                 seg.ws = 0;
2464                 switch (tcb->state) {
2465                         case Syn_sent:
2466                                 seg.flags = 0;
2467                                 if (tcb->snd.ptr == tcb->iss) {
2468                                         seg.flags |= SYN;
2469                                         dsize--;
2470                                         seg.mss = tcb->mss;
2471                                         seg.ws = tcb->scale;
2472                                 }
2473                                 break;
2474                         case Syn_received:
2475                                 /*
2476                                  *  don't send any data with a SYN/ACK packet
2477                                  *  because Linux rejects the packet in its
2478                                  *  attempt to solve the SYN attack problem
2479                                  */
2480                                 if (tcb->snd.ptr == tcb->iss) {
2481                                         seg.flags |= SYN;
2482                                         dsize = 0;
2483                                         ssize = 1;
2484                                         seg.mss = tcb->mss;
2485                                         seg.ws = tcb->scale;
2486                                 }
2487                                 break;
2488                 }
2489                 seg.seq = tcb->snd.ptr;
2490                 seg.ack = tcb->rcv.nxt;
2491                 seg.wnd = tcb->rcv.wnd;
2492
2493                 /* Pull out data to send */
2494                 bp = NULL;
2495                 if (dsize != 0) {
2496                         bp = qcopy(s->wq, dsize, sent);
2497                         if (BLEN(bp) != dsize) {
2498                                 seg.flags |= FIN;
2499                                 dsize--;
2500                         }
2501                 }
2502
2503                 if (sent + dsize == sndcnt)
2504                         seg.flags |= PSH;
2505
2506                 /* keep track of balance of resent data */
2507                 if (seq_lt(tcb->snd.ptr, tcb->snd.nxt)) {
2508                         n = tcb->snd.nxt - tcb->snd.ptr;
2509                         if (ssize < n)
2510                                 n = ssize;
2511                         tcb->resent += n;
2512                         netlog(f, Logtcp, "rexmit: %I.%d -> %I.%d ptr 0x%lx nxt 0x%lx\n",
2513                                    s->raddr, s->rport, s->laddr, s->lport, tcb->snd.ptr,
2514                                    tcb->snd.nxt);
2515                         tpriv->stats[RetransSegs]++;
2516                 }
2517
2518                 tcb->snd.ptr += ssize;
2519
2520                 /* Pull up the send pointer so we can accept acks
2521                  * for this window
2522                  */
2523                 if (seq_gt(tcb->snd.ptr, tcb->snd.nxt))
2524                         tcb->snd.nxt = tcb->snd.ptr;
2525
2526                 /* Build header, link data and compute cksum */
2527                 switch (version) {
2528                         case V4:
2529                                 tcb->protohdr.tcp4hdr.vihl = IP_VER4;
2530                                 hbp = htontcp4(&seg, bp, &tcb->protohdr.tcp4hdr, tcb);
2531                                 if (hbp == NULL) {
2532                                         freeblist(bp);
2533                                         return;
2534                                 }
2535                                 break;
2536                         case V6:
2537                                 tcb->protohdr.tcp6hdr.vcf[0] = IP_VER6;
2538                                 hbp = htontcp6(&seg, bp, &tcb->protohdr.tcp6hdr, tcb);
2539                                 if (hbp == NULL) {
2540                                         freeblist(bp);
2541                                         return;
2542                                 }
2543                                 break;
2544                         default:
2545                                 hbp = NULL;     /* to suppress a warning */
2546                                 panic("tcpoutput: version %d", version);
2547                 }
2548
2549                 /* Start the transmission timers if there is new data and we
2550                  * expect acknowledges
2551                  */
2552                 if (ssize != 0) {
2553                         if (tcb->timer.state != TcptimerON)
2554                                 tcpgo(tpriv, &tcb->timer);
2555
2556                         /*  If round trip timer isn't running, start it.
2557                          *  measure the longest packet only in case the
2558                          *  transmission time dominates RTT
2559                          */
2560                         if (tcb->rtt_timer.state != TcptimerON)
2561                                 if (ssize == tcb->mss) {
2562                                         tcpgo(tpriv, &tcb->rtt_timer);
2563                                         tcb->rttseq = tcb->snd.ptr;
2564                                 }
2565                 }
2566
2567                 tpriv->stats[OutSegs]++;
2568
2569                 /* put off the next keep alive */
2570                 tcpgo(tpriv, &tcb->katimer);
2571
2572                 switch (version) {
2573                         case V4:
2574                                 if (ipoput4(f, hbp, 0, s->ttl, s->tos, s) < 0) {
2575                                         /* a negative return means no route */
2576                                         localclose(s, "no route");
2577                                 }
2578                                 break;
2579                         case V6:
2580                                 if (ipoput6(f, hbp, 0, s->ttl, s->tos, s) < 0) {
2581                                         /* a negative return means no route */
2582                                         localclose(s, "no route");
2583                                 }
2584                                 break;
2585                         default:
2586                                 panic("tcpoutput2: version %d", version);
2587                 }
2588                 if ((msgs % 4) == 1) {
2589                         qunlock(&s->qlock);
2590                         kthread_yield();
2591                         qlock(&s->qlock);
2592                 }
2593         }
2594 }
2595
2596 /*
2597  *  the BSD convention (hack?) for keep alives.  resend last uint8_t acked.
2598  */
2599 void tcpsendka(struct conv *s)
2600 {
2601         Tcp seg;
2602         Tcpctl *tcb;
2603         struct block *hbp, *dbp;
2604
2605         tcb = (Tcpctl *) s->ptcl;
2606
2607         dbp = NULL;
2608         seg.urg = 0;
2609         seg.source = s->lport;
2610         seg.dest = s->rport;
2611         seg.flags = ACK | PSH;
2612         seg.mss = 0;
2613         seg.ws = 0;
2614         if (tcpporthogdefense)
2615                 seg.seq = tcb->snd.una - (1 << 30) - nrand(1 << 20);
2616         else
2617                 seg.seq = tcb->snd.una - 1;
2618         seg.ack = tcb->rcv.nxt;
2619         tcb->rcv.una = 0;
2620         seg.wnd = tcb->rcv.wnd;
2621         if (tcb->state == Finwait2) {
2622                 seg.flags |= FIN;
2623         } else {
2624                 dbp = allocb(1);
2625                 dbp->wp++;
2626         }
2627
2628         if (isv4(s->raddr)) {
2629                 /* Build header, link data and compute cksum */
2630                 tcb->protohdr.tcp4hdr.vihl = IP_VER4;
2631                 hbp = htontcp4(&seg, dbp, &tcb->protohdr.tcp4hdr, tcb);
2632                 if (hbp == NULL) {
2633                         freeblist(dbp);
2634                         return;
2635                 }
2636                 ipoput4(s->p->f, hbp, 0, s->ttl, s->tos, s);
2637         } else {
2638                 /* Build header, link data and compute cksum */
2639                 tcb->protohdr.tcp6hdr.vcf[0] = IP_VER6;
2640                 hbp = htontcp6(&seg, dbp, &tcb->protohdr.tcp6hdr, tcb);
2641                 if (hbp == NULL) {
2642                         freeblist(dbp);
2643                         return;
2644                 }
2645                 ipoput6(s->p->f, hbp, 0, s->ttl, s->tos, s);
2646         }
2647 }
2648
2649 /*
2650  *  set connection to time out after 12 minutes
2651  */
2652 void tcpsetkacounter(Tcpctl * tcb)
2653 {
2654         tcb->kacounter = (12 * 60 * 1000) / (tcb->katimer.start * MSPTICK);
2655         if (tcb->kacounter < 3)
2656                 tcb->kacounter = 3;
2657 }
2658
2659 /*
2660  *  if we've timed out, close the connection
2661  *  otherwise, send a keepalive and restart the timer
2662  */
2663 void tcpkeepalive(void *v)
2664 {
2665         ERRSTACK(1);
2666         Tcpctl *tcb;
2667         struct conv *s;
2668
2669         s = v;
2670         tcb = (Tcpctl *) s->ptcl;
2671         if (waserror()) {
2672                 qunlock(&s->qlock);
2673                 nexterror();
2674         }
2675         qlock(&s->qlock);
2676         if (tcb->state != Closed) {
2677                 if (--(tcb->kacounter) <= 0) {
2678                         localclose(s, Etimedout);
2679                 } else {
2680                         tcpsendka(s);
2681                         tcpgo(s->p->priv, &tcb->katimer);
2682                 }
2683         }
2684         qunlock(&s->qlock);
2685         poperror();
2686 }
2687
2688 /*
2689  *  start keepalive timer
2690  */
2691 char *tcpstartka(struct conv *s, char **f, int n)
2692 {
2693         Tcpctl *tcb;
2694         int x;
2695
2696         tcb = (Tcpctl *) s->ptcl;
2697         if (tcb->state != Established)
2698                 return "connection must be in Establised state";
2699         if (n > 1) {
2700                 x = atoi(f[1]);
2701                 if (x >= MSPTICK)
2702                         tcb->katimer.start = x / MSPTICK;
2703         }
2704         tcpsetkacounter(tcb);
2705         tcpgo(s->p->priv, &tcb->katimer);
2706
2707         return NULL;
2708 }
2709
2710 /*
2711  *  turn checksums on/off
2712  */
2713 char *tcpsetchecksum(struct conv *s, char **f, int unused)
2714 {
2715         Tcpctl *tcb;
2716
2717         tcb = (Tcpctl *) s->ptcl;
2718         tcb->nochecksum = !atoi(f[1]);
2719
2720         return NULL;
2721 }
2722
2723 void tcprxmit(struct conv *s)
2724 {
2725         Tcpctl *tcb;
2726
2727         tcb = (Tcpctl *) s->ptcl;
2728
2729         tcb->flags |= RETRAN | FORCE;
2730         tcb->snd.ptr = tcb->snd.una;
2731
2732         /*
2733          *  We should be halving the slow start threshhold (down to one
2734          *  mss) but leaving it at mss seems to work well enough
2735          */
2736         tcb->ssthresh = tcb->mss;
2737
2738         /*
2739          *  pull window down to a single packet
2740          */
2741         tcb->cwind = tcb->mss;
2742         tcpoutput(s);
2743 }
2744
2745 void tcptimeout(void *arg)
2746 {
2747         ERRSTACK(1);
2748         struct conv *s;
2749         Tcpctl *tcb;
2750         int maxback;
2751         struct tcppriv *tpriv;
2752
2753         s = (struct conv *)arg;
2754         tpriv = s->p->priv;
2755         tcb = (Tcpctl *) s->ptcl;
2756
2757         if (waserror()) {
2758                 qunlock(&s->qlock);
2759                 nexterror();
2760         }
2761         qlock(&s->qlock);
2762         switch (tcb->state) {
2763                 default:
2764                         tcb->backoff++;
2765                         if (tcb->state == Syn_sent)
2766                                 maxback = MAXBACKMS / 2;
2767                         else
2768                                 maxback = MAXBACKMS;
2769                         tcb->backedoff += tcb->timer.start * MSPTICK;
2770                         if (tcb->backedoff >= maxback) {
2771                                 localclose(s, Etimedout);
2772                                 break;
2773                         }
2774                         netlog(s->p->f, Logtcprxmt, "timeout rexmit 0x%lx %d/%d\n",
2775                                    tcb->snd.una, tcb->timer.start, NOW);
2776                         tcpsettimer(tcb);
2777                         tcprxmit(s);
2778                         tpriv->stats[RetransTimeouts]++;
2779                         tcb->snd.dupacks = 0;
2780                         break;
2781                 case Time_wait:
2782                         localclose(s, NULL);
2783                         break;
2784                 case Closed:
2785                         break;
2786         }
2787         qunlock(&s->qlock);
2788         poperror();
2789 }
2790
2791 int inwindow(Tcpctl * tcb, int seq)
2792 {
2793         return seq_within(seq, tcb->rcv.nxt, tcb->rcv.nxt + tcb->rcv.wnd - 1);
2794 }
2795
2796 /*
2797  *  set up state for a received SYN (or SYN ACK) packet
2798  */
2799 void procsyn(struct conv *s, Tcp * seg)
2800 {
2801         Tcpctl *tcb;
2802
2803         tcb = (Tcpctl *) s->ptcl;
2804         tcb->flags |= FORCE;
2805
2806         tcb->rcv.nxt = seg->seq + 1;
2807         tcb->rcv.urg = tcb->rcv.nxt;
2808         tcb->irs = seg->seq;
2809
2810         /* our sending max segment size cannot be bigger than what he asked for */
2811         if (seg->mss != 0 && seg->mss < tcb->mss)
2812                 tcb->mss = seg->mss;
2813
2814         /* the congestion window always starts out as a single segment */
2815         tcb->snd.wnd = seg->wnd;
2816         tcb->cwind = tcb->mss;
2817 }
2818
2819 int
2820 addreseq(Tcpctl * tcb, struct tcppriv *tpriv, Tcp * seg,
2821                  struct block *bp, uint16_t length)
2822 {
2823         Reseq *rp, *rp1;
2824         int i, rqlen, qmax;
2825
2826         rp = kzmalloc(sizeof(Reseq), 0);
2827         if (rp == NULL) {
2828                 freeblist(bp);  /* bp always consumed by add_reseq */
2829                 return 0;
2830         }
2831
2832         rp->seg = *seg;
2833         rp->bp = bp;
2834         rp->length = length;
2835
2836         /* Place on reassembly list sorting by starting seq number */
2837         rp1 = tcb->reseq;
2838         if (rp1 == NULL || seq_lt(seg->seq, rp1->seg.seq)) {
2839                 rp->next = rp1;
2840                 tcb->reseq = rp;
2841                 if (rp->next != NULL)
2842                         tpriv->stats[OutOfOrder]++;
2843                 return 0;
2844         }
2845
2846         rqlen = 0;
2847         for (i = 0;; i++) {
2848                 rqlen += rp1->length;
2849                 if (rp1->next == NULL || seq_lt(seg->seq, rp1->next->seg.seq)) {
2850                         rp->next = rp1->next;
2851                         rp1->next = rp;
2852                         if (rp->next != NULL)
2853                                 tpriv->stats[OutOfOrder]++;
2854                         break;
2855                 }
2856                 rp1 = rp1->next;
2857         }
2858         qmax = QMAX << tcb->rcv.scale;
2859         if (rqlen > qmax) {
2860                 printd("resequence queue > window: %d > %d\n", rqlen, qmax);
2861                 i = 0;
2862                 for (rp1 = tcb->reseq; rp1 != NULL; rp1 = rp1->next) {
2863                         printd("0x%#lx 0x%#lx 0x%#x\n", rp1->seg.seq,
2864                                    rp1->seg.ack, rp1->seg.flags);
2865                         if (i++ > 10) {
2866                                 printd("...\n");
2867                                 break;
2868                         }
2869                 }
2870
2871                 // delete entire reassembly queue; wait for retransmit.
2872                 // - should we be smarter and only delete the tail?
2873                 for (rp = tcb->reseq; rp != NULL; rp = rp1) {
2874                         rp1 = rp->next;
2875                         freeblist(rp->bp);
2876                         kfree(rp);
2877                 }
2878                 tcb->reseq = NULL;
2879
2880                 return -1;
2881         }
2882         return 0;
2883 }
2884
2885 void getreseq(Tcpctl * tcb, Tcp * seg, struct block **bp, uint16_t * length)
2886 {
2887         Reseq *rp;
2888
2889         rp = tcb->reseq;
2890         if (rp == NULL)
2891                 return;
2892
2893         tcb->reseq = rp->next;
2894
2895         *seg = rp->seg;
2896         *bp = rp->bp;
2897         *length = rp->length;
2898
2899         kfree(rp);
2900 }
2901
2902 int tcptrim(Tcpctl * tcb, Tcp * seg, struct block **bp, uint16_t * length)
2903 {
2904         uint16_t len;
2905         uint8_t accept;
2906         int dupcnt, excess;
2907
2908         accept = 0;
2909         len = *length;
2910         if (seg->flags & SYN)
2911                 len++;
2912         if (seg->flags & FIN)
2913                 len++;
2914
2915         if (tcb->rcv.wnd == 0) {
2916                 if (len == 0 && seg->seq == tcb->rcv.nxt)
2917                         return 0;
2918         } else {
2919                 /* Some part of the segment should be in the window */
2920                 if (inwindow(tcb, seg->seq))
2921                         accept++;
2922                 else if (len != 0) {
2923                         if (inwindow(tcb, seg->seq + len - 1) ||
2924                                 seq_within(tcb->rcv.nxt, seg->seq, seg->seq + len - 1))
2925                                 accept++;
2926                 }
2927         }
2928         if (!accept) {
2929                 freeblist(*bp);
2930                 return -1;
2931         }
2932         dupcnt = tcb->rcv.nxt - seg->seq;
2933         if (dupcnt > 0) {
2934                 tcb->rerecv += dupcnt;
2935                 if (seg->flags & SYN) {
2936                         seg->flags &= ~SYN;
2937                         seg->seq++;
2938
2939                         if (seg->urg > 1)
2940                                 seg->urg--;
2941                         else
2942                                 seg->flags &= ~URG;
2943                         dupcnt--;
2944                 }
2945                 if (dupcnt > 0) {
2946                         pullblock(bp, (uint16_t) dupcnt);
2947                         seg->seq += dupcnt;
2948                         *length -= dupcnt;
2949
2950                         if (seg->urg > dupcnt)
2951                                 seg->urg -= dupcnt;
2952                         else {
2953                                 seg->flags &= ~URG;
2954                                 seg->urg = 0;
2955                         }
2956                 }
2957         }
2958         excess = seg->seq + *length - (tcb->rcv.nxt + tcb->rcv.wnd);
2959         if (excess > 0) {
2960                 tcb->rerecv += excess;
2961                 *length -= excess;
2962                 *bp = trimblock(*bp, 0, *length);
2963                 if (*bp == NULL)
2964                         panic("presotto is a boofhead");
2965                 seg->flags &= ~FIN;
2966         }
2967         return 0;
2968 }
2969
2970 void tcpadvise(struct Proto *tcp, struct block *bp, char *msg)
2971 {
2972         Tcp4hdr *h4;
2973         Tcp6hdr *h6;
2974         Tcpctl *tcb;
2975         uint8_t source[IPaddrlen];
2976         uint8_t dest[IPaddrlen];
2977         uint16_t psource, pdest;
2978         struct conv *s, **p;
2979
2980         h4 = (Tcp4hdr *) (bp->rp);
2981         h6 = (Tcp6hdr *) (bp->rp);
2982
2983         if ((h4->vihl & 0xF0) == IP_VER4) {
2984                 v4tov6(dest, h4->tcpdst);
2985                 v4tov6(source, h4->tcpsrc);
2986                 psource = nhgets(h4->tcpsport);
2987                 pdest = nhgets(h4->tcpdport);
2988         } else {
2989                 ipmove(dest, h6->tcpdst);
2990                 ipmove(source, h6->tcpsrc);
2991                 psource = nhgets(h6->tcpsport);
2992                 pdest = nhgets(h6->tcpdport);
2993         }
2994
2995         /* Look for a connection */
2996         qlock(&tcp->qlock);
2997         for (p = tcp->conv; *p; p++) {
2998                 s = *p;
2999                 tcb = (Tcpctl *) s->ptcl;
3000                 if (s->rport == pdest)
3001                         if (s->lport == psource)
3002                                 if (tcb->state != Closed)
3003                                         if (ipcmp(s->raddr, dest) == 0)
3004                                                 if (ipcmp(s->laddr, source) == 0) {
3005                                                         qlock(&s->qlock);
3006                                                         qunlock(&tcp->qlock);
3007                                                         switch (tcb->state) {
3008                                                                 case Syn_sent:
3009                                                                         localclose(s, msg);
3010                                                                         break;
3011                                                         }
3012                                                         qunlock(&s->qlock);
3013                                                         freeblist(bp);
3014                                                         return;
3015                                                 }
3016         }
3017         qunlock(&tcp->qlock);
3018         freeblist(bp);
3019 }
3020
3021 static char *tcpporthogdefensectl(char *val)
3022 {
3023         if (strcmp(val, "on") == 0)
3024                 tcpporthogdefense = 1;
3025         else if (strcmp(val, "off") == 0)
3026                 tcpporthogdefense = 0;
3027         else
3028                 return "unknown value for tcpporthogdefense";
3029         return NULL;
3030 }
3031
3032 /* called with c qlocked */
3033 char *tcpctl(struct conv *c, char **f, int n)
3034 {
3035         if (n == 1 && strcmp(f[0], "hangup") == 0)
3036                 return tcphangup(c);
3037         if (n >= 1 && strcmp(f[0], "keepalive") == 0)
3038                 return tcpstartka(c, f, n);
3039         if (n >= 1 && strcmp(f[0], "checksum") == 0)
3040                 return tcpsetchecksum(c, f, n);
3041         if (n >= 1 && strcmp(f[0], "tcpporthogdefense") == 0)
3042                 return tcpporthogdefensectl(f[1]);
3043         return "unknown control request";
3044 }
3045
3046 int tcpstats(struct Proto *tcp, char *buf, int len)
3047 {
3048         struct tcppriv *priv;
3049         char *p, *e;
3050         int i;
3051
3052         priv = tcp->priv;
3053         p = buf;
3054         e = p + len;
3055         for (i = 0; i < Nstats; i++)
3056                 p = seprintf(p, e, "%s: %lu\n", statnames[i], priv->stats[i]);
3057         return p - buf;
3058 }
3059
3060 /*
3061  *  garbage collect any stale conversations:
3062  *      - SYN received but no SYN-ACK after 5 seconds (could be the SYN attack)
3063  *      - Finwait2 after 5 minutes
3064  *
3065  *  this is called whenever we run out of channels.  Both checks are
3066  *  of questionable validity so we try to use them only when we're
3067  *  up against the wall.
3068  */
3069 int tcpgc(struct Proto *tcp)
3070 {
3071         struct conv *c, **pp, **ep;
3072         int n;
3073         Tcpctl *tcb;
3074
3075         n = 0;
3076         ep = &tcp->conv[tcp->nc];
3077         for (pp = tcp->conv; pp < ep; pp++) {
3078                 c = *pp;
3079                 if (c == NULL)
3080                         break;
3081                 if (!canqlock(&c->qlock))
3082                         continue;
3083                 tcb = (Tcpctl *) c->ptcl;
3084                 switch (tcb->state) {
3085                         case Syn_received:
3086                                 if (NOW - tcb->time > 5000) {
3087                                         localclose(c, "timed out");
3088                                         n++;
3089                                 }
3090                                 break;
3091                         case Finwait2:
3092                                 if (NOW - tcb->time > 5 * 60 * 1000) {
3093                                         localclose(c, "timed out");
3094                                         n++;
3095                                 }
3096                                 break;
3097                 }
3098                 qunlock(&c->qlock);
3099         }
3100         return n;
3101 }
3102
3103 void tcpsettimer(Tcpctl * tcb)
3104 {
3105         int x;
3106
3107         /* round trip dependency */
3108         x = backoff(tcb->backoff) *
3109                 (tcb->mdev + (tcb->srtt >> LOGAGAIN) + MSPTICK) / MSPTICK;
3110
3111         /* bounded twixt 1/2 and 64 seconds */
3112         if (x < 500 / MSPTICK)
3113                 x = 500 / MSPTICK;
3114         else if (x > (64000 / MSPTICK))
3115                 x = 64000 / MSPTICK;
3116         tcb->timer.start = x;
3117 }
3118
3119 void tcpinit(struct Fs *fs)
3120 {
3121         struct Proto *tcp;
3122         struct tcppriv *tpriv;
3123
3124         tcp = kzmalloc(sizeof(struct Proto), 0);
3125         tpriv = tcp->priv = kzmalloc(sizeof(struct tcppriv), 0);
3126         qlock_init(&tpriv->tl);
3127         qlock_init(&tpriv->apl);
3128         tcp->name = "tcp";
3129         tcp->connect = tcpconnect;
3130         tcp->announce = tcpannounce;
3131         tcp->ctl = tcpctl;
3132         tcp->state = tcpstate;
3133         tcp->create = tcpcreate;
3134         tcp->close = tcpclose;
3135         tcp->rcv = tcpiput;
3136         tcp->advise = tcpadvise;
3137         tcp->stats = tcpstats;
3138         tcp->inuse = tcpinuse;
3139         tcp->gc = tcpgc;
3140         tcp->ipproto = IP_TCPPROTO;
3141         tcp->nc = scalednconv();
3142         tcp->ptclsize = sizeof(Tcpctl);
3143         tpriv->stats[MaxConn] = tcp->nc;
3144
3145         Fsproto(fs, tcp);
3146 }
3147
3148 void
3149 tcpsetscale(struct conv *s, Tcpctl * tcb, uint16_t rcvscale, uint16_t sndscale)
3150 {
3151         if (rcvscale) {
3152                 tcb->rcv.scale = rcvscale & 0xff;
3153                 tcb->snd.scale = sndscale & 0xff;
3154                 tcb->window = QMAX << tcb->snd.scale;
3155                 qsetlimit(s->rq, tcb->window);
3156         } else {
3157                 tcb->rcv.scale = 0;
3158                 tcb->snd.scale = 0;
3159                 tcb->window = QMAX;
3160                 qsetlimit(s->rq, tcb->window);
3161         }
3162 }