Lindent pass
[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         if (s->state == Announced)
740                 rendez_wakeup(&s->listenr);
741
742         qhangup(s->rq, reason);
743         qhangup(s->wq, reason);
744
745         tcpsetstate(s, Closed);
746 }
747
748 /* mtu (- TCP + IP hdr len) of 1st hop */
749 int tcpmtu(struct Proto *tcp, uint8_t * addr, int version, int *scale)
750 {
751         struct Ipifc *ifc;
752         int mtu;
753
754         ifc = findipifc(tcp->f, addr, 0);
755         switch (version) {
756                 default:
757                 case V4:
758                         mtu = DEF_MSS;
759                         if (ifc != NULL)
760                                 mtu = ifc->maxtu - ifc->m->hsize - (TCP4_PKT + TCP4_HDRSIZE);
761                         break;
762                 case V6:
763                         mtu = DEF_MSS6;
764                         if (ifc != NULL)
765                                 mtu = ifc->maxtu - ifc->m->hsize - (TCP6_PKT + TCP6_HDRSIZE);
766                         break;
767         }
768         if (ifc != NULL) {
769                 if (ifc->mbps > 100)
770                         *scale = HaveWS | 3;
771                 else if (ifc->mbps > 10)
772                         *scale = HaveWS | 1;
773                 else
774                         *scale = HaveWS | 0;
775         } else
776                 *scale = HaveWS | 0;
777
778         return mtu;
779 }
780
781 void inittcpctl(struct conv *s, int mode)
782 {
783         Tcpctl *tcb;
784         Tcp4hdr *h4;
785         Tcp6hdr *h6;
786         int mss;
787
788         tcb = (Tcpctl *) s->ptcl;
789
790         memset(tcb, 0, sizeof(Tcpctl));
791
792         tcb->ssthresh = 65535;
793         tcb->srtt = tcp_irtt << LOGAGAIN;
794         tcb->mdev = 0;
795
796         /* setup timers */
797         tcb->timer.start = tcp_irtt / MSPTICK;
798         tcb->timer.func = tcptimeout;
799         tcb->timer.arg = s;
800         tcb->rtt_timer.start = MAX_TIME;
801         tcb->acktimer.start = TCP_ACK / MSPTICK;
802         tcb->acktimer.func = tcpacktimer;
803         tcb->acktimer.arg = s;
804         tcb->katimer.start = DEF_KAT / MSPTICK;
805         tcb->katimer.func = tcpkeepalive;
806         tcb->katimer.arg = s;
807
808         mss = DEF_MSS;
809
810         /* create a prototype(pseudo) header */
811         if (mode != TCP_LISTEN) {
812                 if (ipcmp(s->laddr, IPnoaddr) == 0)
813                         findlocalip(s->p->f, s->laddr, s->raddr);
814
815                 switch (s->ipversion) {
816                         case V4:
817                                 h4 = &tcb->protohdr.tcp4hdr;
818                                 memset(h4, 0, sizeof(*h4));
819                                 h4->proto = IP_TCPPROTO;
820                                 hnputs(h4->tcpsport, s->lport);
821                                 hnputs(h4->tcpdport, s->rport);
822                                 v6tov4(h4->tcpsrc, s->laddr);
823                                 v6tov4(h4->tcpdst, s->raddr);
824                                 break;
825                         case V6:
826                                 h6 = &tcb->protohdr.tcp6hdr;
827                                 memset(h6, 0, sizeof(*h6));
828                                 h6->proto = IP_TCPPROTO;
829                                 hnputs(h6->tcpsport, s->lport);
830                                 hnputs(h6->tcpdport, s->rport);
831                                 ipmove(h6->tcpsrc, s->laddr);
832                                 ipmove(h6->tcpdst, s->raddr);
833                                 mss = DEF_MSS6;
834                                 break;
835                         default:
836                                 panic("inittcpctl: version %d", s->ipversion);
837                 }
838         }
839
840         tcb->mss = tcb->cwind = mss;
841
842         /* default is no window scaling */
843         tcb->window = QMAX;
844         tcb->rcv.wnd = QMAX;
845         tcb->rcv.scale = 0;
846         tcb->snd.scale = 0;
847         qsetlimit(s->rq, QMAX);
848 }
849
850 /*
851  *  called with s qlocked
852  */
853 void tcpstart(struct conv *s, int mode)
854 {
855         Tcpctl *tcb;
856         struct tcppriv *tpriv;
857         char kpname[KNAMELEN];
858
859         tpriv = s->p->priv;
860
861         if (tpriv->ackprocstarted == 0) {
862                 qlock(&tpriv->apl);
863                 if (tpriv->ackprocstarted == 0) {
864                         snprintf(kpname, sizeof(kpname), "#I%dtcpack", s->p->f->dev);
865                         ktask(kpname, tcpackproc, s->p);
866                         tpriv->ackprocstarted = 1;
867                 }
868                 qunlock(&tpriv->apl);
869         }
870
871         tcb = (Tcpctl *) s->ptcl;
872
873         inittcpctl(s, mode);
874
875         iphtadd(&tpriv->ht, s);
876         switch (mode) {
877                 case TCP_LISTEN:
878                         tpriv->stats[PassiveOpens]++;
879                         tcb->flags |= CLONE;
880                         tcpsetstate(s, Listen);
881                         break;
882
883                 case TCP_CONNECT:
884                         tpriv->stats[ActiveOpens]++;
885                         tcb->flags |= ACTIVE;
886                         tcpsndsyn(s, tcb);
887                         tcpsetstate(s, Syn_sent);
888                         tcpoutput(s);
889                         break;
890         }
891 }
892
893 static char *tcpflag(uint16_t flag)
894 {
895         static char buf[128];
896
897         snprintf(buf, sizeof(buf), "%d", flag >> 10);   /* Head len */
898         if (flag & URG)
899                 snprintf(buf, sizeof(buf), "%s%s", buf, " URG");
900         if (flag & ACK)
901                 snprintf(buf, sizeof(buf), "%s%s", buf, " ACK");
902         if (flag & PSH)
903                 snprintf(buf, sizeof(buf), "%s%s", buf, " PSH");
904         if (flag & RST)
905                 snprintf(buf, sizeof(buf), "%s%s", buf, " RST");
906         if (flag & SYN)
907                 snprintf(buf, sizeof(buf), "%s%s", buf, " SYN");
908         if (flag & FIN)
909                 snprintf(buf, sizeof(buf), "%s%s", buf, " FIN");
910
911         return buf;
912 }
913
914 struct block *htontcp6(Tcp * tcph, struct block *data, Tcp6hdr * ph,
915                                            Tcpctl * tcb)
916 {
917         int dlen;
918         Tcp6hdr *h;
919         uint16_t csum;
920         uint16_t hdrlen, optpad = 0;
921         uint8_t *opt;
922
923         hdrlen = TCP6_HDRSIZE;
924         if (tcph->flags & SYN) {
925                 if (tcph->mss)
926                         hdrlen += MSS_LENGTH;
927                 if (tcph->ws)
928                         hdrlen += WS_LENGTH;
929                 optpad = hdrlen & 3;
930                 if (optpad)
931                         optpad = 4 - optpad;
932                 hdrlen += optpad;
933         }
934
935         if (data) {
936                 dlen = blocklen(data);
937                 data = padblock(data, hdrlen + TCP6_PKT);
938                 if (data == NULL)
939                         return NULL;
940         } else {
941                 dlen = 0;
942                 data = allocb(hdrlen + TCP6_PKT + 64);  /* the 64 pad is to meet mintu's */
943                 if (data == NULL)
944                         return NULL;
945                 data->wp += hdrlen + TCP6_PKT;
946         }
947
948         /* copy in pseudo ip header plus port numbers */
949         h = (Tcp6hdr *) (data->rp);
950         memmove(h, ph, TCP6_TCBPHDRSZ);
951
952         /* compose pseudo tcp header, do cksum calculation */
953         hnputl(h->vcf, hdrlen + dlen);
954         h->ploadlen[0] = h->ploadlen[1] = h->proto = 0;
955         h->ttl = ph->proto;
956
957         /* copy in variable bits */
958         hnputl(h->tcpseq, tcph->seq);
959         hnputl(h->tcpack, tcph->ack);
960         hnputs(h->tcpflag, (hdrlen << 10) | tcph->flags);
961         hnputs(h->tcpwin, tcph->wnd >> (tcb != NULL ? tcb->snd.scale : 0));
962         hnputs(h->tcpurg, tcph->urg);
963
964         if (tcph->flags & SYN) {
965                 opt = h->tcpopt;
966                 if (tcph->mss != 0) {
967                         *opt++ = MSSOPT;
968                         *opt++ = MSS_LENGTH;
969                         hnputs(opt, tcph->mss);
970                         opt += 2;
971                 }
972                 if (tcph->ws != 0) {
973                         *opt++ = WSOPT;
974                         *opt++ = WS_LENGTH;
975                         *opt++ = tcph->ws;
976                 }
977                 while (optpad-- > 0)
978                         *opt++ = NOOPOPT;
979         }
980
981         if (tcb != NULL && tcb->nochecksum) {
982                 h->tcpcksum[0] = h->tcpcksum[1] = 0;
983         } else {
984                 csum = ptclcsum(data, TCP6_IPLEN, hdrlen + dlen + TCP6_PHDRSIZE);
985                 hnputs(h->tcpcksum, csum);
986         }
987
988         /* move from pseudo header back to normal ip header */
989         memset(h->vcf, 0, 4);
990         h->vcf[0] = IP_VER6;
991         hnputs(h->ploadlen, hdrlen + dlen);
992         h->proto = ph->proto;
993
994         return data;
995 }
996
997 struct block *htontcp4(Tcp * tcph, struct block *data, Tcp4hdr * ph,
998                                            Tcpctl * tcb)
999 {
1000         int dlen;
1001         Tcp4hdr *h;
1002         uint16_t csum;
1003         uint16_t hdrlen, optpad = 0;
1004         uint8_t *opt;
1005
1006         hdrlen = TCP4_HDRSIZE;
1007         if (tcph->flags & SYN) {
1008                 if (tcph->mss)
1009                         hdrlen += MSS_LENGTH;
1010                 if (tcph->ws)
1011                         hdrlen += WS_LENGTH;
1012                 optpad = hdrlen & 3;
1013                 if (optpad)
1014                         optpad = 4 - optpad;
1015                 hdrlen += optpad;
1016         }
1017
1018         if (data) {
1019                 dlen = blocklen(data);
1020                 data = padblock(data, hdrlen + TCP4_PKT);
1021                 if (data == NULL)
1022                         return NULL;
1023         } else {
1024                 dlen = 0;
1025                 data = allocb(hdrlen + TCP4_PKT + 64);  /* the 64 pad is to meet mintu's */
1026                 if (data == NULL)
1027                         return NULL;
1028                 data->wp += hdrlen + TCP4_PKT;
1029         }
1030
1031         /* copy in pseudo ip header plus port numbers */
1032         h = (Tcp4hdr *) (data->rp);
1033         memmove(h, ph, TCP4_TCBPHDRSZ);
1034
1035         /* copy in variable bits */
1036         hnputs(h->tcplen, hdrlen + dlen);
1037         hnputl(h->tcpseq, tcph->seq);
1038         hnputl(h->tcpack, tcph->ack);
1039         hnputs(h->tcpflag, (hdrlen << 10) | tcph->flags);
1040         hnputs(h->tcpwin, tcph->wnd >> (tcb != NULL ? tcb->snd.scale : 0));
1041         hnputs(h->tcpurg, tcph->urg);
1042
1043         if (tcph->flags & SYN) {
1044                 opt = h->tcpopt;
1045                 if (tcph->mss != 0) {
1046                         *opt++ = MSSOPT;
1047                         *opt++ = MSS_LENGTH;
1048                         hnputs(opt, tcph->mss);
1049                         opt += 2;
1050                 }
1051                 if (tcph->ws != 0) {
1052                         *opt++ = WSOPT;
1053                         *opt++ = WS_LENGTH;
1054                         *opt++ = tcph->ws;
1055                 }
1056                 while (optpad-- > 0)
1057                         *opt++ = NOOPOPT;
1058         }
1059
1060         if (tcb != NULL && tcb->nochecksum) {
1061                 h->tcpcksum[0] = h->tcpcksum[1] = 0;
1062         } else {
1063                 csum = ptclcsum(data, TCP4_IPLEN, hdrlen + dlen + TCP4_PHDRSIZE);
1064                 hnputs(h->tcpcksum, csum);
1065         }
1066
1067         return data;
1068 }
1069
1070 int ntohtcp6(Tcp * tcph, struct block **bpp)
1071 {
1072         Tcp6hdr *h;
1073         uint8_t *optr;
1074         uint16_t hdrlen;
1075         uint16_t optlen;
1076         int n;
1077
1078         *bpp = pullupblock(*bpp, TCP6_PKT + TCP6_HDRSIZE);
1079         if (*bpp == NULL)
1080                 return -1;
1081
1082         h = (Tcp6hdr *) ((*bpp)->rp);
1083         tcph->source = nhgets(h->tcpsport);
1084         tcph->dest = nhgets(h->tcpdport);
1085         tcph->seq = nhgetl(h->tcpseq);
1086         tcph->ack = nhgetl(h->tcpack);
1087         hdrlen = (h->tcpflag[0] >> 2) & ~3;
1088         if (hdrlen < TCP6_HDRSIZE) {
1089                 freeblist(*bpp);
1090                 return -1;
1091         }
1092
1093         tcph->flags = h->tcpflag[1];
1094         tcph->wnd = nhgets(h->tcpwin);
1095         tcph->urg = nhgets(h->tcpurg);
1096         tcph->mss = 0;
1097         tcph->ws = 0;
1098         tcph->len = nhgets(h->ploadlen) - hdrlen;
1099
1100         *bpp = pullupblock(*bpp, hdrlen + TCP6_PKT);
1101         if (*bpp == NULL)
1102                 return -1;
1103
1104         optr = h->tcpopt;
1105         n = hdrlen - TCP6_HDRSIZE;
1106         while (n > 0 && *optr != EOLOPT) {
1107                 if (*optr == NOOPOPT) {
1108                         n--;
1109                         optr++;
1110                         continue;
1111                 }
1112                 optlen = optr[1];
1113                 if (optlen < 2 || optlen > n)
1114                         break;
1115                 switch (*optr) {
1116                         case MSSOPT:
1117                                 if (optlen == MSS_LENGTH)
1118                                         tcph->mss = nhgets(optr + 2);
1119                                 break;
1120                         case WSOPT:
1121                                 if (optlen == WS_LENGTH && *(optr + 2) <= 14)
1122                                         tcph->ws = HaveWS | *(optr + 2);
1123                                 break;
1124                 }
1125                 n -= optlen;
1126                 optr += optlen;
1127         }
1128         return hdrlen;
1129 }
1130
1131 int ntohtcp4(Tcp * tcph, struct block **bpp)
1132 {
1133         Tcp4hdr *h;
1134         uint8_t *optr;
1135         uint16_t hdrlen;
1136         uint16_t optlen;
1137         int n;
1138
1139         *bpp = pullupblock(*bpp, TCP4_PKT + TCP4_HDRSIZE);
1140         if (*bpp == NULL)
1141                 return -1;
1142
1143         h = (Tcp4hdr *) ((*bpp)->rp);
1144         tcph->source = nhgets(h->tcpsport);
1145         tcph->dest = nhgets(h->tcpdport);
1146         tcph->seq = nhgetl(h->tcpseq);
1147         tcph->ack = nhgetl(h->tcpack);
1148
1149         hdrlen = (h->tcpflag[0] >> 2) & ~3;
1150         if (hdrlen < TCP4_HDRSIZE) {
1151                 freeblist(*bpp);
1152                 return -1;
1153         }
1154
1155         tcph->flags = h->tcpflag[1];
1156         tcph->wnd = nhgets(h->tcpwin);
1157         tcph->urg = nhgets(h->tcpurg);
1158         tcph->mss = 0;
1159         tcph->ws = 0;
1160         tcph->len = nhgets(h->length) - (hdrlen + TCP4_PKT);
1161
1162         *bpp = pullupblock(*bpp, hdrlen + TCP4_PKT);
1163         if (*bpp == NULL)
1164                 return -1;
1165
1166         optr = h->tcpopt;
1167         n = hdrlen - TCP4_HDRSIZE;
1168         while (n > 0 && *optr != EOLOPT) {
1169                 if (*optr == NOOPOPT) {
1170                         n--;
1171                         optr++;
1172                         continue;
1173                 }
1174                 optlen = optr[1];
1175                 if (optlen < 2 || optlen > n)
1176                         break;
1177                 switch (*optr) {
1178                         case MSSOPT:
1179                                 if (optlen == MSS_LENGTH)
1180                                         tcph->mss = nhgets(optr + 2);
1181                                 break;
1182                         case WSOPT:
1183                                 if (optlen == WS_LENGTH && *(optr + 2) <= 14)
1184                                         tcph->ws = HaveWS | *(optr + 2);
1185                                 break;
1186                 }
1187                 n -= optlen;
1188                 optr += optlen;
1189         }
1190         return hdrlen;
1191 }
1192
1193 /*
1194  *  For outgiing calls, generate an initial sequence
1195  *  number and put a SYN on the send queue
1196  */
1197 void tcpsndsyn(struct conv *s, Tcpctl * tcb)
1198 {
1199         tcb->iss = (nrand(1 << 16) << 16) | nrand(1 << 16);
1200         tcb->rttseq = tcb->iss;
1201         tcb->snd.wl2 = tcb->iss;
1202         tcb->snd.una = tcb->iss;
1203         tcb->snd.ptr = tcb->rttseq;
1204         tcb->snd.nxt = tcb->rttseq;
1205         tcb->flgcnt++;
1206         tcb->flags |= FORCE;
1207         tcb->sndsyntime = NOW;
1208
1209         /* set desired mss and scale */
1210         tcb->mss = tcpmtu(s->p, s->laddr, s->ipversion, &tcb->scale);
1211 }
1212
1213 void
1214 sndrst(struct Proto *tcp, uint8_t * source, uint8_t * dest,
1215            uint16_t length, Tcp * seg, uint8_t version, char *reason)
1216 {
1217         struct block *hbp;
1218         uint8_t rflags;
1219         struct tcppriv *tpriv;
1220         Tcp4hdr ph4;
1221         Tcp6hdr ph6;
1222
1223         netlog(tcp->f, Logtcp, "sndrst: %s", reason);
1224
1225         tpriv = tcp->priv;
1226
1227         if (seg->flags & RST)
1228                 return;
1229
1230         /* make pseudo header */
1231         switch (version) {
1232                 case V4:
1233                         memset(&ph4, 0, sizeof(ph4));
1234                         ph4.vihl = IP_VER4;
1235                         v6tov4(ph4.tcpsrc, dest);
1236                         v6tov4(ph4.tcpdst, source);
1237                         ph4.proto = IP_TCPPROTO;
1238                         hnputs(ph4.tcplen, TCP4_HDRSIZE);
1239                         hnputs(ph4.tcpsport, seg->dest);
1240                         hnputs(ph4.tcpdport, seg->source);
1241                         break;
1242                 case V6:
1243                         memset(&ph6, 0, sizeof(ph6));
1244                         ph6.vcf[0] = IP_VER6;
1245                         ipmove(ph6.tcpsrc, dest);
1246                         ipmove(ph6.tcpdst, source);
1247                         ph6.proto = IP_TCPPROTO;
1248                         hnputs(ph6.ploadlen, TCP6_HDRSIZE);
1249                         hnputs(ph6.tcpsport, seg->dest);
1250                         hnputs(ph6.tcpdport, seg->source);
1251                         break;
1252                 default:
1253                         panic("sndrst: version %d", version);
1254         }
1255
1256         tpriv->stats[OutRsts]++;
1257         rflags = RST;
1258
1259         /* convince the other end that this reset is in band */
1260         if (seg->flags & ACK) {
1261                 seg->seq = seg->ack;
1262                 seg->ack = 0;
1263         } else {
1264                 rflags |= ACK;
1265                 seg->ack = seg->seq;
1266                 seg->seq = 0;
1267                 if (seg->flags & SYN)
1268                         seg->ack++;
1269                 seg->ack += length;
1270                 if (seg->flags & FIN)
1271                         seg->ack++;
1272         }
1273         seg->flags = rflags;
1274         seg->wnd = 0;
1275         seg->urg = 0;
1276         seg->mss = 0;
1277         seg->ws = 0;
1278         switch (version) {
1279                 case V4:
1280                         hbp = htontcp4(seg, NULL, &ph4, NULL);
1281                         if (hbp == NULL)
1282                                 return;
1283                         ipoput4(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1284                         break;
1285                 case V6:
1286                         hbp = htontcp6(seg, NULL, &ph6, NULL);
1287                         if (hbp == NULL)
1288                                 return;
1289                         ipoput6(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1290                         break;
1291                 default:
1292                         panic("sndrst2: version %d", version);
1293         }
1294 }
1295
1296 /*
1297  *  send a reset to the remote side and close the conversation
1298  *  called with s qlocked
1299  */
1300 char *tcphangup(struct conv *s)
1301 {
1302         ERRSTACK(2);
1303         Tcp seg;
1304         Tcpctl *tcb;
1305         struct block *hbp;
1306
1307         tcb = (Tcpctl *) s->ptcl;
1308         if (waserror()) {
1309                 poperror();
1310                 return commonerror();
1311         }
1312         if (s->raddr != 0) {
1313                 /* discard error style, poperror regardless */
1314                 if (!waserror()) {
1315                         seg.flags = RST | ACK;
1316                         seg.ack = tcb->rcv.nxt;
1317                         tcb->rcv.una = 0;
1318                         seg.seq = tcb->snd.ptr;
1319                         seg.wnd = 0;
1320                         seg.urg = 0;
1321                         seg.mss = 0;
1322                         seg.ws = 0;
1323                         switch (s->ipversion) {
1324                                 case V4:
1325                                         tcb->protohdr.tcp4hdr.vihl = IP_VER4;
1326                                         hbp = htontcp4(&seg, NULL, &tcb->protohdr.tcp4hdr, tcb);
1327                                         ipoput4(s->p->f, hbp, 0, s->ttl, s->tos, s);
1328                                         break;
1329                                 case V6:
1330                                         tcb->protohdr.tcp6hdr.vcf[0] = IP_VER6;
1331                                         hbp = htontcp6(&seg, NULL, &tcb->protohdr.tcp6hdr, tcb);
1332                                         ipoput6(s->p->f, hbp, 0, s->ttl, s->tos, s);
1333                                         break;
1334                                 default:
1335                                         panic("tcphangup: version %d", s->ipversion);
1336                         }
1337                 }
1338                 poperror();
1339         }
1340         localclose(s, NULL);
1341         poperror();
1342         return NULL;
1343 }
1344
1345 /*
1346  *  (re)send a SYN ACK
1347  */
1348 int sndsynack(struct Proto *tcp, Limbo * lp)
1349 {
1350         struct block *hbp;
1351         Tcp4hdr ph4;
1352         Tcp6hdr ph6;
1353         Tcp seg;
1354         int scale;
1355
1356         /* make pseudo header */
1357         switch (lp->version) {
1358                 case V4:
1359                         memset(&ph4, 0, sizeof(ph4));
1360                         ph4.vihl = IP_VER4;
1361                         v6tov4(ph4.tcpsrc, lp->laddr);
1362                         v6tov4(ph4.tcpdst, lp->raddr);
1363                         ph4.proto = IP_TCPPROTO;
1364                         hnputs(ph4.tcplen, TCP4_HDRSIZE);
1365                         hnputs(ph4.tcpsport, lp->lport);
1366                         hnputs(ph4.tcpdport, lp->rport);
1367                         break;
1368                 case V6:
1369                         memset(&ph6, 0, sizeof(ph6));
1370                         ph6.vcf[0] = IP_VER6;
1371                         ipmove(ph6.tcpsrc, lp->laddr);
1372                         ipmove(ph6.tcpdst, lp->raddr);
1373                         ph6.proto = IP_TCPPROTO;
1374                         hnputs(ph6.ploadlen, TCP6_HDRSIZE);
1375                         hnputs(ph6.tcpsport, lp->lport);
1376                         hnputs(ph6.tcpdport, lp->rport);
1377                         break;
1378                 default:
1379                         panic("sndrst: version %d", lp->version);
1380         }
1381
1382         seg.seq = lp->iss;
1383         seg.ack = lp->irs + 1;
1384         seg.flags = SYN | ACK;
1385         seg.urg = 0;
1386         seg.mss = tcpmtu(tcp, lp->laddr, lp->version, &scale);
1387         seg.wnd = QMAX;
1388
1389         /* if the other side set scale, we should too */
1390         if (lp->rcvscale) {
1391                 seg.ws = scale;
1392                 lp->sndscale = scale;
1393         } else {
1394                 seg.ws = 0;
1395                 lp->sndscale = 0;
1396         }
1397
1398         switch (lp->version) {
1399                 case V4:
1400                         hbp = htontcp4(&seg, NULL, &ph4, NULL);
1401                         if (hbp == NULL)
1402                                 return -1;
1403                         ipoput4(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1404                         break;
1405                 case V6:
1406                         hbp = htontcp6(&seg, NULL, &ph6, NULL);
1407                         if (hbp == NULL)
1408                                 return -1;
1409                         ipoput6(tcp->f, hbp, 0, MAXTTL, DFLTTOS, NULL);
1410                         break;
1411                 default:
1412                         panic("sndsnack: version %d", lp->version);
1413         }
1414         lp->lastsend = NOW;
1415         return 0;
1416 }
1417
1418 #define hashipa(a, p) ( ( (a)[IPaddrlen-2] + (a)[IPaddrlen-1] + p )&LHTMASK )
1419
1420 /*
1421  *  put a call into limbo and respond with a SYN ACK
1422  *
1423  *  called with proto locked
1424  */
1425 static void
1426 limbo(struct conv *s, uint8_t * source, uint8_t * dest, Tcp * seg, int version)
1427 {
1428         Limbo *lp, **l;
1429         struct tcppriv *tpriv;
1430         int h;
1431
1432         tpriv = s->p->priv;
1433         h = hashipa(source, seg->source);
1434
1435         for (l = &tpriv->lht[h]; *l != NULL; l = &lp->next) {
1436                 lp = *l;
1437                 if (lp->lport != seg->dest || lp->rport != seg->source
1438                         || lp->version != version)
1439                         continue;
1440                 if (ipcmp(lp->raddr, source) != 0)
1441                         continue;
1442                 if (ipcmp(lp->laddr, dest) != 0)
1443                         continue;
1444
1445                 /* each new SYN restarts the retransmits */
1446                 lp->irs = seg->seq;
1447                 break;
1448         }
1449         lp = *l;
1450         if (lp == NULL) {
1451                 if (tpriv->nlimbo >= Maxlimbo && tpriv->lht[h]) {
1452                         lp = tpriv->lht[h];
1453                         tpriv->lht[h] = lp->next;
1454                         lp->next = NULL;
1455                 } else {
1456                         lp = kzmalloc(sizeof(*lp), 0);
1457                         if (lp == NULL)
1458                                 return;
1459                         tpriv->nlimbo++;
1460                 }
1461                 *l = lp;
1462                 lp->version = version;
1463                 ipmove(lp->laddr, dest);
1464                 ipmove(lp->raddr, source);
1465                 lp->lport = seg->dest;
1466                 lp->rport = seg->source;
1467                 lp->mss = seg->mss;
1468                 lp->rcvscale = seg->ws;
1469                 lp->irs = seg->seq;
1470                 lp->iss = (nrand(1 << 16) << 16) | nrand(1 << 16);
1471         }
1472
1473         if (sndsynack(s->p, lp) < 0) {
1474                 *l = lp->next;
1475                 tpriv->nlimbo--;
1476                 kfree(lp);
1477         }
1478 }
1479
1480 /*
1481  *  resend SYN ACK's once every SYNACK_RXTIMER ms.
1482  */
1483 static void limborexmit(struct Proto *tcp)
1484 {
1485         struct tcppriv *tpriv;
1486         Limbo **l, *lp;
1487         int h;
1488         int seen;
1489         uint32_t now;
1490
1491         tpriv = tcp->priv;
1492
1493         if (!canqlock(&tcp->qlock))
1494                 return;
1495         seen = 0;
1496         now = NOW;
1497         for (h = 0; h < NLHT && seen < tpriv->nlimbo; h++) {
1498                 for (l = &tpriv->lht[h]; *l != NULL && seen < tpriv->nlimbo;) {
1499                         lp = *l;
1500                         seen++;
1501                         if (now - lp->lastsend < (lp->rexmits + 1) * SYNACK_RXTIMER)
1502                                 continue;
1503
1504                         /* time it out after 1 second */
1505                         if (++(lp->rexmits) > 5) {
1506                                 tpriv->nlimbo--;
1507                                 *l = lp->next;
1508                                 kfree(lp);
1509                                 continue;
1510                         }
1511
1512                         /* if we're being attacked, don't bother resending SYN ACK's */
1513                         if (tpriv->nlimbo > 100)
1514                                 continue;
1515
1516                         if (sndsynack(tcp, lp) < 0) {
1517                                 tpriv->nlimbo--;
1518                                 *l = lp->next;
1519                                 kfree(lp);
1520                                 continue;
1521                         }
1522
1523                         l = &lp->next;
1524                 }
1525         }
1526         qunlock(&tcp->qlock);
1527 }
1528
1529 /*
1530  *  lookup call in limbo.  if found, throw it out.
1531  *
1532  *  called with proto locked
1533  */
1534 static void
1535 limborst(struct conv *s, Tcp * segp, uint8_t * src, uint8_t * dst,
1536                  uint8_t version)
1537 {
1538         Limbo *lp, **l;
1539         int h;
1540         struct tcppriv *tpriv;
1541
1542         tpriv = s->p->priv;
1543
1544         /* find a call in limbo */
1545         h = hashipa(src, segp->source);
1546         for (l = &tpriv->lht[h]; *l != NULL; l = &lp->next) {
1547                 lp = *l;
1548                 if (lp->lport != segp->dest || lp->rport != segp->source
1549                         || lp->version != version)
1550                         continue;
1551                 if (ipcmp(lp->laddr, dst) != 0)
1552                         continue;
1553                 if (ipcmp(lp->raddr, src) != 0)
1554                         continue;
1555
1556                 /* RST can only follow the SYN */
1557                 if (segp->seq == lp->irs + 1) {
1558                         tpriv->nlimbo--;
1559                         *l = lp->next;
1560                         kfree(lp);
1561                 }
1562                 break;
1563         }
1564 }
1565
1566 /*
1567  *  come here when we finally get an ACK to our SYN-ACK.
1568  *  lookup call in limbo.  if found, create a new conversation
1569  *
1570  *  called with proto locked
1571  */
1572 static struct conv *tcpincoming(struct conv *s, Tcp * segp, uint8_t * src,
1573                                                                 uint8_t * dst, uint8_t version)
1574 {
1575         struct conv *new;
1576         Tcpctl *tcb;
1577         struct tcppriv *tpriv;
1578         Tcp4hdr *h4;
1579         Tcp6hdr *h6;
1580         Limbo *lp, **l;
1581         int h;
1582
1583         /* unless it's just an ack, it can't be someone coming out of limbo */
1584         if ((segp->flags & SYN) || (segp->flags & ACK) == 0)
1585                 return NULL;
1586
1587         tpriv = s->p->priv;
1588
1589         /* find a call in limbo */
1590         h = hashipa(src, segp->source);
1591         for (l = &tpriv->lht[h]; (lp = *l) != NULL; l = &lp->next) {
1592                 netlog(s->p->f, Logtcp,
1593                            "tcpincoming s %I,0x%x/%I,0x%x d %I,0x%x/%I,0x%x v %d/%d", src,
1594                            segp->source, lp->raddr, lp->rport, dst, segp->dest, lp->laddr,
1595                            lp->lport, version, lp->version);
1596
1597                 if (lp->lport != segp->dest || lp->rport != segp->source
1598                         || lp->version != version)
1599                         continue;
1600                 if (ipcmp(lp->laddr, dst) != 0)
1601                         continue;
1602                 if (ipcmp(lp->raddr, src) != 0)
1603                         continue;
1604
1605                 /* we're assuming no data with the initial SYN */
1606                 if (segp->seq != lp->irs + 1 || segp->ack != lp->iss + 1) {
1607                         netlog(s->p->f, Logtcp, "tcpincoming s 0x%lx/0x%lx a 0x%lx 0x%lx",
1608                                    segp->seq, lp->irs + 1, segp->ack, lp->iss + 1);
1609                         lp = NULL;
1610                 } else {
1611                         tpriv->nlimbo--;
1612                         *l = lp->next;
1613                 }
1614                 break;
1615         }
1616         if (lp == NULL)
1617                 return NULL;
1618
1619         new = Fsnewcall(s, src, segp->source, dst, segp->dest, version);
1620         if (new == NULL)
1621                 return NULL;
1622
1623         memmove(new->ptcl, s->ptcl, sizeof(Tcpctl));
1624         tcb = (Tcpctl *) new->ptcl;
1625         tcb->flags &= ~CLONE;
1626         tcb->timer.arg = new;
1627         tcb->timer.state = TcptimerOFF;
1628         tcb->acktimer.arg = new;
1629         tcb->acktimer.state = TcptimerOFF;
1630         tcb->katimer.arg = new;
1631         tcb->katimer.state = TcptimerOFF;
1632         tcb->rtt_timer.arg = new;
1633         tcb->rtt_timer.state = TcptimerOFF;
1634
1635         tcb->irs = lp->irs;
1636         tcb->rcv.nxt = tcb->irs + 1;
1637         tcb->rcv.urg = tcb->rcv.nxt;
1638
1639         tcb->iss = lp->iss;
1640         tcb->rttseq = tcb->iss;
1641         tcb->snd.wl2 = tcb->iss;
1642         tcb->snd.una = tcb->iss + 1;
1643         tcb->snd.ptr = tcb->iss + 1;
1644         tcb->snd.nxt = tcb->iss + 1;
1645         tcb->flgcnt = 0;
1646         tcb->flags |= SYNACK;
1647
1648         /* our sending max segment size cannot be bigger than what he asked for */
1649         if (lp->mss != 0 && lp->mss < tcb->mss)
1650                 tcb->mss = lp->mss;
1651
1652         /* window scaling */
1653         tcpsetscale(new, tcb, lp->rcvscale, lp->sndscale);
1654
1655         /* the congestion window always starts out as a single segment */
1656         tcb->snd.wnd = segp->wnd;
1657         tcb->cwind = tcb->mss;
1658
1659         /* set initial round trip time */
1660         tcb->sndsyntime = lp->lastsend + lp->rexmits * SYNACK_RXTIMER;
1661         tcpsynackrtt(new);
1662
1663         kfree(lp);
1664
1665         /* set up proto header */
1666         switch (version) {
1667                 case V4:
1668                         h4 = &tcb->protohdr.tcp4hdr;
1669                         memset(h4, 0, sizeof(*h4));
1670                         h4->proto = IP_TCPPROTO;
1671                         hnputs(h4->tcpsport, new->lport);
1672                         hnputs(h4->tcpdport, new->rport);
1673                         v6tov4(h4->tcpsrc, dst);
1674                         v6tov4(h4->tcpdst, src);
1675                         break;
1676                 case V6:
1677                         h6 = &tcb->protohdr.tcp6hdr;
1678                         memset(h6, 0, sizeof(*h6));
1679                         h6->proto = IP_TCPPROTO;
1680                         hnputs(h6->tcpsport, new->lport);
1681                         hnputs(h6->tcpdport, new->rport);
1682                         ipmove(h6->tcpsrc, dst);
1683                         ipmove(h6->tcpdst, src);
1684                         break;
1685                 default:
1686                         panic("tcpincoming: version %d", new->ipversion);
1687         }
1688
1689         tcpsetstate(new, Established);
1690
1691         iphtadd(&tpriv->ht, new);
1692
1693         return new;
1694 }
1695
1696 int seq_within(uint32_t x, uint32_t low, uint32_t high)
1697 {
1698         if (low <= high) {
1699                 if (low <= x && x <= high)
1700                         return 1;
1701         } else {
1702                 if (x >= low || x <= high)
1703                         return 1;
1704         }
1705         return 0;
1706 }
1707
1708 int seq_lt(uint32_t x, uint32_t y)
1709 {
1710         return (int)(x - y) < 0;
1711 }
1712
1713 int seq_le(uint32_t x, uint32_t y)
1714 {
1715         return (int)(x - y) <= 0;
1716 }
1717
1718 int seq_gt(uint32_t x, uint32_t y)
1719 {
1720         return (int)(x - y) > 0;
1721 }
1722
1723 int seq_ge(uint32_t x, uint32_t y)
1724 {
1725         return (int)(x - y) >= 0;
1726 }
1727
1728 /*
1729  *  use the time between the first SYN and it's ack as the
1730  *  initial round trip time
1731  */
1732 void tcpsynackrtt(struct conv *s)
1733 {
1734         Tcpctl *tcb;
1735         int delta;
1736         struct tcppriv *tpriv;
1737
1738         tcb = (Tcpctl *) s->ptcl;
1739         tpriv = s->p->priv;
1740
1741         delta = NOW - tcb->sndsyntime;
1742         tcb->srtt = delta << LOGAGAIN;
1743         tcb->mdev = delta << LOGDGAIN;
1744
1745         /* halt round trip timer */
1746         tcphalt(tpriv, &tcb->rtt_timer);
1747 }
1748
1749 void update(struct conv *s, Tcp * seg)
1750 {
1751         int rtt, delta;
1752         Tcpctl *tcb;
1753         uint32_t acked;
1754         uint32_t expand;
1755         struct tcppriv *tpriv;
1756
1757         tpriv = s->p->priv;
1758         tcb = (Tcpctl *) s->ptcl;
1759
1760         /* if everything has been acked, force output(?) */
1761         if (seq_gt(seg->ack, tcb->snd.nxt)) {
1762                 tcb->flags |= FORCE;
1763                 return;
1764         }
1765
1766         /* added by Dong Lin for fast retransmission */
1767         if (seg->ack == tcb->snd.una
1768                 && tcb->snd.una != tcb->snd.nxt
1769                 && seg->len == 0 && seg->wnd == tcb->snd.wnd) {
1770
1771                 /* this is a pure ack w/o window update */
1772                 netlog(s->p->f, Logtcprxmt, "dupack %lu ack %lu sndwnd %d advwin %d\n",
1773                            tcb->snd.dupacks, seg->ack, tcb->snd.wnd, seg->wnd);
1774
1775                 if (++tcb->snd.dupacks == TCPREXMTTHRESH) {
1776                         /*
1777                          *  tahoe tcp rxt the packet, half sshthresh,
1778                          *  and set cwnd to one packet
1779                          */
1780                         tcb->snd.recovery = 1;
1781                         tcb->snd.rxt = tcb->snd.nxt;
1782                         netlog(s->p->f, Logtcprxmt, "fast rxt %lu, nxt %lu\n", tcb->snd.una,
1783                                    tcb->snd.nxt);
1784                         tcprxmit(s);
1785                 } else {
1786                         /* do reno tcp here. */
1787                 }
1788         }
1789
1790         /*
1791          *  update window
1792          */
1793         if (seq_gt(seg->ack, tcb->snd.wl2)
1794                 || (tcb->snd.wl2 == seg->ack && seg->wnd > tcb->snd.wnd)) {
1795                 tcb->snd.wnd = seg->wnd;
1796                 tcb->snd.wl2 = seg->ack;
1797         }
1798
1799         if (!seq_gt(seg->ack, tcb->snd.una)) {
1800                 /*
1801                  *  don't let us hangup if sending into a closed window and
1802                  *  we're still getting acks
1803                  */
1804                 if ((tcb->flags & RETRAN) && tcb->snd.wnd == 0) {
1805                         tcb->backedoff = MAXBACKMS / 4;
1806                 }
1807                 return;
1808         }
1809
1810         /*
1811          *  any positive ack turns off fast rxt,
1812          *  (should we do new-reno on partial acks?)
1813          */
1814         if (!tcb->snd.recovery || seq_ge(seg->ack, tcb->snd.rxt)) {
1815                 tcb->snd.dupacks = 0;
1816                 tcb->snd.recovery = 0;
1817         } else
1818                 netlog(s->p->f, Logtcp, "rxt next %lu, cwin %u\n", seg->ack,
1819                            tcb->cwind);
1820
1821         /* Compute the new send window size */
1822         acked = seg->ack - tcb->snd.una;
1823
1824         /* avoid slow start and timers for SYN acks */
1825         if ((tcb->flags & SYNACK) == 0) {
1826                 tcb->flags |= SYNACK;
1827                 acked--;
1828                 tcb->flgcnt--;
1829                 goto done;
1830         }
1831
1832         /* slow start as long as we're not recovering from lost packets */
1833         if (tcb->cwind < tcb->snd.wnd && !tcb->snd.recovery) {
1834                 if (tcb->cwind < tcb->ssthresh) {
1835                         expand = tcb->mss;
1836                         if (acked < expand)
1837                                 expand = acked;
1838                 } else
1839                         expand = ((int)tcb->mss * tcb->mss) / tcb->cwind;
1840
1841                 if (tcb->cwind + expand < tcb->cwind)
1842                         expand = tcb->snd.wnd - tcb->cwind;
1843                 if (tcb->cwind + expand > tcb->snd.wnd)
1844                         expand = tcb->snd.wnd - tcb->cwind;
1845                 tcb->cwind += expand;
1846         }
1847
1848         /* Adjust the timers according to the round trip time */
1849         if (tcb->rtt_timer.state == TcptimerON && seq_ge(seg->ack, tcb->rttseq)) {
1850                 tcphalt(tpriv, &tcb->rtt_timer);
1851                 if ((tcb->flags & RETRAN) == 0) {
1852                         tcb->backoff = 0;
1853                         tcb->backedoff = 0;
1854                         rtt = tcb->rtt_timer.start - tcb->rtt_timer.count;
1855                         if (rtt == 0)
1856                                 rtt = 1;        /* otherwise all close systems will rexmit in 0 time */
1857                         rtt *= MSPTICK;
1858                         if (tcb->srtt == 0) {
1859                                 tcb->srtt = rtt << LOGAGAIN;
1860                                 tcb->mdev = rtt << LOGDGAIN;
1861                         } else {
1862                                 delta = rtt - (tcb->srtt >> LOGAGAIN);
1863                                 tcb->srtt += delta;
1864                                 if (tcb->srtt <= 0)
1865                                         tcb->srtt = 1;
1866
1867                                 delta = abs(delta) - (tcb->mdev >> LOGDGAIN);
1868                                 tcb->mdev += delta;
1869                                 if (tcb->mdev <= 0)
1870                                         tcb->mdev = 1;
1871                         }
1872                         tcpsettimer(tcb);
1873                 }
1874         }
1875
1876 done:
1877         if (qdiscard(s->wq, acked) < acked)
1878                 tcb->flgcnt--;
1879
1880         tcb->snd.una = seg->ack;
1881         if (seq_gt(seg->ack, tcb->snd.urg))
1882                 tcb->snd.urg = seg->ack;
1883
1884         if (tcb->snd.una != tcb->snd.nxt)
1885                 tcpgo(tpriv, &tcb->timer);
1886         else
1887                 tcphalt(tpriv, &tcb->timer);
1888
1889         if (seq_lt(tcb->snd.ptr, tcb->snd.una))
1890                 tcb->snd.ptr = tcb->snd.una;
1891
1892         tcb->flags &= ~RETRAN;
1893         tcb->backoff = 0;
1894         tcb->backedoff = 0;
1895 }
1896
1897 void tcpiput(struct Proto *tcp, struct Ipifc *unused, struct block *bp)
1898 {
1899         ERRSTACK(1);
1900         Tcp seg;
1901         Tcp4hdr *h4;
1902         Tcp6hdr *h6;
1903         int hdrlen;
1904         Tcpctl *tcb;
1905         uint16_t length;
1906         uint8_t source[IPaddrlen], dest[IPaddrlen];
1907         struct conv *s;
1908         struct Fs *f;
1909         struct tcppriv *tpriv;
1910         uint8_t version;
1911
1912         f = tcp->f;
1913         tpriv = tcp->priv;
1914
1915         tpriv->stats[InSegs]++;
1916
1917         h4 = (Tcp4hdr *) (bp->rp);
1918         h6 = (Tcp6hdr *) (bp->rp);
1919
1920         if ((h4->vihl & 0xF0) == IP_VER4) {
1921                 version = V4;
1922                 length = nhgets(h4->length);
1923                 v4tov6(dest, h4->tcpdst);
1924                 v4tov6(source, h4->tcpsrc);
1925
1926                 h4->Unused = 0;
1927                 hnputs(h4->tcplen, length - TCP4_PKT);
1928                 if (!(bp->flag & Btcpck) && (h4->tcpcksum[0] || h4->tcpcksum[1]) &&
1929                         ptclcsum(bp, TCP4_IPLEN, length - TCP4_IPLEN)) {
1930                         tpriv->stats[CsumErrs]++;
1931                         tpriv->stats[InErrs]++;
1932                         netlog(f, Logtcp, "bad tcp proto cksum\n");
1933                         freeblist(bp);
1934                         return;
1935                 }
1936
1937                 hdrlen = ntohtcp4(&seg, &bp);
1938                 if (hdrlen < 0) {
1939                         tpriv->stats[HlenErrs]++;
1940                         tpriv->stats[InErrs]++;
1941                         netlog(f, Logtcp, "bad tcp hdr len\n");
1942                         return;
1943                 }
1944
1945                 /* trim the packet to the size claimed by the datagram */
1946                 length -= hdrlen + TCP4_PKT;
1947                 bp = trimblock(bp, hdrlen + TCP4_PKT, length);
1948                 if (bp == NULL) {
1949                         tpriv->stats[LenErrs]++;
1950                         tpriv->stats[InErrs]++;
1951                         netlog(f, Logtcp, "tcp len < 0 after trim\n");
1952                         return;
1953                 }
1954         } else {
1955                 int ttl = h6->ttl;
1956                 int proto = h6->proto;
1957
1958                 version = V6;
1959                 length = nhgets(h6->ploadlen);
1960                 ipmove(dest, h6->tcpdst);
1961                 ipmove(source, h6->tcpsrc);
1962
1963                 h6->ploadlen[0] = h6->ploadlen[1] = h6->proto = 0;
1964                 h6->ttl = proto;
1965                 hnputl(h6->vcf, length);
1966                 if ((h6->tcpcksum[0] || h6->tcpcksum[1]) &&
1967                         ptclcsum(bp, TCP6_IPLEN, length + TCP6_PHDRSIZE)) {
1968                         tpriv->stats[CsumErrs]++;
1969                         tpriv->stats[InErrs]++;
1970                         netlog(f, Logtcp, "bad tcp proto cksum\n");
1971                         freeblist(bp);
1972                         return;
1973                 }
1974                 h6->ttl = ttl;
1975                 h6->proto = proto;
1976                 hnputs(h6->ploadlen, length);
1977
1978                 hdrlen = ntohtcp6(&seg, &bp);
1979                 if (hdrlen < 0) {
1980                         tpriv->stats[HlenErrs]++;
1981                         tpriv->stats[InErrs]++;
1982                         netlog(f, Logtcp, "bad tcp hdr len\n");
1983                         return;
1984                 }
1985
1986                 /* trim the packet to the size claimed by the datagram */
1987                 length -= hdrlen;
1988                 bp = trimblock(bp, hdrlen + TCP6_PKT, length);
1989                 if (bp == NULL) {
1990                         tpriv->stats[LenErrs]++;
1991                         tpriv->stats[InErrs]++;
1992                         netlog(f, Logtcp, "tcp len < 0 after trim\n");
1993                         return;
1994                 }
1995         }
1996
1997         /* lock protocol while searching for a conversation */
1998         qlock(&tcp->qlock);
1999
2000         /* Look for a matching conversation */
2001         s = iphtlook(&tpriv->ht, source, seg.source, dest, seg.dest);
2002         if (s == NULL) {
2003                 netlog(f, Logtcp, "iphtlook failed");
2004 reset:
2005                 qunlock(&tcp->qlock);
2006                 sndrst(tcp, source, dest, length, &seg, version, "no conversation");
2007                 freeblist(bp);
2008                 return;
2009         }
2010
2011         /* if it's a listener, look for the right flags and get a new conv */
2012         tcb = (Tcpctl *) s->ptcl;
2013         if (tcb->state == Listen) {
2014                 if (seg.flags & RST) {
2015                         limborst(s, &seg, source, dest, version);
2016                         qunlock(&tcp->qlock);
2017                         freeblist(bp);
2018                         return;
2019                 }
2020
2021                 /* if this is a new SYN, put the call into limbo */
2022                 if ((seg.flags & SYN) && (seg.flags & ACK) == 0) {
2023                         limbo(s, source, dest, &seg, version);
2024                         qunlock(&tcp->qlock);
2025                         freeblist(bp);
2026                         return;
2027                 }
2028
2029                 /*
2030                  *  if there's a matching call in limbo, tcpincoming will
2031                  *  return it in state Syn_received
2032                  */
2033                 s = tcpincoming(s, &seg, source, dest, version);
2034                 if (s == NULL)
2035                         goto reset;
2036         }
2037
2038         /* The rest of the input state machine is run with the control block
2039          * locked and implements the state machine directly out of the RFC.
2040          * Out-of-band data is ignored - it was always a bad idea.
2041          */
2042         tcb = (Tcpctl *) s->ptcl;
2043         if (waserror()) {
2044                 qunlock(&s->qlock);
2045                 nexterror();
2046         }
2047         qlock(&s->qlock);
2048         qunlock(&tcp->qlock);
2049
2050         /* fix up window */
2051         seg.wnd <<= tcb->rcv.scale;
2052
2053         /* every input packet in puts off the keep alive time out */
2054         tcpsetkacounter(tcb);
2055
2056         switch (tcb->state) {
2057                 case Closed:
2058                         sndrst(tcp, source, dest, length, &seg, version,
2059                                    "sending to Closed");
2060                         goto raise;
2061                 case Syn_sent:
2062                         if (seg.flags & ACK) {
2063                                 if (!seq_within(seg.ack, tcb->iss + 1, tcb->snd.nxt)) {
2064                                         sndrst(tcp, source, dest, length, &seg, version,
2065                                                    "bad seq in Syn_sent");
2066                                         goto raise;
2067                                 }
2068                         }
2069                         if (seg.flags & RST) {
2070                                 if (seg.flags & ACK)
2071                                         localclose(s, Econrefused);
2072                                 goto raise;
2073                         }
2074
2075                         if (seg.flags & SYN) {
2076                                 procsyn(s, &seg);
2077                                 if (seg.flags & ACK) {
2078                                         update(s, &seg);
2079                                         tcpsynackrtt(s);
2080                                         tcpsetstate(s, Established);
2081                                         tcpsetscale(s, tcb, seg.ws, tcb->scale);
2082                                 } else {
2083                                         tcb->time = NOW;
2084                                         tcpsetstate(s, Syn_received);   /* DLP - shouldn't this be a reset? */
2085                                 }
2086
2087                                 if (length != 0 || (seg.flags & FIN))
2088                                         break;
2089
2090                                 freeblist(bp);
2091                                 goto output;
2092                         } else
2093                                 freeblist(bp);
2094
2095                         qunlock(&s->qlock);
2096                         poperror();
2097                         return;
2098                 case Syn_received:
2099                         /* doesn't matter if it's the correct ack, we're just trying to set timing */
2100                         if (seg.flags & ACK)
2101                                 tcpsynackrtt(s);
2102                         break;
2103         }
2104
2105         /*
2106          *  One DOS attack is to open connections to us and then forget about them,
2107          *  thereby tying up a conv at no long term cost to the attacker.
2108          *  This is an attempt to defeat these stateless DOS attacks.  See
2109          *  corresponding code in tcpsendka().
2110          */
2111         if (tcb->state != Syn_received && (seg.flags & RST) == 0) {
2112                 if (tcpporthogdefense
2113                         && seq_within(seg.ack, tcb->snd.una - (1 << 31),
2114                                                   tcb->snd.una - (1 << 29))) {
2115                         printd("stateless hog %I.%d->%I.%d f 0x%x 0x%lx - 0x%lx - 0x%lx\n",
2116                                    source, seg.source, dest, seg.dest, seg.flags,
2117                                    tcb->snd.una - (1 << 31), seg.ack, tcb->snd.una - (1 << 29));
2118                         localclose(s, "stateless hog");
2119                 }
2120         }
2121
2122         /* Cut the data to fit the receive window */
2123         if (tcptrim(tcb, &seg, &bp, &length) == -1) {
2124                 netlog(f, Logtcp, "tcp len < 0, %lu %d\n", seg.seq, length);
2125                 update(s, &seg);
2126                 if (qlen(s->wq) + tcb->flgcnt == 0 && tcb->state == Closing) {
2127                         tcphalt(tpriv, &tcb->rtt_timer);
2128                         tcphalt(tpriv, &tcb->acktimer);
2129                         tcphalt(tpriv, &tcb->katimer);
2130                         tcpsetstate(s, Time_wait);
2131                         tcb->timer.start = MSL2 * (1000 / MSPTICK);
2132                         tcpgo(tpriv, &tcb->timer);
2133                 }
2134                 if (!(seg.flags & RST)) {
2135                         tcb->flags |= FORCE;
2136                         goto output;
2137                 }
2138                 qunlock(&s->qlock);
2139                 poperror();
2140                 return;
2141         }
2142
2143         /* Cannot accept so answer with a rst */
2144         if (length && tcb->state == Closed) {
2145                 sndrst(tcp, source, dest, length, &seg, version, "sending to Closed");
2146                 goto raise;
2147         }
2148
2149         /* The segment is beyond the current receive pointer so
2150          * queue the data in the resequence queue
2151          */
2152         if (seg.seq != tcb->rcv.nxt)
2153                 if (length != 0 || (seg.flags & (SYN | FIN))) {
2154                         update(s, &seg);
2155                         if (addreseq(tcb, tpriv, &seg, bp, length) < 0)
2156                                 printd("reseq %I.%d -> %I.%d\n", s->raddr, s->rport, s->laddr,
2157                                            s->lport);
2158                         tcb->flags |= FORCE;
2159                         goto output;
2160                 }
2161
2162         /*
2163          *  keep looping till we've processed this packet plus any
2164          *  adjacent packets in the resequence queue
2165          */
2166         for (;;) {
2167                 if (seg.flags & RST) {
2168                         if (tcb->state == Established) {
2169                                 tpriv->stats[EstabResets]++;
2170                                 if (tcb->rcv.nxt != seg.seq)
2171                                         printd
2172                                                 ("out of order RST rcvd: %I.%d -> %I.%d, rcv.nxt 0x%lx seq 0x%lx\n",
2173                                                  s->raddr, s->rport, s->laddr, s->lport, tcb->rcv.nxt,
2174                                                  seg.seq);
2175                         }
2176                         localclose(s, Econrefused);
2177                         goto raise;
2178                 }
2179
2180                 if ((seg.flags & ACK) == 0)
2181                         goto raise;
2182
2183                 switch (tcb->state) {
2184                         case Syn_received:
2185                                 if (!seq_within(seg.ack, tcb->snd.una + 1, tcb->snd.nxt)) {
2186                                         sndrst(tcp, source, dest, length, &seg, version,
2187                                                    "bad seq in Syn_received");
2188                                         goto raise;
2189                                 }
2190                                 update(s, &seg);
2191                                 tcpsetstate(s, Established);
2192                         case Established:
2193                         case Close_wait:
2194                                 update(s, &seg);
2195                                 break;
2196                         case Finwait1:
2197                                 update(s, &seg);
2198                                 if (qlen(s->wq) + tcb->flgcnt == 0) {
2199                                         tcphalt(tpriv, &tcb->rtt_timer);
2200                                         tcphalt(tpriv, &tcb->acktimer);
2201                                         tcpsetkacounter(tcb);
2202                                         tcb->time = NOW;
2203                                         tcpsetstate(s, Finwait2);
2204                                         tcb->katimer.start = MSL2 * (1000 / MSPTICK);
2205                                         tcpgo(tpriv, &tcb->katimer);
2206                                 }
2207                                 break;
2208                         case Finwait2:
2209                                 update(s, &seg);
2210                                 break;
2211                         case Closing:
2212                                 update(s, &seg);
2213                                 if (qlen(s->wq) + tcb->flgcnt == 0) {
2214                                         tcphalt(tpriv, &tcb->rtt_timer);
2215                                         tcphalt(tpriv, &tcb->acktimer);
2216                                         tcphalt(tpriv, &tcb->katimer);
2217                                         tcpsetstate(s, Time_wait);
2218                                         tcb->timer.start = MSL2 * (1000 / MSPTICK);
2219                                         tcpgo(tpriv, &tcb->timer);
2220                                 }
2221                                 break;
2222                         case Last_ack:
2223                                 update(s, &seg);
2224                                 if (qlen(s->wq) + tcb->flgcnt == 0) {
2225                                         localclose(s, NULL);
2226                                         goto raise;
2227                                 }
2228                         case Time_wait:
2229                                 tcb->flags |= FORCE;
2230                                 if (tcb->timer.state != TcptimerON)
2231                                         tcpgo(tpriv, &tcb->timer);
2232                 }
2233
2234                 if ((seg.flags & URG) && seg.urg) {
2235                         if (seq_gt(seg.urg + seg.seq, tcb->rcv.urg)) {
2236                                 tcb->rcv.urg = seg.urg + seg.seq;
2237                                 pullblock(&bp, seg.urg);
2238                         }
2239                 } else if (seq_gt(tcb->rcv.nxt, tcb->rcv.urg))
2240                         tcb->rcv.urg = tcb->rcv.nxt;
2241
2242                 if (length == 0) {
2243                         if (bp != NULL)
2244                                 freeblist(bp);
2245                 } else {
2246                         switch (tcb->state) {
2247                                 default:
2248                                         /* Ignore segment text */
2249                                         if (bp != NULL)
2250                                                 freeblist(bp);
2251                                         break;
2252
2253                                 case Syn_received:
2254                                 case Established:
2255                                 case Finwait1:
2256                                         /* If we still have some data place on
2257                                          * receive queue
2258                                          */
2259                                         if (bp) {
2260                                                 bp = packblock(bp);
2261                                                 if (bp == NULL)
2262                                                         panic("tcp packblock");
2263                                                 qpassnolim(s->rq, bp);
2264                                                 bp = NULL;
2265
2266                                                 /*
2267                                                  *  Force an ack every 2 data messages.  This is
2268                                                  *  a hack for rob to make his home system run
2269                                                  *  faster.
2270                                                  *
2271                                                  *  this also keeps the standard TCP congestion
2272                                                  *  control working since it needs an ack every
2273                                                  *  2 max segs worth.  This is not quite that,
2274                                                  *  but under a real stream is equivalent since
2275                                                  *  every packet has a max seg in it.
2276                                                  */
2277                                                 if (++(tcb->rcv.una) >= 2)
2278                                                         tcb->flags |= FORCE;
2279                                         }
2280                                         tcb->rcv.nxt += length;
2281
2282                                         /*
2283                                          *  update our rcv window
2284                                          */
2285                                         tcprcvwin(s);
2286
2287                                         /*
2288                                          *  turn on the acktimer if there's something
2289                                          *  to ack
2290                                          */
2291                                         if (tcb->acktimer.state != TcptimerON)
2292                                                 tcpgo(tpriv, &tcb->acktimer);
2293
2294                                         break;
2295                                 case Finwait2:
2296                                         /* no process to read the data, send a reset */
2297                                         if (bp != NULL)
2298                                                 freeblist(bp);
2299                                         sndrst(tcp, source, dest, length, &seg, version,
2300                                                    "send to Finwait2");
2301                                         qunlock(&s->qlock);
2302                                         poperror();
2303                                         return;
2304                         }
2305                 }
2306
2307                 if (seg.flags & FIN) {
2308                         tcb->flags |= FORCE;
2309
2310                         switch (tcb->state) {
2311                                 case Syn_received:
2312                                 case Established:
2313                                         tcb->rcv.nxt++;
2314                                         tcpsetstate(s, Close_wait);
2315                                         break;
2316                                 case Finwait1:
2317                                         tcb->rcv.nxt++;
2318                                         if (qlen(s->wq) + tcb->flgcnt == 0) {
2319                                                 tcphalt(tpriv, &tcb->rtt_timer);
2320                                                 tcphalt(tpriv, &tcb->acktimer);
2321                                                 tcphalt(tpriv, &tcb->katimer);
2322                                                 tcpsetstate(s, Time_wait);
2323                                                 tcb->timer.start = MSL2 * (1000 / MSPTICK);
2324                                                 tcpgo(tpriv, &tcb->timer);
2325                                         } else
2326                                                 tcpsetstate(s, Closing);
2327                                         break;
2328                                 case Finwait2:
2329                                         tcb->rcv.nxt++;
2330                                         tcphalt(tpriv, &tcb->rtt_timer);
2331                                         tcphalt(tpriv, &tcb->acktimer);
2332                                         tcphalt(tpriv, &tcb->katimer);
2333                                         tcpsetstate(s, Time_wait);
2334                                         tcb->timer.start = MSL2 * (1000 / MSPTICK);
2335                                         tcpgo(tpriv, &tcb->timer);
2336                                         break;
2337                                 case Close_wait:
2338                                 case Closing:
2339                                 case Last_ack:
2340                                         break;
2341                                 case Time_wait:
2342                                         tcpgo(tpriv, &tcb->timer);
2343                                         break;
2344                         }
2345                 }
2346
2347                 /*
2348                  *  get next adjacent segment from the resequence queue.
2349                  *  dump/trim any overlapping segments
2350                  */
2351                 for (;;) {
2352                         if (tcb->reseq == NULL)
2353                                 goto output;
2354
2355                         if (seq_ge(tcb->rcv.nxt, tcb->reseq->seg.seq) == 0)
2356                                 goto output;
2357
2358                         getreseq(tcb, &seg, &bp, &length);
2359
2360                         if (tcptrim(tcb, &seg, &bp, &length) == 0)
2361                                 break;
2362                 }
2363         }
2364 output:
2365         tcpoutput(s);
2366         qunlock(&s->qlock);
2367         poperror();
2368         return;
2369 raise:
2370         qunlock(&s->qlock);
2371         poperror();
2372         freeblist(bp);
2373         tcpkick(s);
2374 }
2375
2376 /*
2377  *  always enters and exits with the s locked.  We drop
2378  *  the lock to ipoput the packet so some care has to be
2379  *  taken by callers.
2380  */
2381 void tcpoutput(struct conv *s)
2382 {
2383         Tcp seg;
2384         int msgs;
2385         Tcpctl *tcb;
2386         struct block *hbp, *bp;
2387         int sndcnt, n;
2388         uint32_t ssize, dsize, usable, sent;
2389         struct Fs *f;
2390         struct tcppriv *tpriv;
2391         uint8_t version;
2392
2393         f = s->p->f;
2394         tpriv = s->p->priv;
2395         version = s->ipversion;
2396
2397         for (msgs = 0; msgs < 100; msgs++) {
2398                 tcb = (Tcpctl *) s->ptcl;
2399
2400                 switch (tcb->state) {
2401                         case Listen:
2402                         case Closed:
2403                         case Finwait2:
2404                                 return;
2405                 }
2406
2407                 /* force an ack when a window has opened up */
2408                 if (tcb->rcv.blocked && tcb->rcv.wnd > 0) {
2409                         tcb->rcv.blocked = 0;
2410                         tcb->flags |= FORCE;
2411                 }
2412
2413                 sndcnt = qlen(s->wq) + tcb->flgcnt;
2414                 sent = tcb->snd.ptr - tcb->snd.una;
2415
2416                 /* Don't send anything else until our SYN has been acked */
2417                 if (tcb->snd.ptr != tcb->iss && (tcb->flags & SYNACK) == 0)
2418                         break;
2419
2420                 /* Compute usable segment based on offered window and limit
2421                  * window probes to one
2422                  */
2423                 if (tcb->snd.wnd == 0) {
2424                         if (sent != 0) {
2425                                 if ((tcb->flags & FORCE) == 0)
2426                                         break;
2427 //              tcb->snd.ptr = tcb->snd.una;
2428                         }
2429                         usable = 1;
2430                 } else {
2431                         usable = tcb->cwind;
2432                         if (tcb->snd.wnd < usable)
2433                                 usable = tcb->snd.wnd;
2434                         usable -= sent;
2435                 }
2436                 ssize = sndcnt - sent;
2437                 if (ssize && usable < 2)
2438                         netlog(s->p->f, Logtcp, "throttled snd.wnd %lu cwind %lu\n",
2439                                    tcb->snd.wnd, tcb->cwind);
2440                 if (usable < ssize)
2441                         ssize = usable;
2442                 if (tcb->mss < ssize)
2443                         ssize = tcb->mss;
2444                 dsize = ssize;
2445                 seg.urg = 0;
2446
2447                 if (ssize == 0)
2448                         if ((tcb->flags & FORCE) == 0)
2449                                 break;
2450
2451                 tcb->flags &= ~FORCE;
2452                 tcprcvwin(s);
2453
2454                 /* By default we will generate an ack */
2455                 tcphalt(tpriv, &tcb->acktimer);
2456                 tcb->rcv.una = 0;
2457                 seg.source = s->lport;
2458                 seg.dest = s->rport;
2459                 seg.flags = ACK;
2460                 seg.mss = 0;
2461                 seg.ws = 0;
2462                 switch (tcb->state) {
2463                         case Syn_sent:
2464                                 seg.flags = 0;
2465                                 if (tcb->snd.ptr == tcb->iss) {
2466                                         seg.flags |= SYN;
2467                                         dsize--;
2468                                         seg.mss = tcb->mss;
2469                                         seg.ws = tcb->scale;
2470                                 }
2471                                 break;
2472                         case Syn_received:
2473                                 /*
2474                                  *  don't send any data with a SYN/ACK packet
2475                                  *  because Linux rejects the packet in its
2476                                  *  attempt to solve the SYN attack problem
2477                                  */
2478                                 if (tcb->snd.ptr == tcb->iss) {
2479                                         seg.flags |= SYN;
2480                                         dsize = 0;
2481                                         ssize = 1;
2482                                         seg.mss = tcb->mss;
2483                                         seg.ws = tcb->scale;
2484                                 }
2485                                 break;
2486                 }
2487                 seg.seq = tcb->snd.ptr;
2488                 seg.ack = tcb->rcv.nxt;
2489                 seg.wnd = tcb->rcv.wnd;
2490
2491                 /* Pull out data to send */
2492                 bp = NULL;
2493                 if (dsize != 0) {
2494                         bp = qcopy(s->wq, dsize, sent);
2495                         if (BLEN(bp) != dsize) {
2496                                 seg.flags |= FIN;
2497                                 dsize--;
2498                         }
2499                 }
2500
2501                 if (sent + dsize == sndcnt)
2502                         seg.flags |= PSH;
2503
2504                 /* keep track of balance of resent data */
2505                 if (seq_lt(tcb->snd.ptr, tcb->snd.nxt)) {
2506                         n = tcb->snd.nxt - tcb->snd.ptr;
2507                         if (ssize < n)
2508                                 n = ssize;
2509                         tcb->resent += n;
2510                         netlog(f, Logtcp, "rexmit: %I.%d -> %I.%d ptr 0x%lx nxt 0x%lx\n",
2511                                    s->raddr, s->rport, s->laddr, s->lport, tcb->snd.ptr,
2512                                    tcb->snd.nxt);
2513                         tpriv->stats[RetransSegs]++;
2514                 }
2515
2516                 tcb->snd.ptr += ssize;
2517
2518                 /* Pull up the send pointer so we can accept acks
2519                  * for this window
2520                  */
2521                 if (seq_gt(tcb->snd.ptr, tcb->snd.nxt))
2522                         tcb->snd.nxt = tcb->snd.ptr;
2523
2524                 /* Build header, link data and compute cksum */
2525                 switch (version) {
2526                         case V4:
2527                                 tcb->protohdr.tcp4hdr.vihl = IP_VER4;
2528                                 hbp = htontcp4(&seg, bp, &tcb->protohdr.tcp4hdr, tcb);
2529                                 if (hbp == NULL) {
2530                                         freeblist(bp);
2531                                         return;
2532                                 }
2533                                 break;
2534                         case V6:
2535                                 tcb->protohdr.tcp6hdr.vcf[0] = IP_VER6;
2536                                 hbp = htontcp6(&seg, bp, &tcb->protohdr.tcp6hdr, tcb);
2537                                 if (hbp == NULL) {
2538                                         freeblist(bp);
2539                                         return;
2540                                 }
2541                                 break;
2542                         default:
2543                                 hbp = NULL;     /* to suppress a warning */
2544                                 panic("tcpoutput: version %d", version);
2545                 }
2546
2547                 /* Start the transmission timers if there is new data and we
2548                  * expect acknowledges
2549                  */
2550                 if (ssize != 0) {
2551                         if (tcb->timer.state != TcptimerON)
2552                                 tcpgo(tpriv, &tcb->timer);
2553
2554                         /*  If round trip timer isn't running, start it.
2555                          *  measure the longest packet only in case the
2556                          *  transmission time dominates RTT
2557                          */
2558                         if (tcb->rtt_timer.state != TcptimerON)
2559                                 if (ssize == tcb->mss) {
2560                                         tcpgo(tpriv, &tcb->rtt_timer);
2561                                         tcb->rttseq = tcb->snd.ptr;
2562                                 }
2563                 }
2564
2565                 tpriv->stats[OutSegs]++;
2566
2567                 /* put off the next keep alive */
2568                 tcpgo(tpriv, &tcb->katimer);
2569
2570                 switch (version) {
2571                         case V4:
2572                                 if (ipoput4(f, hbp, 0, s->ttl, s->tos, s) < 0) {
2573                                         /* a negative return means no route */
2574                                         localclose(s, "no route");
2575                                 }
2576                                 break;
2577                         case V6:
2578                                 if (ipoput6(f, hbp, 0, s->ttl, s->tos, s) < 0) {
2579                                         /* a negative return means no route */
2580                                         localclose(s, "no route");
2581                                 }
2582                                 break;
2583                         default:
2584                                 panic("tcpoutput2: version %d", version);
2585                 }
2586                 if ((msgs % 4) == 1) {
2587                         qunlock(&s->qlock);
2588                         kthread_yield();
2589                         qlock(&s->qlock);
2590                 }
2591         }
2592 }
2593
2594 /*
2595  *  the BSD convention (hack?) for keep alives.  resend last uint8_t acked.
2596  */
2597 void tcpsendka(struct conv *s)
2598 {
2599         Tcp seg;
2600         Tcpctl *tcb;
2601         struct block *hbp, *dbp;
2602
2603         tcb = (Tcpctl *) s->ptcl;
2604
2605         dbp = NULL;
2606         seg.urg = 0;
2607         seg.source = s->lport;
2608         seg.dest = s->rport;
2609         seg.flags = ACK | PSH;
2610         seg.mss = 0;
2611         seg.ws = 0;
2612         if (tcpporthogdefense)
2613                 seg.seq = tcb->snd.una - (1 << 30) - nrand(1 << 20);
2614         else
2615                 seg.seq = tcb->snd.una - 1;
2616         seg.ack = tcb->rcv.nxt;
2617         tcb->rcv.una = 0;
2618         seg.wnd = tcb->rcv.wnd;
2619         if (tcb->state == Finwait2) {
2620                 seg.flags |= FIN;
2621         } else {
2622                 dbp = allocb(1);
2623                 dbp->wp++;
2624         }
2625
2626         if (isv4(s->raddr)) {
2627                 /* Build header, link data and compute cksum */
2628                 tcb->protohdr.tcp4hdr.vihl = IP_VER4;
2629                 hbp = htontcp4(&seg, dbp, &tcb->protohdr.tcp4hdr, tcb);
2630                 if (hbp == NULL) {
2631                         freeblist(dbp);
2632                         return;
2633                 }
2634                 ipoput4(s->p->f, hbp, 0, s->ttl, s->tos, s);
2635         } else {
2636                 /* Build header, link data and compute cksum */
2637                 tcb->protohdr.tcp6hdr.vcf[0] = IP_VER6;
2638                 hbp = htontcp6(&seg, dbp, &tcb->protohdr.tcp6hdr, tcb);
2639                 if (hbp == NULL) {
2640                         freeblist(dbp);
2641                         return;
2642                 }
2643                 ipoput6(s->p->f, hbp, 0, s->ttl, s->tos, s);
2644         }
2645 }
2646
2647 /*
2648  *  set connection to time out after 12 minutes
2649  */
2650 void tcpsetkacounter(Tcpctl * tcb)
2651 {
2652         tcb->kacounter = (12 * 60 * 1000) / (tcb->katimer.start * MSPTICK);
2653         if (tcb->kacounter < 3)
2654                 tcb->kacounter = 3;
2655 }
2656
2657 /*
2658  *  if we've timed out, close the connection
2659  *  otherwise, send a keepalive and restart the timer
2660  */
2661 void tcpkeepalive(void *v)
2662 {
2663         ERRSTACK(1);
2664         Tcpctl *tcb;
2665         struct conv *s;
2666
2667         s = v;
2668         tcb = (Tcpctl *) s->ptcl;
2669         if (waserror()) {
2670                 qunlock(&s->qlock);
2671                 nexterror();
2672         }
2673         qlock(&s->qlock);
2674         if (tcb->state != Closed) {
2675                 if (--(tcb->kacounter) <= 0) {
2676                         localclose(s, Etimedout);
2677                 } else {
2678                         tcpsendka(s);
2679                         tcpgo(s->p->priv, &tcb->katimer);
2680                 }
2681         }
2682         qunlock(&s->qlock);
2683         poperror();
2684 }
2685
2686 /*
2687  *  start keepalive timer
2688  */
2689 char *tcpstartka(struct conv *s, char **f, int n)
2690 {
2691         Tcpctl *tcb;
2692         int x;
2693
2694         tcb = (Tcpctl *) s->ptcl;
2695         if (tcb->state != Established)
2696                 return "connection must be in Establised state";
2697         if (n > 1) {
2698                 x = atoi(f[1]);
2699                 if (x >= MSPTICK)
2700                         tcb->katimer.start = x / MSPTICK;
2701         }
2702         tcpsetkacounter(tcb);
2703         tcpgo(s->p->priv, &tcb->katimer);
2704
2705         return NULL;
2706 }
2707
2708 /*
2709  *  turn checksums on/off
2710  */
2711 char *tcpsetchecksum(struct conv *s, char **f, int unused)
2712 {
2713         Tcpctl *tcb;
2714
2715         tcb = (Tcpctl *) s->ptcl;
2716         tcb->nochecksum = !atoi(f[1]);
2717
2718         return NULL;
2719 }
2720
2721 void tcprxmit(struct conv *s)
2722 {
2723         Tcpctl *tcb;
2724
2725         tcb = (Tcpctl *) s->ptcl;
2726
2727         tcb->flags |= RETRAN | FORCE;
2728         tcb->snd.ptr = tcb->snd.una;
2729
2730         /*
2731          *  We should be halving the slow start threshhold (down to one
2732          *  mss) but leaving it at mss seems to work well enough
2733          */
2734         tcb->ssthresh = tcb->mss;
2735
2736         /*
2737          *  pull window down to a single packet
2738          */
2739         tcb->cwind = tcb->mss;
2740         tcpoutput(s);
2741 }
2742
2743 void tcptimeout(void *arg)
2744 {
2745         ERRSTACK(1);
2746         struct conv *s;
2747         Tcpctl *tcb;
2748         int maxback;
2749         struct tcppriv *tpriv;
2750
2751         s = (struct conv *)arg;
2752         tpriv = s->p->priv;
2753         tcb = (Tcpctl *) s->ptcl;
2754
2755         if (waserror()) {
2756                 qunlock(&s->qlock);
2757                 nexterror();
2758         }
2759         qlock(&s->qlock);
2760         switch (tcb->state) {
2761                 default:
2762                         tcb->backoff++;
2763                         if (tcb->state == Syn_sent)
2764                                 maxback = MAXBACKMS / 2;
2765                         else
2766                                 maxback = MAXBACKMS;
2767                         tcb->backedoff += tcb->timer.start * MSPTICK;
2768                         if (tcb->backedoff >= maxback) {
2769                                 localclose(s, Etimedout);
2770                                 break;
2771                         }
2772                         netlog(s->p->f, Logtcprxmt, "timeout rexmit 0x%lx %d/%d\n",
2773                                    tcb->snd.una, tcb->timer.start, NOW);
2774                         tcpsettimer(tcb);
2775                         tcprxmit(s);
2776                         tpriv->stats[RetransTimeouts]++;
2777                         tcb->snd.dupacks = 0;
2778                         break;
2779                 case Time_wait:
2780                         localclose(s, NULL);
2781                         break;
2782                 case Closed:
2783                         break;
2784         }
2785         qunlock(&s->qlock);
2786         poperror();
2787 }
2788
2789 int inwindow(Tcpctl * tcb, int seq)
2790 {
2791         return seq_within(seq, tcb->rcv.nxt, tcb->rcv.nxt + tcb->rcv.wnd - 1);
2792 }
2793
2794 /*
2795  *  set up state for a received SYN (or SYN ACK) packet
2796  */
2797 void procsyn(struct conv *s, Tcp * seg)
2798 {
2799         Tcpctl *tcb;
2800
2801         tcb = (Tcpctl *) s->ptcl;
2802         tcb->flags |= FORCE;
2803
2804         tcb->rcv.nxt = seg->seq + 1;
2805         tcb->rcv.urg = tcb->rcv.nxt;
2806         tcb->irs = seg->seq;
2807
2808         /* our sending max segment size cannot be bigger than what he asked for */
2809         if (seg->mss != 0 && seg->mss < tcb->mss)
2810                 tcb->mss = seg->mss;
2811
2812         /* the congestion window always starts out as a single segment */
2813         tcb->snd.wnd = seg->wnd;
2814         tcb->cwind = tcb->mss;
2815 }
2816
2817 int
2818 addreseq(Tcpctl * tcb, struct tcppriv *tpriv, Tcp * seg,
2819                  struct block *bp, uint16_t length)
2820 {
2821         Reseq *rp, *rp1;
2822         int i, rqlen, qmax;
2823
2824         rp = kzmalloc(sizeof(Reseq), 0);
2825         if (rp == NULL) {
2826                 freeblist(bp);  /* bp always consumed by add_reseq */
2827                 return 0;
2828         }
2829
2830         rp->seg = *seg;
2831         rp->bp = bp;
2832         rp->length = length;
2833
2834         /* Place on reassembly list sorting by starting seq number */
2835         rp1 = tcb->reseq;
2836         if (rp1 == NULL || seq_lt(seg->seq, rp1->seg.seq)) {
2837                 rp->next = rp1;
2838                 tcb->reseq = rp;
2839                 if (rp->next != NULL)
2840                         tpriv->stats[OutOfOrder]++;
2841                 return 0;
2842         }
2843
2844         rqlen = 0;
2845         for (i = 0;; i++) {
2846                 rqlen += rp1->length;
2847                 if (rp1->next == NULL || seq_lt(seg->seq, rp1->next->seg.seq)) {
2848                         rp->next = rp1->next;
2849                         rp1->next = rp;
2850                         if (rp->next != NULL)
2851                                 tpriv->stats[OutOfOrder]++;
2852                         break;
2853                 }
2854                 rp1 = rp1->next;
2855         }
2856         qmax = QMAX << tcb->rcv.scale;
2857         if (rqlen > qmax) {
2858                 printd("resequence queue > window: %d > %d\n", rqlen, qmax);
2859                 i = 0;
2860                 for (rp1 = tcb->reseq; rp1 != NULL; rp1 = rp1->next) {
2861                         printd("0x%#lx 0x%#lx 0x%#x\n", rp1->seg.seq,
2862                                    rp1->seg.ack, rp1->seg.flags);
2863                         if (i++ > 10) {
2864                                 printd("...\n");
2865                                 break;
2866                         }
2867                 }
2868
2869                 // delete entire reassembly queue; wait for retransmit.
2870                 // - should we be smarter and only delete the tail?
2871                 for (rp = tcb->reseq; rp != NULL; rp = rp1) {
2872                         rp1 = rp->next;
2873                         freeblist(rp->bp);
2874                         kfree(rp);
2875                 }
2876                 tcb->reseq = NULL;
2877
2878                 return -1;
2879         }
2880         return 0;
2881 }
2882
2883 void getreseq(Tcpctl * tcb, Tcp * seg, struct block **bp, uint16_t * length)
2884 {
2885         Reseq *rp;
2886
2887         rp = tcb->reseq;
2888         if (rp == NULL)
2889                 return;
2890
2891         tcb->reseq = rp->next;
2892
2893         *seg = rp->seg;
2894         *bp = rp->bp;
2895         *length = rp->length;
2896
2897         kfree(rp);
2898 }
2899
2900 int tcptrim(Tcpctl * tcb, Tcp * seg, struct block **bp, uint16_t * length)
2901 {
2902         uint16_t len;
2903         uint8_t accept;
2904         int dupcnt, excess;
2905
2906         accept = 0;
2907         len = *length;
2908         if (seg->flags & SYN)
2909                 len++;
2910         if (seg->flags & FIN)
2911                 len++;
2912
2913         if (tcb->rcv.wnd == 0) {
2914                 if (len == 0 && seg->seq == tcb->rcv.nxt)
2915                         return 0;
2916         } else {
2917                 /* Some part of the segment should be in the window */
2918                 if (inwindow(tcb, seg->seq))
2919                         accept++;
2920                 else if (len != 0) {
2921                         if (inwindow(tcb, seg->seq + len - 1) ||
2922                                 seq_within(tcb->rcv.nxt, seg->seq, seg->seq + len - 1))
2923                                 accept++;
2924                 }
2925         }
2926         if (!accept) {
2927                 freeblist(*bp);
2928                 return -1;
2929         }
2930         dupcnt = tcb->rcv.nxt - seg->seq;
2931         if (dupcnt > 0) {
2932                 tcb->rerecv += dupcnt;
2933                 if (seg->flags & SYN) {
2934                         seg->flags &= ~SYN;
2935                         seg->seq++;
2936
2937                         if (seg->urg > 1)
2938                                 seg->urg--;
2939                         else
2940                                 seg->flags &= ~URG;
2941                         dupcnt--;
2942                 }
2943                 if (dupcnt > 0) {
2944                         pullblock(bp, (uint16_t) dupcnt);
2945                         seg->seq += dupcnt;
2946                         *length -= dupcnt;
2947
2948                         if (seg->urg > dupcnt)
2949                                 seg->urg -= dupcnt;
2950                         else {
2951                                 seg->flags &= ~URG;
2952                                 seg->urg = 0;
2953                         }
2954                 }
2955         }
2956         excess = seg->seq + *length - (tcb->rcv.nxt + tcb->rcv.wnd);
2957         if (excess > 0) {
2958                 tcb->rerecv += excess;
2959                 *length -= excess;
2960                 *bp = trimblock(*bp, 0, *length);
2961                 if (*bp == NULL)
2962                         panic("presotto is a boofhead");
2963                 seg->flags &= ~FIN;
2964         }
2965         return 0;
2966 }
2967
2968 void tcpadvise(struct Proto *tcp, struct block *bp, char *msg)
2969 {
2970         Tcp4hdr *h4;
2971         Tcp6hdr *h6;
2972         Tcpctl *tcb;
2973         uint8_t source[IPaddrlen];
2974         uint8_t dest[IPaddrlen];
2975         uint16_t psource, pdest;
2976         struct conv *s, **p;
2977
2978         h4 = (Tcp4hdr *) (bp->rp);
2979         h6 = (Tcp6hdr *) (bp->rp);
2980
2981         if ((h4->vihl & 0xF0) == IP_VER4) {
2982                 v4tov6(dest, h4->tcpdst);
2983                 v4tov6(source, h4->tcpsrc);
2984                 psource = nhgets(h4->tcpsport);
2985                 pdest = nhgets(h4->tcpdport);
2986         } else {
2987                 ipmove(dest, h6->tcpdst);
2988                 ipmove(source, h6->tcpsrc);
2989                 psource = nhgets(h6->tcpsport);
2990                 pdest = nhgets(h6->tcpdport);
2991         }
2992
2993         /* Look for a connection */
2994         qlock(&tcp->qlock);
2995         for (p = tcp->conv; *p; p++) {
2996                 s = *p;
2997                 tcb = (Tcpctl *) s->ptcl;
2998                 if (s->rport == pdest)
2999                         if (s->lport == psource)
3000                                 if (tcb->state != Closed)
3001                                         if (ipcmp(s->raddr, dest) == 0)
3002                                                 if (ipcmp(s->laddr, source) == 0) {
3003                                                         qlock(&s->qlock);
3004                                                         qunlock(&tcp->qlock);
3005                                                         switch (tcb->state) {
3006                                                                 case Syn_sent:
3007                                                                         localclose(s, msg);
3008                                                                         break;
3009                                                         }
3010                                                         qunlock(&s->qlock);
3011                                                         freeblist(bp);
3012                                                         return;
3013                                                 }
3014         }
3015         qunlock(&tcp->qlock);
3016         freeblist(bp);
3017 }
3018
3019 static char *tcpporthogdefensectl(char *val)
3020 {
3021         if (strcmp(val, "on") == 0)
3022                 tcpporthogdefense = 1;
3023         else if (strcmp(val, "off") == 0)
3024                 tcpporthogdefense = 0;
3025         else
3026                 return "unknown value for tcpporthogdefense";
3027         return NULL;
3028 }
3029
3030 /* called with c qlocked */
3031 char *tcpctl(struct conv *c, char **f, int n)
3032 {
3033         if (n == 1 && strcmp(f[0], "hangup") == 0)
3034                 return tcphangup(c);
3035         if (n >= 1 && strcmp(f[0], "keepalive") == 0)
3036                 return tcpstartka(c, f, n);
3037         if (n >= 1 && strcmp(f[0], "checksum") == 0)
3038                 return tcpsetchecksum(c, f, n);
3039         if (n >= 1 && strcmp(f[0], "tcpporthogdefense") == 0)
3040                 return tcpporthogdefensectl(f[1]);
3041         return "unknown control request";
3042 }
3043
3044 int tcpstats(struct Proto *tcp, char *buf, int len)
3045 {
3046         struct tcppriv *priv;
3047         char *p, *e;
3048         int i;
3049
3050         priv = tcp->priv;
3051         p = buf;
3052         e = p + len;
3053         for (i = 0; i < Nstats; i++)
3054                 p = seprintf(p, e, "%s: %lu\n", statnames[i], priv->stats[i]);
3055         return p - buf;
3056 }
3057
3058 /*
3059  *  garbage collect any stale conversations:
3060  *      - SYN received but no SYN-ACK after 5 seconds (could be the SYN attack)
3061  *      - Finwait2 after 5 minutes
3062  *
3063  *  this is called whenever we run out of channels.  Both checks are
3064  *  of questionable validity so we try to use them only when we're
3065  *  up against the wall.
3066  */
3067 int tcpgc(struct Proto *tcp)
3068 {
3069         struct conv *c, **pp, **ep;
3070         int n;
3071         Tcpctl *tcb;
3072
3073         n = 0;
3074         ep = &tcp->conv[tcp->nc];
3075         for (pp = tcp->conv; pp < ep; pp++) {
3076                 c = *pp;
3077                 if (c == NULL)
3078                         break;
3079                 if (!canqlock(&c->qlock))
3080                         continue;
3081                 tcb = (Tcpctl *) c->ptcl;
3082                 switch (tcb->state) {
3083                         case Syn_received:
3084                                 if (NOW - tcb->time > 5000) {
3085                                         localclose(c, "timed out");
3086                                         n++;
3087                                 }
3088                                 break;
3089                         case Finwait2:
3090                                 if (NOW - tcb->time > 5 * 60 * 1000) {
3091                                         localclose(c, "timed out");
3092                                         n++;
3093                                 }
3094                                 break;
3095                 }
3096                 qunlock(&c->qlock);
3097         }
3098         return n;
3099 }
3100
3101 void tcpsettimer(Tcpctl * tcb)
3102 {
3103         int x;
3104
3105         /* round trip dependency */
3106         x = backoff(tcb->backoff) *
3107                 (tcb->mdev + (tcb->srtt >> LOGAGAIN) + MSPTICK) / MSPTICK;
3108
3109         /* bounded twixt 1/2 and 64 seconds */
3110         if (x < 500 / MSPTICK)
3111                 x = 500 / MSPTICK;
3112         else if (x > (64000 / MSPTICK))
3113                 x = 64000 / MSPTICK;
3114         tcb->timer.start = x;
3115 }
3116
3117 void tcpinit(struct Fs *fs)
3118 {
3119         struct Proto *tcp;
3120         struct tcppriv *tpriv;
3121
3122         tcp = kzmalloc(sizeof(struct Proto), 0);
3123         tpriv = tcp->priv = kzmalloc(sizeof(struct tcppriv), 0);
3124         qlock_init(&tpriv->tl);
3125         qlock_init(&tpriv->apl);
3126         tcp->name = "tcp";
3127         tcp->connect = tcpconnect;
3128         tcp->announce = tcpannounce;
3129         tcp->ctl = tcpctl;
3130         tcp->state = tcpstate;
3131         tcp->create = tcpcreate;
3132         tcp->close = tcpclose;
3133         tcp->rcv = tcpiput;
3134         tcp->advise = tcpadvise;
3135         tcp->stats = tcpstats;
3136         tcp->inuse = tcpinuse;
3137         tcp->gc = tcpgc;
3138         tcp->ipproto = IP_TCPPROTO;
3139         tcp->nc = scalednconv();
3140         tcp->ptclsize = sizeof(Tcpctl);
3141         tpriv->stats[MaxConn] = tcp->nc;
3142
3143         Fsproto(fs, tcp);
3144 }
3145
3146 void
3147 tcpsetscale(struct conv *s, Tcpctl * tcb, uint16_t rcvscale, uint16_t sndscale)
3148 {
3149         if (rcvscale) {
3150                 tcb->rcv.scale = rcvscale & 0xff;
3151                 tcb->snd.scale = sndscale & 0xff;
3152                 tcb->window = QMAX << tcb->snd.scale;
3153                 qsetlimit(s->rq, tcb->window);
3154         } else {
3155                 tcb->rcv.scale = 0;
3156                 tcb->snd.scale = 0;
3157                 tcb->window = QMAX;
3158                 qsetlimit(s->rq, tcb->window);
3159         }
3160 }