linux 2.6.16.38 w/ vs2.0.3-rc1
[linux-2.6.git] / net / ipv4 / netfilter / ip_conntrack_proto_tcp.c
1 /* (C) 1999-2001 Paul `Rusty' Russell
2  * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>:
9  *      - Real stateful connection tracking
10  *      - Modified state transitions table
11  *      - Window scaling support added
12  *      - SACK support added
13  *
14  * Willy Tarreau:
15  *      - State table bugfixes
16  *      - More robust state changes
17  *      - Tuning timer parameters
18  *
19  * version 2.2
20  */
21
22 #include <linux/config.h>
23 #include <linux/types.h>
24 #include <linux/sched.h>
25 #include <linux/timer.h>
26 #include <linux/netfilter.h>
27 #include <linux/module.h>
28 #include <linux/in.h>
29 #include <linux/ip.h>
30 #include <linux/tcp.h>
31 #include <linux/spinlock.h>
32
33 #include <net/tcp.h>
34
35 #include <linux/netfilter_ipv4.h>
36 #include <linux/netfilter_ipv4/ip_conntrack.h>
37 #include <linux/netfilter_ipv4/ip_conntrack_protocol.h>
38
39 #if 0
40 #define DEBUGP printk
41 #define DEBUGP_VARS
42 #else
43 #define DEBUGP(format, args...)
44 #endif
45
46 /* Protects conntrack->proto.tcp */
47 static DEFINE_RWLOCK(tcp_lock);
48
49 /* "Be conservative in what you do, 
50     be liberal in what you accept from others." 
51     If it's non-zero, we mark only out of window RST segments as INVALID. */
52 int ip_ct_tcp_be_liberal = 0;
53
54 /* When connection is picked up from the middle, how many packets are required
55    to pass in each direction when we assume we are in sync - if any side uses
56    window scaling, we lost the game. 
57    If it is set to zero, we disable picking up already established 
58    connections. */
59 int ip_ct_tcp_loose = 3;
60
61 /* Max number of the retransmitted packets without receiving an (acceptable) 
62    ACK from the destination. If this number is reached, a shorter timer 
63    will be started. */
64 int ip_ct_tcp_max_retrans = 3;
65
66   /* FIXME: Examine ipfilter's timeouts and conntrack transitions more
67      closely.  They're more complex. --RR */
68
69 static const char *tcp_conntrack_names[] = {
70         "NONE",
71         "SYN_SENT",
72         "SYN_RECV",
73         "ESTABLISHED",
74         "FIN_WAIT",
75         "CLOSE_WAIT",
76         "LAST_ACK",
77         "TIME_WAIT",
78         "CLOSE",
79         "LISTEN"
80 };
81   
82 #define SECS * HZ
83 #define MINS * 60 SECS
84 #define HOURS * 60 MINS
85 #define DAYS * 24 HOURS
86
87 unsigned int ip_ct_tcp_timeout_syn_sent =      2 MINS;
88 unsigned int ip_ct_tcp_timeout_syn_recv =     60 SECS;
89 unsigned int ip_ct_tcp_timeout_established =   5 DAYS;
90 unsigned int ip_ct_tcp_timeout_fin_wait =      2 MINS;
91 unsigned int ip_ct_tcp_timeout_close_wait =   60 SECS;
92 unsigned int ip_ct_tcp_timeout_last_ack =     30 SECS;
93 unsigned int ip_ct_tcp_timeout_time_wait =     2 MINS;
94 unsigned int ip_ct_tcp_timeout_close =        10 SECS;
95
96 /* RFC1122 says the R2 limit should be at least 100 seconds.
97    Linux uses 15 packets as limit, which corresponds 
98    to ~13-30min depending on RTO. */
99 unsigned int ip_ct_tcp_timeout_max_retrans =     5 MINS;
100  
101 static const unsigned int * tcp_timeouts[]
102 = { NULL,                              /*      TCP_CONNTRACK_NONE */
103     &ip_ct_tcp_timeout_syn_sent,       /*      TCP_CONNTRACK_SYN_SENT, */
104     &ip_ct_tcp_timeout_syn_recv,       /*      TCP_CONNTRACK_SYN_RECV, */
105     &ip_ct_tcp_timeout_established,    /*      TCP_CONNTRACK_ESTABLISHED,      */
106     &ip_ct_tcp_timeout_fin_wait,       /*      TCP_CONNTRACK_FIN_WAIT, */
107     &ip_ct_tcp_timeout_close_wait,     /*      TCP_CONNTRACK_CLOSE_WAIT,       */
108     &ip_ct_tcp_timeout_last_ack,       /*      TCP_CONNTRACK_LAST_ACK, */
109     &ip_ct_tcp_timeout_time_wait,      /*      TCP_CONNTRACK_TIME_WAIT,        */
110     &ip_ct_tcp_timeout_close,          /*      TCP_CONNTRACK_CLOSE,    */
111     NULL,                              /*      TCP_CONNTRACK_LISTEN */
112  };
113  
114 #define sNO TCP_CONNTRACK_NONE
115 #define sSS TCP_CONNTRACK_SYN_SENT
116 #define sSR TCP_CONNTRACK_SYN_RECV
117 #define sES TCP_CONNTRACK_ESTABLISHED
118 #define sFW TCP_CONNTRACK_FIN_WAIT
119 #define sCW TCP_CONNTRACK_CLOSE_WAIT
120 #define sLA TCP_CONNTRACK_LAST_ACK
121 #define sTW TCP_CONNTRACK_TIME_WAIT
122 #define sCL TCP_CONNTRACK_CLOSE
123 #define sLI TCP_CONNTRACK_LISTEN
124 #define sIV TCP_CONNTRACK_MAX
125 #define sIG TCP_CONNTRACK_IGNORE
126
127 /* What TCP flags are set from RST/SYN/FIN/ACK. */
128 enum tcp_bit_set {
129         TCP_SYN_SET,
130         TCP_SYNACK_SET,
131         TCP_FIN_SET,
132         TCP_ACK_SET,
133         TCP_RST_SET,
134         TCP_NONE_SET,
135 };
136   
137 /*
138  * The TCP state transition table needs a few words...
139  *
140  * We are the man in the middle. All the packets go through us
141  * but might get lost in transit to the destination.
142  * It is assumed that the destinations can't receive segments 
143  * we haven't seen.
144  *
145  * The checked segment is in window, but our windows are *not*
146  * equivalent with the ones of the sender/receiver. We always
147  * try to guess the state of the current sender.
148  *
149  * The meaning of the states are:
150  *
151  * NONE:        initial state
152  * SYN_SENT:    SYN-only packet seen 
153  * SYN_RECV:    SYN-ACK packet seen
154  * ESTABLISHED: ACK packet seen
155  * FIN_WAIT:    FIN packet seen
156  * CLOSE_WAIT:  ACK seen (after FIN) 
157  * LAST_ACK:    FIN seen (after FIN)
158  * TIME_WAIT:   last ACK seen
159  * CLOSE:       closed connection
160  *
161  * LISTEN state is not used.
162  *
163  * Packets marked as IGNORED (sIG):
164  *      if they may be either invalid or valid 
165  *      and the receiver may send back a connection 
166  *      closing RST or a SYN/ACK.
167  *
168  * Packets marked as INVALID (sIV):
169  *      if they are invalid
170  *      or we do not support the request (simultaneous open)
171  */
172 static const enum tcp_conntrack tcp_conntracks[2][6][TCP_CONNTRACK_MAX] = {
173         {
174 /* ORIGINAL */
175 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sLI   */
176 /*syn*/    { sSS, sSS, sIG, sIG, sIG, sIG, sIG, sSS, sSS, sIV },
177 /*
178  *      sNO -> sSS      Initialize a new connection
179  *      sSS -> sSS      Retransmitted SYN
180  *      sSR -> sIG      Late retransmitted SYN?
181  *      sES -> sIG      Error: SYNs in window outside the SYN_SENT state
182  *                      are errors. Receiver will reply with RST 
183  *                      and close the connection.
184  *                      Or we are not in sync and hold a dead connection.
185  *      sFW -> sIG
186  *      sCW -> sIG
187  *      sLA -> sIG
188  *      sTW -> sSS      Reopened connection (RFC 1122).
189  *      sCL -> sSS
190  */
191 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sLI   */
192 /*synack*/ { sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV },
193 /*
194  * A SYN/ACK from the client is always invalid:
195  *      - either it tries to set up a simultaneous open, which is 
196  *        not supported;
197  *      - or the firewall has just been inserted between the two hosts
198  *        during the session set-up. The SYN will be retransmitted 
199  *        by the true client (or it'll time out).
200  */
201 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sLI   */
202 /*fin*/    { sIV, sIV, sFW, sFW, sLA, sLA, sLA, sTW, sCL, sIV },
203 /*
204  *      sNO -> sIV      Too late and no reason to do anything...
205  *      sSS -> sIV      Client migth not send FIN in this state:
206  *                      we enforce waiting for a SYN/ACK reply first.
207  *      sSR -> sFW      Close started.
208  *      sES -> sFW      
209  *      sFW -> sLA      FIN seen in both directions, waiting for
210  *                      the last ACK. 
211  *                      Migth be a retransmitted FIN as well...
212  *      sCW -> sLA
213  *      sLA -> sLA      Retransmitted FIN. Remain in the same state.
214  *      sTW -> sTW
215  *      sCL -> sCL
216  */
217 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sLI   */
218 /*ack*/    { sES, sIV, sES, sES, sCW, sCW, sTW, sTW, sCL, sIV },
219 /*
220  *      sNO -> sES      Assumed.
221  *      sSS -> sIV      ACK is invalid: we haven't seen a SYN/ACK yet.
222  *      sSR -> sES      Established state is reached.
223  *      sES -> sES      :-)
224  *      sFW -> sCW      Normal close request answered by ACK.
225  *      sCW -> sCW
226  *      sLA -> sTW      Last ACK detected.
227  *      sTW -> sTW      Retransmitted last ACK. Remain in the same state.
228  *      sCL -> sCL
229  */
230 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sLI   */
231 /*rst*/    { sIV, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sIV },
232 /*none*/   { sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV }
233         },
234         {
235 /* REPLY */
236 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sLI   */
237 /*syn*/    { sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV },
238 /*
239  *      sNO -> sIV      Never reached.
240  *      sSS -> sIV      Simultaneous open, not supported
241  *      sSR -> sIV      Simultaneous open, not supported.
242  *      sES -> sIV      Server may not initiate a connection.
243  *      sFW -> sIV
244  *      sCW -> sIV
245  *      sLA -> sIV
246  *      sTW -> sIV      Reopened connection, but server may not do it.
247  *      sCL -> sIV
248  */
249 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sLI   */
250 /*synack*/ { sIV, sSR, sSR, sIG, sIG, sIG, sIG, sIG, sIG, sIV },
251 /*
252  *      sSS -> sSR      Standard open.
253  *      sSR -> sSR      Retransmitted SYN/ACK.
254  *      sES -> sIG      Late retransmitted SYN/ACK?
255  *      sFW -> sIG      Might be SYN/ACK answering ignored SYN
256  *      sCW -> sIG
257  *      sLA -> sIG
258  *      sTW -> sIG
259  *      sCL -> sIG
260  */
261 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sLI   */
262 /*fin*/    { sIV, sIV, sFW, sFW, sLA, sLA, sLA, sTW, sCL, sIV },
263 /*
264  *      sSS -> sIV      Server might not send FIN in this state.
265  *      sSR -> sFW      Close started.
266  *      sES -> sFW
267  *      sFW -> sLA      FIN seen in both directions.
268  *      sCW -> sLA
269  *      sLA -> sLA      Retransmitted FIN.
270  *      sTW -> sTW
271  *      sCL -> sCL
272  */
273 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sLI   */
274 /*ack*/    { sIV, sIG, sSR, sES, sCW, sCW, sTW, sTW, sCL, sIV },
275 /*
276  *      sSS -> sIG      Might be a half-open connection.
277  *      sSR -> sSR      Might answer late resent SYN.
278  *      sES -> sES      :-)
279  *      sFW -> sCW      Normal close request answered by ACK.
280  *      sCW -> sCW
281  *      sLA -> sTW      Last ACK detected.
282  *      sTW -> sTW      Retransmitted last ACK.
283  *      sCL -> sCL
284  */
285 /*           sNO, sSS, sSR, sES, sFW, sCW, sLA, sTW, sCL, sLI   */
286 /*rst*/    { sIV, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sCL, sIV },
287 /*none*/   { sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV, sIV }
288         }
289 };
290
291 static int tcp_pkt_to_tuple(const struct sk_buff *skb,
292                             unsigned int dataoff,
293                             struct ip_conntrack_tuple *tuple)
294 {
295         struct tcphdr _hdr, *hp;
296
297         /* Actually only need first 8 bytes. */
298         hp = skb_header_pointer(skb, dataoff, 8, &_hdr);
299         if (hp == NULL)
300                 return 0;
301
302         tuple->src.u.tcp.port = hp->source;
303         tuple->dst.u.tcp.port = hp->dest;
304
305         return 1;
306 }
307
308 static int tcp_invert_tuple(struct ip_conntrack_tuple *tuple,
309                             const struct ip_conntrack_tuple *orig)
310 {
311         tuple->src.u.tcp.port = orig->dst.u.tcp.port;
312         tuple->dst.u.tcp.port = orig->src.u.tcp.port;
313         return 1;
314 }
315
316 /* Print out the per-protocol part of the tuple. */
317 static int tcp_print_tuple(struct seq_file *s,
318                            const struct ip_conntrack_tuple *tuple)
319 {
320         return seq_printf(s, "sport=%hu dport=%hu ",
321                           ntohs(tuple->src.u.tcp.port),
322                           ntohs(tuple->dst.u.tcp.port));
323 }
324
325 /* Print out the private part of the conntrack. */
326 static int tcp_print_conntrack(struct seq_file *s,
327                                const struct ip_conntrack *conntrack)
328 {
329         enum tcp_conntrack state;
330
331         read_lock_bh(&tcp_lock);
332         state = conntrack->proto.tcp.state;
333         read_unlock_bh(&tcp_lock);
334
335         return seq_printf(s, "%s ", tcp_conntrack_names[state]);
336 }
337
338 #if defined(CONFIG_IP_NF_CONNTRACK_NETLINK) || \
339     defined(CONFIG_IP_NF_CONNTRACK_NETLINK_MODULE)
340 static int tcp_to_nfattr(struct sk_buff *skb, struct nfattr *nfa,
341                          const struct ip_conntrack *ct)
342 {
343         struct nfattr *nest_parms;
344         
345         read_lock_bh(&tcp_lock);
346         nest_parms = NFA_NEST(skb, CTA_PROTOINFO_TCP);
347         NFA_PUT(skb, CTA_PROTOINFO_TCP_STATE, sizeof(u_int8_t),
348                 &ct->proto.tcp.state);
349         read_unlock_bh(&tcp_lock);
350
351         NFA_NEST_END(skb, nest_parms);
352
353         return 0;
354
355 nfattr_failure:
356         read_unlock_bh(&tcp_lock);
357         return -1;
358 }
359
360 static const size_t cta_min_tcp[CTA_PROTOINFO_TCP_MAX] = {
361         [CTA_PROTOINFO_TCP_STATE-1]     = sizeof(u_int8_t),
362 };
363
364 static int nfattr_to_tcp(struct nfattr *cda[], struct ip_conntrack *ct)
365 {
366         struct nfattr *attr = cda[CTA_PROTOINFO_TCP-1];
367         struct nfattr *tb[CTA_PROTOINFO_TCP_MAX];
368
369         /* updates could not contain anything about the private
370          * protocol info, in that case skip the parsing */
371         if (!attr)
372                 return 0;
373
374         nfattr_parse_nested(tb, CTA_PROTOINFO_TCP_MAX, attr);
375
376         if (nfattr_bad_size(tb, CTA_PROTOINFO_TCP_MAX, cta_min_tcp))
377                 return -EINVAL;
378
379         if (!tb[CTA_PROTOINFO_TCP_STATE-1])
380                 return -EINVAL;
381
382         write_lock_bh(&tcp_lock);
383         ct->proto.tcp.state = 
384                 *(u_int8_t *)NFA_DATA(tb[CTA_PROTOINFO_TCP_STATE-1]);
385         write_unlock_bh(&tcp_lock);
386
387         return 0;
388 }
389 #endif
390
391 static unsigned int get_conntrack_index(const struct tcphdr *tcph)
392 {
393         if (tcph->rst) return TCP_RST_SET;
394         else if (tcph->syn) return (tcph->ack ? TCP_SYNACK_SET : TCP_SYN_SET);
395         else if (tcph->fin) return TCP_FIN_SET;
396         else if (tcph->ack) return TCP_ACK_SET;
397         else return TCP_NONE_SET;
398 }
399
400 /* TCP connection tracking based on 'Real Stateful TCP Packet Filtering
401    in IP Filter' by Guido van Rooij.
402    
403    http://www.nluug.nl/events/sane2000/papers.html
404    http://www.iae.nl/users/guido/papers/tcp_filtering.ps.gz
405    
406    The boundaries and the conditions are changed according to RFC793:
407    the packet must intersect the window (i.e. segments may be
408    after the right or before the left edge) and thus receivers may ACK
409    segments after the right edge of the window.
410
411         td_maxend = max(sack + max(win,1)) seen in reply packets
412         td_maxwin = max(max(win, 1)) + (sack - ack) seen in sent packets
413         td_maxwin += seq + len - sender.td_maxend
414                         if seq + len > sender.td_maxend
415         td_end    = max(seq + len) seen in sent packets
416    
417    I.   Upper bound for valid data:     seq <= sender.td_maxend
418    II.  Lower bound for valid data:     seq + len >= sender.td_end - receiver.td_maxwin
419    III. Upper bound for valid ack:      sack <= receiver.td_end
420    IV.  Lower bound for valid ack:      ack >= receiver.td_end - MAXACKWINDOW
421         
422    where sack is the highest right edge of sack block found in the packet.
423         
424    The upper bound limit for a valid ack is not ignored - 
425    we doesn't have to deal with fragments. 
426 */
427
428 static inline __u32 segment_seq_plus_len(__u32 seq,
429                                          size_t len,
430                                          struct iphdr *iph,
431                                          struct tcphdr *tcph)
432 {
433         return (seq + len - (iph->ihl + tcph->doff)*4
434                 + (tcph->syn ? 1 : 0) + (tcph->fin ? 1 : 0));
435 }
436   
437 /* Fixme: what about big packets? */
438 #define MAXACKWINCONST                  66000
439 #define MAXACKWINDOW(sender)                                            \
440         ((sender)->td_maxwin > MAXACKWINCONST ? (sender)->td_maxwin     \
441                                               : MAXACKWINCONST)
442   
443 /*
444  * Simplified tcp_parse_options routine from tcp_input.c
445  */
446 static void tcp_options(const struct sk_buff *skb,
447                         struct iphdr *iph,
448                         struct tcphdr *tcph, 
449                         struct ip_ct_tcp_state *state)
450 {
451         unsigned char buff[(15 * 4) - sizeof(struct tcphdr)];
452         unsigned char *ptr;
453         int length = (tcph->doff*4) - sizeof(struct tcphdr);
454         
455         if (!length)
456                 return;
457
458         ptr = skb_header_pointer(skb,
459                                  (iph->ihl * 4) + sizeof(struct tcphdr),
460                                  length, buff);
461         BUG_ON(ptr == NULL);
462
463         state->td_scale = 
464         state->flags = 0;
465         
466         while (length > 0) {
467                 int opcode=*ptr++;
468                 int opsize;
469                 
470                 switch (opcode) {
471                 case TCPOPT_EOL:
472                         return;
473                 case TCPOPT_NOP:        /* Ref: RFC 793 section 3.1 */
474                         length--;
475                         continue;
476                 default:
477                         opsize=*ptr++;
478                         if (opsize < 2) /* "silly options" */
479                                 return;
480                         if (opsize > length)
481                                 break;  /* don't parse partial options */
482
483                         if (opcode == TCPOPT_SACK_PERM 
484                             && opsize == TCPOLEN_SACK_PERM)
485                                 state->flags |= IP_CT_TCP_FLAG_SACK_PERM;
486                         else if (opcode == TCPOPT_WINDOW
487                                  && opsize == TCPOLEN_WINDOW) {
488                                 state->td_scale = *(u_int8_t *)ptr;
489                                 
490                                 if (state->td_scale > 14) {
491                                         /* See RFC1323 */
492                                         state->td_scale = 14;
493                                 }
494                                 state->flags |=
495                                         IP_CT_TCP_FLAG_WINDOW_SCALE;
496                         }
497                         ptr += opsize - 2;
498                         length -= opsize;
499                 }
500         }
501 }
502
503 static void tcp_sack(const struct sk_buff *skb,
504                      struct iphdr *iph,
505                      struct tcphdr *tcph,
506                      __u32 *sack)
507 {
508         unsigned char buff[(15 * 4) - sizeof(struct tcphdr)];
509         unsigned char *ptr;
510         int length = (tcph->doff*4) - sizeof(struct tcphdr);
511         __u32 tmp;
512
513         if (!length)
514                 return;
515
516         ptr = skb_header_pointer(skb,
517                                  (iph->ihl * 4) + sizeof(struct tcphdr),
518                                  length, buff);
519         BUG_ON(ptr == NULL);
520
521         /* Fast path for timestamp-only option */
522         if (length == TCPOLEN_TSTAMP_ALIGNED*4
523             && *(__u32 *)ptr ==
524                 __constant_ntohl((TCPOPT_NOP << 24) 
525                                  | (TCPOPT_NOP << 16)
526                                  | (TCPOPT_TIMESTAMP << 8)
527                                  | TCPOLEN_TIMESTAMP))
528                 return;
529                 
530         while (length > 0) {
531                 int opcode=*ptr++;
532                 int opsize, i;
533                 
534                 switch (opcode) {
535                 case TCPOPT_EOL:
536                         return;
537                 case TCPOPT_NOP:        /* Ref: RFC 793 section 3.1 */
538                         length--;
539                         continue;
540                 default:
541                         opsize=*ptr++;
542                         if (opsize < 2) /* "silly options" */
543                                 return;
544                         if (opsize > length)
545                                 break;  /* don't parse partial options */
546
547                         if (opcode == TCPOPT_SACK 
548                             && opsize >= (TCPOLEN_SACK_BASE 
549                                           + TCPOLEN_SACK_PERBLOCK)
550                             && !((opsize - TCPOLEN_SACK_BASE) 
551                                  % TCPOLEN_SACK_PERBLOCK)) {
552                                 for (i = 0;
553                                      i < (opsize - TCPOLEN_SACK_BASE);
554                                      i += TCPOLEN_SACK_PERBLOCK) {
555                                         tmp = ntohl(*((u_int32_t *)(ptr+i)+1));
556                                         
557                                         if (after(tmp, *sack))
558                                                 *sack = tmp;
559                                 }
560                                 return;
561                         }
562                         ptr += opsize - 2;
563                         length -= opsize;
564                 }
565         }
566 }
567
568 static int tcp_in_window(struct ip_ct_tcp *state, 
569                          enum ip_conntrack_dir dir,
570                          unsigned int index,
571                          const struct sk_buff *skb,
572                          struct iphdr *iph,
573                          struct tcphdr *tcph)
574 {
575         struct ip_ct_tcp_state *sender = &state->seen[dir];
576         struct ip_ct_tcp_state *receiver = &state->seen[!dir];
577         __u32 seq, ack, sack, end, win, swin;
578         int res;
579         
580         /*
581          * Get the required data from the packet.
582          */
583         seq = ntohl(tcph->seq);
584         ack = sack = ntohl(tcph->ack_seq);
585         win = ntohs(tcph->window);
586         end = segment_seq_plus_len(seq, skb->len, iph, tcph);
587         
588         if (receiver->flags & IP_CT_TCP_FLAG_SACK_PERM)
589                 tcp_sack(skb, iph, tcph, &sack);
590                 
591         DEBUGP("tcp_in_window: START\n");
592         DEBUGP("tcp_in_window: src=%u.%u.%u.%u:%hu dst=%u.%u.%u.%u:%hu "
593                "seq=%u ack=%u sack=%u win=%u end=%u\n",
594                 NIPQUAD(iph->saddr), ntohs(tcph->source), 
595                 NIPQUAD(iph->daddr), ntohs(tcph->dest),
596                 seq, ack, sack, win, end);
597         DEBUGP("tcp_in_window: sender end=%u maxend=%u maxwin=%u scale=%i "
598                "receiver end=%u maxend=%u maxwin=%u scale=%i\n",
599                 sender->td_end, sender->td_maxend, sender->td_maxwin,
600                 sender->td_scale, 
601                 receiver->td_end, receiver->td_maxend, receiver->td_maxwin, 
602                 receiver->td_scale);
603                 
604         if (sender->td_end == 0) {
605                 /*
606                  * Initialize sender data.
607                  */
608                 if (tcph->syn && tcph->ack) {
609                         /*
610                          * Outgoing SYN-ACK in reply to a SYN.
611                          */
612                         sender->td_end = 
613                         sender->td_maxend = end;
614                         sender->td_maxwin = (win == 0 ? 1 : win);
615
616                         tcp_options(skb, iph, tcph, sender);
617                         /* 
618                          * RFC 1323:
619                          * Both sides must send the Window Scale option
620                          * to enable window scaling in either direction.
621                          */
622                         if (!(sender->flags & IP_CT_TCP_FLAG_WINDOW_SCALE
623                               && receiver->flags & IP_CT_TCP_FLAG_WINDOW_SCALE))
624                                 sender->td_scale = 
625                                 receiver->td_scale = 0;
626                 } else {
627                         /*
628                          * We are in the middle of a connection,
629                          * its history is lost for us.
630                          * Let's try to use the data from the packet.
631                          */
632                         sender->td_end = end;
633                         sender->td_maxwin = (win == 0 ? 1 : win);
634                         sender->td_maxend = end + sender->td_maxwin;
635                 }
636         } else if (((state->state == TCP_CONNTRACK_SYN_SENT
637                      && dir == IP_CT_DIR_ORIGINAL)
638                     || (state->state == TCP_CONNTRACK_SYN_RECV
639                         && dir == IP_CT_DIR_REPLY))
640                     && after(end, sender->td_end)) {
641                 /*
642                  * RFC 793: "if a TCP is reinitialized ... then it need
643                  * not wait at all; it must only be sure to use sequence 
644                  * numbers larger than those recently used."
645                  */
646                 sender->td_end =
647                 sender->td_maxend = end;
648                 sender->td_maxwin = (win == 0 ? 1 : win);
649
650                 tcp_options(skb, iph, tcph, sender);
651         }
652         
653         if (!(tcph->ack)) {
654                 /*
655                  * If there is no ACK, just pretend it was set and OK.
656                  */
657                 ack = sack = receiver->td_end;
658         } else if (((tcp_flag_word(tcph) & (TCP_FLAG_ACK|TCP_FLAG_RST)) == 
659                     (TCP_FLAG_ACK|TCP_FLAG_RST)) 
660                    && (ack == 0)) {
661                 /*
662                  * Broken TCP stacks, that set ACK in RST packets as well
663                  * with zero ack value.
664                  */
665                 ack = sack = receiver->td_end;
666         }
667
668         if (seq == end
669             && (!tcph->rst 
670                 || (seq == 0 && state->state == TCP_CONNTRACK_SYN_SENT)))
671                 /*
672                  * Packets contains no data: we assume it is valid
673                  * and check the ack value only.
674                  * However RST segments are always validated by their
675                  * SEQ number, except when seq == 0 (reset sent answering
676                  * SYN.
677                  */
678                 seq = end = sender->td_end;
679                 
680         DEBUGP("tcp_in_window: src=%u.%u.%u.%u:%hu dst=%u.%u.%u.%u:%hu "
681                "seq=%u ack=%u sack =%u win=%u end=%u\n",
682                 NIPQUAD(iph->saddr), ntohs(tcph->source),
683                 NIPQUAD(iph->daddr), ntohs(tcph->dest),
684                 seq, ack, sack, win, end);
685         DEBUGP("tcp_in_window: sender end=%u maxend=%u maxwin=%u scale=%i "
686                "receiver end=%u maxend=%u maxwin=%u scale=%i\n",
687                 sender->td_end, sender->td_maxend, sender->td_maxwin,
688                 sender->td_scale, 
689                 receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
690                 receiver->td_scale);
691         
692         DEBUGP("tcp_in_window: I=%i II=%i III=%i IV=%i\n",
693                 before(seq, sender->td_maxend + 1),
694                 after(end, sender->td_end - receiver->td_maxwin - 1),
695                 before(sack, receiver->td_end + 1),
696                 after(ack, receiver->td_end - MAXACKWINDOW(sender)));
697         
698         if (sender->loose || receiver->loose ||
699             (before(seq, sender->td_maxend + 1) &&
700              after(end, sender->td_end - receiver->td_maxwin - 1) &&
701              before(sack, receiver->td_end + 1) &&
702              after(ack, receiver->td_end - MAXACKWINDOW(sender)))) {
703                 /*
704                  * Take into account window scaling (RFC 1323).
705                  */
706                 if (!tcph->syn)
707                         win <<= sender->td_scale;
708                 
709                 /*
710                  * Update sender data.
711                  */
712                 swin = win + (sack - ack);
713                 if (sender->td_maxwin < swin)
714                         sender->td_maxwin = swin;
715                 if (after(end, sender->td_end))
716                         sender->td_end = end;
717                 /*
718                  * Update receiver data.
719                  */
720                 if (after(end, sender->td_maxend))
721                         receiver->td_maxwin += end - sender->td_maxend;
722                 if (after(sack + win, receiver->td_maxend - 1)) {
723                         receiver->td_maxend = sack + win;
724                         if (win == 0)
725                                 receiver->td_maxend++;
726                 }
727
728                 /* 
729                  * Check retransmissions.
730                  */
731                 if (index == TCP_ACK_SET) {
732                         if (state->last_dir == dir
733                             && state->last_seq == seq
734                             && state->last_ack == ack
735                             && state->last_end == end)
736                                 state->retrans++;
737                         else {
738                                 state->last_dir = dir;
739                                 state->last_seq = seq;
740                                 state->last_ack = ack;
741                                 state->last_end = end;
742                                 state->retrans = 0;
743                         }
744                 }
745                 /*
746                  * Close the window of disabled window tracking :-)
747                  */
748                 if (sender->loose)
749                         sender->loose--;
750                 
751                 res = 1;
752         } else {
753                 if (LOG_INVALID(IPPROTO_TCP))
754                         nf_log_packet(PF_INET, 0, skb, NULL, NULL, NULL,
755                         "ip_ct_tcp: %s ",
756                         before(seq, sender->td_maxend + 1) ?
757                         after(end, sender->td_end - receiver->td_maxwin - 1) ?
758                         before(sack, receiver->td_end + 1) ?
759                         after(ack, receiver->td_end - MAXACKWINDOW(sender)) ? "BUG"
760                         : "ACK is under the lower bound (possible overly delayed ACK)"
761                         : "ACK is over the upper bound (ACKed data not seen yet)"
762                         : "SEQ is under the lower bound (already ACKed data retransmitted)"
763                         : "SEQ is over the upper bound (over the window of the receiver)");
764
765                 res = ip_ct_tcp_be_liberal;
766         }
767   
768         DEBUGP("tcp_in_window: res=%i sender end=%u maxend=%u maxwin=%u "
769                "receiver end=%u maxend=%u maxwin=%u\n",
770                 res, sender->td_end, sender->td_maxend, sender->td_maxwin, 
771                 receiver->td_end, receiver->td_maxend, receiver->td_maxwin);
772
773         return res;
774 }
775
776 #ifdef CONFIG_IP_NF_NAT_NEEDED
777 /* Update sender->td_end after NAT successfully mangled the packet */
778 void ip_conntrack_tcp_update(struct sk_buff *skb,
779                              struct ip_conntrack *conntrack, 
780                              enum ip_conntrack_dir dir)
781 {
782         struct iphdr *iph = skb->nh.iph;
783         struct tcphdr *tcph = (void *)skb->nh.iph + skb->nh.iph->ihl*4;
784         __u32 end;
785 #ifdef DEBUGP_VARS
786         struct ip_ct_tcp_state *sender = &conntrack->proto.tcp.seen[dir];
787         struct ip_ct_tcp_state *receiver = &conntrack->proto.tcp.seen[!dir];
788 #endif
789
790         end = segment_seq_plus_len(ntohl(tcph->seq), skb->len, iph, tcph);
791         
792         write_lock_bh(&tcp_lock);
793         /*
794          * We have to worry for the ack in the reply packet only...
795          */
796         if (after(end, conntrack->proto.tcp.seen[dir].td_end))
797                 conntrack->proto.tcp.seen[dir].td_end = end;
798         conntrack->proto.tcp.last_end = end;
799         write_unlock_bh(&tcp_lock);
800         DEBUGP("tcp_update: sender end=%u maxend=%u maxwin=%u scale=%i "
801                "receiver end=%u maxend=%u maxwin=%u scale=%i\n",
802                 sender->td_end, sender->td_maxend, sender->td_maxwin,
803                 sender->td_scale, 
804                 receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
805                 receiver->td_scale);
806 }
807  
808 #endif
809
810 #define TH_FIN  0x01
811 #define TH_SYN  0x02
812 #define TH_RST  0x04
813 #define TH_PUSH 0x08
814 #define TH_ACK  0x10
815 #define TH_URG  0x20
816 #define TH_ECE  0x40
817 #define TH_CWR  0x80
818
819 /* table of valid flag combinations - ECE and CWR are always valid */
820 static const u8 tcp_valid_flags[(TH_FIN|TH_SYN|TH_RST|TH_PUSH|TH_ACK|TH_URG) + 1] =
821 {
822         [TH_SYN]                        = 1,
823         [TH_SYN|TH_ACK]                 = 1,
824         [TH_SYN|TH_PUSH]                = 1,
825         [TH_SYN|TH_ACK|TH_PUSH]         = 1,
826         [TH_RST]                        = 1,
827         [TH_RST|TH_ACK]                 = 1,
828         [TH_RST|TH_ACK|TH_PUSH]         = 1,
829         [TH_FIN|TH_ACK]                 = 1,
830         [TH_ACK]                        = 1,
831         [TH_ACK|TH_PUSH]                = 1,
832         [TH_ACK|TH_URG]                 = 1,
833         [TH_ACK|TH_URG|TH_PUSH]         = 1,
834         [TH_FIN|TH_ACK|TH_PUSH]         = 1,
835         [TH_FIN|TH_ACK|TH_URG]          = 1,
836         [TH_FIN|TH_ACK|TH_URG|TH_PUSH]  = 1,
837 };
838
839 /* Protect conntrack agaist broken packets. Code taken from ipt_unclean.c.  */
840 static int tcp_error(struct sk_buff *skb,
841                      enum ip_conntrack_info *ctinfo,
842                      unsigned int hooknum)
843 {
844         struct iphdr *iph = skb->nh.iph;
845         struct tcphdr _tcph, *th;
846         unsigned int tcplen = skb->len - iph->ihl * 4;
847         u_int8_t tcpflags;
848
849         /* Smaller that minimal TCP header? */
850         th = skb_header_pointer(skb, iph->ihl * 4,
851                                 sizeof(_tcph), &_tcph);
852         if (th == NULL) {
853                 if (LOG_INVALID(IPPROTO_TCP))
854                         nf_log_packet(PF_INET, 0, skb, NULL, NULL, NULL,
855                                 "ip_ct_tcp: short packet ");
856                 return -NF_ACCEPT;
857         }
858   
859         /* Not whole TCP header or malformed packet */
860         if (th->doff*4 < sizeof(struct tcphdr) || tcplen < th->doff*4) {
861                 if (LOG_INVALID(IPPROTO_TCP))
862                         nf_log_packet(PF_INET, 0, skb, NULL, NULL, NULL,
863                                 "ip_ct_tcp: truncated/malformed packet ");
864                 return -NF_ACCEPT;
865         }
866   
867         /* Checksum invalid? Ignore.
868          * We skip checking packets on the outgoing path
869          * because the semantic of CHECKSUM_HW is different there 
870          * and moreover root might send raw packets.
871          */
872         /* FIXME: Source route IP option packets --RR */
873         if (hooknum == NF_IP_PRE_ROUTING
874             && skb->ip_summed != CHECKSUM_UNNECESSARY
875             && csum_tcpudp_magic(iph->saddr, iph->daddr, tcplen, IPPROTO_TCP,
876                                  skb->ip_summed == CHECKSUM_HW ? skb->csum
877                                  : skb_checksum(skb, iph->ihl*4, tcplen, 0))) {
878                 if (LOG_INVALID(IPPROTO_TCP))
879                         nf_log_packet(PF_INET, 0, skb, NULL, NULL, NULL,
880                                   "ip_ct_tcp: bad TCP checksum ");
881                 return -NF_ACCEPT;
882         }
883
884         /* Check TCP flags. */
885         tcpflags = (((u_int8_t *)th)[13] & ~(TH_ECE|TH_CWR));
886         if (!tcp_valid_flags[tcpflags]) {
887                 if (LOG_INVALID(IPPROTO_TCP))
888                         nf_log_packet(PF_INET, 0, skb, NULL, NULL, NULL,
889                                   "ip_ct_tcp: invalid TCP flag combination ");
890                 return -NF_ACCEPT;
891         }
892
893         return NF_ACCEPT;
894 }
895
896 /* Returns verdict for packet, or -1 for invalid. */
897 static int tcp_packet(struct ip_conntrack *conntrack,
898                       const struct sk_buff *skb,
899                       enum ip_conntrack_info ctinfo)
900 {
901         enum tcp_conntrack new_state, old_state;
902         enum ip_conntrack_dir dir;
903         struct iphdr *iph = skb->nh.iph;
904         struct tcphdr *th, _tcph;
905         unsigned long timeout;
906         unsigned int index;
907         
908         th = skb_header_pointer(skb, iph->ihl * 4,
909                                 sizeof(_tcph), &_tcph);
910         BUG_ON(th == NULL);
911         
912         write_lock_bh(&tcp_lock);
913         old_state = conntrack->proto.tcp.state;
914         dir = CTINFO2DIR(ctinfo);
915         index = get_conntrack_index(th);
916         new_state = tcp_conntracks[dir][index][old_state];
917
918         switch (new_state) {
919         case TCP_CONNTRACK_IGNORE:
920                 /* Ignored packets:
921                  * 
922                  * a) SYN in ORIGINAL
923                  * b) SYN/ACK in REPLY
924                  * c) ACK in reply direction after initial SYN in original.
925                  */
926                 if (index == TCP_SYNACK_SET
927                     && conntrack->proto.tcp.last_index == TCP_SYN_SET
928                     && conntrack->proto.tcp.last_dir != dir
929                     && ntohl(th->ack_seq) ==
930                              conntrack->proto.tcp.last_end) {
931                         /* This SYN/ACK acknowledges a SYN that we earlier 
932                          * ignored as invalid. This means that the client and
933                          * the server are both in sync, while the firewall is
934                          * not. We kill this session and block the SYN/ACK so
935                          * that the client cannot but retransmit its SYN and 
936                          * thus initiate a clean new session.
937                          */
938                         write_unlock_bh(&tcp_lock);
939                         if (LOG_INVALID(IPPROTO_TCP))
940                                 nf_log_packet(PF_INET, 0, skb, NULL, NULL,
941                                               NULL, "ip_ct_tcp: "
942                                               "killing out of sync session ");
943                         if (del_timer(&conntrack->timeout))
944                                 conntrack->timeout.function((unsigned long)
945                                                             conntrack);
946                         return -NF_DROP;
947                 }
948                 conntrack->proto.tcp.last_index = index;
949                 conntrack->proto.tcp.last_dir = dir;
950                 conntrack->proto.tcp.last_seq = ntohl(th->seq);
951                 conntrack->proto.tcp.last_end = 
952                     segment_seq_plus_len(ntohl(th->seq), skb->len, iph, th);
953                 
954                 write_unlock_bh(&tcp_lock);
955                 if (LOG_INVALID(IPPROTO_TCP))
956                         nf_log_packet(PF_INET, 0, skb, NULL, NULL, NULL,
957                                   "ip_ct_tcp: invalid packet ignored ");
958                 return NF_ACCEPT;
959         case TCP_CONNTRACK_MAX:
960                 /* Invalid packet */
961                 DEBUGP("ip_ct_tcp: Invalid dir=%i index=%u ostate=%u\n",
962                        dir, get_conntrack_index(th),
963                        old_state);
964                 write_unlock_bh(&tcp_lock);
965                 if (LOG_INVALID(IPPROTO_TCP))
966                         nf_log_packet(PF_INET, 0, skb, NULL, NULL, NULL,
967                                   "ip_ct_tcp: invalid state ");
968                 return -NF_ACCEPT;
969         case TCP_CONNTRACK_SYN_SENT:
970                 if (old_state < TCP_CONNTRACK_TIME_WAIT)
971                         break;
972                 if ((conntrack->proto.tcp.seen[dir].flags &
973                          IP_CT_TCP_FLAG_CLOSE_INIT)
974                     || after(ntohl(th->seq),
975                              conntrack->proto.tcp.seen[dir].td_end)) {  
976                         /* Attempt to reopen a closed connection.
977                         * Delete this connection and look up again. */
978                         write_unlock_bh(&tcp_lock);
979                         if (del_timer(&conntrack->timeout))
980                                 conntrack->timeout.function((unsigned long)
981                                                             conntrack);
982                         return -NF_REPEAT;
983                 } else {
984                         write_unlock_bh(&tcp_lock);
985                         if (LOG_INVALID(IPPROTO_TCP))
986                                 nf_log_packet(PF_INET, 0, skb, NULL, NULL,
987                                               NULL, "ip_ct_tcp: invalid SYN");
988                         return -NF_ACCEPT;
989                 }
990         case TCP_CONNTRACK_CLOSE:
991                 if (index == TCP_RST_SET
992                     && ((test_bit(IPS_SEEN_REPLY_BIT, &conntrack->status)
993                          && conntrack->proto.tcp.last_index == TCP_SYN_SET)
994                         || (!test_bit(IPS_ASSURED_BIT, &conntrack->status)
995                             && conntrack->proto.tcp.last_index == TCP_ACK_SET))
996                     && ntohl(th->ack_seq) == conntrack->proto.tcp.last_end) {
997                         /* RST sent to invalid SYN or ACK we had let through
998                          * at a) and c) above:
999                          *
1000                          * a) SYN was in window then
1001                          * c) we hold a half-open connection.
1002                          *
1003                          * Delete our connection entry.
1004                          * We skip window checking, because packet might ACK
1005                          * segments we ignored. */
1006                         goto in_window;
1007                 }
1008                 /* Just fall through */
1009         default:
1010                 /* Keep compilers happy. */
1011                 break;
1012         }
1013
1014         if (!tcp_in_window(&conntrack->proto.tcp, dir, index, 
1015                            skb, iph, th)) {
1016                 write_unlock_bh(&tcp_lock);
1017                 return -NF_ACCEPT;
1018         }
1019     in_window:
1020         /* From now on we have got in-window packets */ 
1021         conntrack->proto.tcp.last_index = index;
1022
1023         DEBUGP("tcp_conntracks: src=%u.%u.%u.%u:%hu dst=%u.%u.%u.%u:%hu "
1024                "syn=%i ack=%i fin=%i rst=%i old=%i new=%i\n",
1025                 NIPQUAD(iph->saddr), ntohs(th->source),
1026                 NIPQUAD(iph->daddr), ntohs(th->dest),
1027                 (th->syn ? 1 : 0), (th->ack ? 1 : 0),
1028                 (th->fin ? 1 : 0), (th->rst ? 1 : 0),
1029                 old_state, new_state);
1030
1031         conntrack->proto.tcp.state = new_state;
1032         if (old_state != new_state 
1033             && (new_state == TCP_CONNTRACK_FIN_WAIT
1034                 || new_state == TCP_CONNTRACK_CLOSE))
1035                 conntrack->proto.tcp.seen[dir].flags |= IP_CT_TCP_FLAG_CLOSE_INIT;
1036         timeout = conntrack->proto.tcp.retrans >= ip_ct_tcp_max_retrans
1037                   && *tcp_timeouts[new_state] > ip_ct_tcp_timeout_max_retrans
1038                   ? ip_ct_tcp_timeout_max_retrans : *tcp_timeouts[new_state];
1039         write_unlock_bh(&tcp_lock);
1040
1041         ip_conntrack_event_cache(IPCT_PROTOINFO_VOLATILE, skb);
1042         if (new_state != old_state)
1043                 ip_conntrack_event_cache(IPCT_PROTOINFO, skb);
1044
1045         if (!test_bit(IPS_SEEN_REPLY_BIT, &conntrack->status)) {
1046                 /* If only reply is a RST, we can consider ourselves not to
1047                    have an established connection: this is a fairly common
1048                    problem case, so we can delete the conntrack
1049                    immediately.  --RR */
1050                 if (th->rst) {
1051                         if (del_timer(&conntrack->timeout))
1052                                 conntrack->timeout.function((unsigned long)
1053                                                             conntrack);
1054                         return NF_ACCEPT;
1055                 }
1056         } else if (!test_bit(IPS_ASSURED_BIT, &conntrack->status)
1057                    && (old_state == TCP_CONNTRACK_SYN_RECV
1058                        || old_state == TCP_CONNTRACK_ESTABLISHED)
1059                    && new_state == TCP_CONNTRACK_ESTABLISHED) {
1060                 /* Set ASSURED if we see see valid ack in ESTABLISHED 
1061                    after SYN_RECV or a valid answer for a picked up 
1062                    connection. */
1063                 set_bit(IPS_ASSURED_BIT, &conntrack->status);
1064                 ip_conntrack_event_cache(IPCT_STATUS, skb);
1065         }
1066         ip_ct_refresh_acct(conntrack, ctinfo, skb, timeout);
1067
1068         return NF_ACCEPT;
1069 }
1070  
1071 /* Called when a new connection for this protocol found. */
1072 static int tcp_new(struct ip_conntrack *conntrack,
1073                    const struct sk_buff *skb)
1074 {
1075         enum tcp_conntrack new_state;
1076         struct iphdr *iph = skb->nh.iph;
1077         struct tcphdr *th, _tcph;
1078 #ifdef DEBUGP_VARS
1079         struct ip_ct_tcp_state *sender = &conntrack->proto.tcp.seen[0];
1080         struct ip_ct_tcp_state *receiver = &conntrack->proto.tcp.seen[1];
1081 #endif
1082
1083         th = skb_header_pointer(skb, iph->ihl * 4,
1084                                 sizeof(_tcph), &_tcph);
1085         BUG_ON(th == NULL);
1086         
1087         /* Don't need lock here: this conntrack not in circulation yet */
1088         new_state
1089                 = tcp_conntracks[0][get_conntrack_index(th)]
1090                 [TCP_CONNTRACK_NONE];
1091
1092         /* Invalid: delete conntrack */
1093         if (new_state >= TCP_CONNTRACK_MAX) {
1094                 DEBUGP("ip_ct_tcp: invalid new deleting.\n");
1095                 return 0;
1096         }
1097
1098         if (new_state == TCP_CONNTRACK_SYN_SENT) {
1099                 /* SYN packet */
1100                 conntrack->proto.tcp.seen[0].td_end =
1101                         segment_seq_plus_len(ntohl(th->seq), skb->len,
1102                                              iph, th);
1103                 conntrack->proto.tcp.seen[0].td_maxwin = ntohs(th->window);
1104                 if (conntrack->proto.tcp.seen[0].td_maxwin == 0)
1105                         conntrack->proto.tcp.seen[0].td_maxwin = 1;
1106                 conntrack->proto.tcp.seen[0].td_maxend =
1107                         conntrack->proto.tcp.seen[0].td_end;
1108
1109                 tcp_options(skb, iph, th, &conntrack->proto.tcp.seen[0]);
1110                 conntrack->proto.tcp.seen[1].flags = 0;
1111                 conntrack->proto.tcp.seen[0].loose = 
1112                 conntrack->proto.tcp.seen[1].loose = 0;
1113         } else if (ip_ct_tcp_loose == 0) {
1114                 /* Don't try to pick up connections. */
1115                 return 0;
1116         } else {
1117                 /*
1118                  * We are in the middle of a connection,
1119                  * its history is lost for us.
1120                  * Let's try to use the data from the packet.
1121                  */
1122                 conntrack->proto.tcp.seen[0].td_end =
1123                         segment_seq_plus_len(ntohl(th->seq), skb->len,
1124                                              iph, th);
1125                 conntrack->proto.tcp.seen[0].td_maxwin = ntohs(th->window);
1126                 if (conntrack->proto.tcp.seen[0].td_maxwin == 0)
1127                         conntrack->proto.tcp.seen[0].td_maxwin = 1;
1128                 conntrack->proto.tcp.seen[0].td_maxend =
1129                         conntrack->proto.tcp.seen[0].td_end + 
1130                         conntrack->proto.tcp.seen[0].td_maxwin;
1131                 conntrack->proto.tcp.seen[0].td_scale = 0;
1132
1133                 /* We assume SACK. Should we assume window scaling too? */
1134                 conntrack->proto.tcp.seen[0].flags =
1135                 conntrack->proto.tcp.seen[1].flags = IP_CT_TCP_FLAG_SACK_PERM;
1136                 conntrack->proto.tcp.seen[0].loose = 
1137                 conntrack->proto.tcp.seen[1].loose = ip_ct_tcp_loose;
1138         }
1139     
1140         conntrack->proto.tcp.seen[1].td_end = 0;
1141         conntrack->proto.tcp.seen[1].td_maxend = 0;
1142         conntrack->proto.tcp.seen[1].td_maxwin = 1;
1143         conntrack->proto.tcp.seen[1].td_scale = 0;      
1144
1145         /* tcp_packet will set them */
1146         conntrack->proto.tcp.state = TCP_CONNTRACK_NONE;
1147         conntrack->proto.tcp.last_index = TCP_NONE_SET;
1148          
1149         DEBUGP("tcp_new: sender end=%u maxend=%u maxwin=%u scale=%i "
1150                "receiver end=%u maxend=%u maxwin=%u scale=%i\n",
1151                 sender->td_end, sender->td_maxend, sender->td_maxwin,
1152                 sender->td_scale, 
1153                 receiver->td_end, receiver->td_maxend, receiver->td_maxwin,
1154                 receiver->td_scale);
1155         return 1;
1156 }
1157   
1158 struct ip_conntrack_protocol ip_conntrack_protocol_tcp =
1159 {
1160         .proto                  = IPPROTO_TCP,
1161         .name                   = "tcp",
1162         .pkt_to_tuple           = tcp_pkt_to_tuple,
1163         .invert_tuple           = tcp_invert_tuple,
1164         .print_tuple            = tcp_print_tuple,
1165         .print_conntrack        = tcp_print_conntrack,
1166         .packet                 = tcp_packet,
1167         .new                    = tcp_new,
1168         .error                  = tcp_error,
1169 #if defined(CONFIG_IP_NF_CONNTRACK_NETLINK) || \
1170     defined(CONFIG_IP_NF_CONNTRACK_NETLINK_MODULE)
1171         .to_nfattr              = tcp_to_nfattr,
1172         .from_nfattr            = nfattr_to_tcp,
1173         .tuple_to_nfattr        = ip_ct_port_tuple_to_nfattr,
1174         .nfattr_to_tuple        = ip_ct_port_nfattr_to_tuple,
1175 #endif
1176 };