root/net/ipv4/tcp.c

/* [previous][next][first][last][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. tcp_find_established
  2. tcp_dequeue_established
  3. tcp_close_pending
  4. tcp_time_wait
  5. tcp_err
  6. tcp_readable
  7. tcp_listen_select
  8. tcp_select
  9. tcp_ioctl
  10. tcp_send_check
  11. tcp_build_header
  12. tcp_sendmsg
  13. tcp_read_wakeup
  14. cleanup_rbuf
  15. tcp_recv_urg
  16. tcp_recvmsg
  17. tcp_close_state
  18. tcp_shutdown
  19. tcp_close
  20. tcp_accept
  21. tcp_connect
  22. tcp_setsockopt
  23. tcp_getsockopt

   1 /*
   2  * INET         An implementation of the TCP/IP protocol suite for the LINUX
   3  *              operating system.  INET is implemented using the  BSD Socket
   4  *              interface as the means of communication with the user level.
   5  *
   6  *              Implementation of the Transmission Control Protocol(TCP).
   7  *
   8  * Version:     @(#)tcp.c       1.0.16  05/25/93
   9  *
  10  * Authors:     Ross Biro, <bir7@leland.Stanford.Edu>
  11  *              Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  12  *              Mark Evans, <evansmp@uhura.aston.ac.uk>
  13  *              Corey Minyard <wf-rch!minyard@relay.EU.net>
  14  *              Florian La Roche, <flla@stud.uni-sb.de>
  15  *              Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
  16  *              Linus Torvalds, <torvalds@cs.helsinki.fi>
  17  *              Alan Cox, <gw4pts@gw4pts.ampr.org>
  18  *              Matthew Dillon, <dillon@apollo.west.oic.com>
  19  *              Arnt Gulbrandsen, <agulbra@nvg.unit.no>
  20  *              Jorge Cwik, <jorge@laser.satlink.net>
  21  *
  22  * Fixes:       
  23  *              Alan Cox        :       Numerous verify_area() calls
  24  *              Alan Cox        :       Set the ACK bit on a reset
  25  *              Alan Cox        :       Stopped it crashing if it closed while
  26  *                                      sk->inuse=1 and was trying to connect 
  27  *                                      (tcp_err()).
  28  *              Alan Cox        :       All icmp error handling was broken
  29  *                                      pointers passed where wrong and the
  30  *                                      socket was looked up backwards. Nobody
  31  *                                      tested any icmp error code obviously.
  32  *              Alan Cox        :       tcp_err() now handled properly. It 
  33  *                                      wakes people on errors. select 
  34  *                                      behaves and the icmp error race
  35  *                                      has gone by moving it into sock.c
  36  *              Alan Cox        :       tcp_send_reset() fixed to work for 
  37  *                                      everything not just packets for 
  38  *                                      unknown sockets.
  39  *              Alan Cox        :       tcp option processing.
  40  *              Alan Cox        :       Reset tweaked (still not 100%) [Had 
  41  *                                      syn rule wrong]
  42  *              Herp Rosmanith  :       More reset fixes
  43  *              Alan Cox        :       No longer acks invalid rst frames. 
  44  *                                      Acking any kind of RST is right out.
  45  *              Alan Cox        :       Sets an ignore me flag on an rst 
  46  *                                      receive otherwise odd bits of prattle 
  47  *                                      escape still
  48  *              Alan Cox        :       Fixed another acking RST frame bug. 
  49  *                                      Should stop LAN workplace lockups.
  50  *              Alan Cox        :       Some tidyups using the new skb list 
  51  *                                      facilities
  52  *              Alan Cox        :       sk->keepopen now seems to work
  53  *              Alan Cox        :       Pulls options out correctly on accepts
  54  *              Alan Cox        :       Fixed assorted sk->rqueue->next errors
  55  *              Alan Cox        :       PSH doesn't end a TCP read. Switched a
  56  *                                      bit to skb ops.
  57  *              Alan Cox        :       Tidied tcp_data to avoid a potential 
  58  *                                      nasty.
  59  *              Alan Cox        :       Added some better commenting, as the 
  60  *                                      tcp is hard to follow
  61  *              Alan Cox        :       Removed incorrect check for 20 * psh
  62  *      Michael O'Reilly        :       ack < copied bug fix.
  63  *      Johannes Stille         :       Misc tcp fixes (not all in yet).
  64  *              Alan Cox        :       FIN with no memory -> CRASH
  65  *              Alan Cox        :       Added socket option proto entries. 
  66  *                                      Also added awareness of them to accept.
  67  *              Alan Cox        :       Added TCP options (SOL_TCP)
  68  *              Alan Cox        :       Switched wakeup calls to callbacks, 
  69  *                                      so the kernel can layer network 
  70  *                                      sockets.
  71  *              Alan Cox        :       Use ip_tos/ip_ttl settings.
  72  *              Alan Cox        :       Handle FIN (more) properly (we hope).
  73  *              Alan Cox        :       RST frames sent on unsynchronised 
  74  *                                      state ack error.
  75  *              Alan Cox        :       Put in missing check for SYN bit.
  76  *              Alan Cox        :       Added tcp_select_window() aka NET2E 
  77  *                                      window non shrink trick.
  78  *              Alan Cox        :       Added a couple of small NET2E timer 
  79  *                                      fixes
  80  *              Charles Hedrick :       TCP fixes
  81  *              Toomas Tamm     :       TCP window fixes
  82  *              Alan Cox        :       Small URG fix to rlogin ^C ack fight
  83  *              Charles Hedrick :       Rewrote most of it to actually work
  84  *              Linus           :       Rewrote tcp_read() and URG handling
  85  *                                      completely
  86  *              Gerhard Koerting:       Fixed some missing timer handling
  87  *              Matthew Dillon  :       Reworked TCP machine states as per RFC
  88  *              Gerhard Koerting:       PC/TCP workarounds
  89  *              Adam Caldwell   :       Assorted timer/timing errors
  90  *              Matthew Dillon  :       Fixed another RST bug
  91  *              Alan Cox        :       Move to kernel side addressing changes.
  92  *              Alan Cox        :       Beginning work on TCP fastpathing 
  93  *                                      (not yet usable)
  94  *              Arnt Gulbrandsen:       Turbocharged tcp_check() routine.
  95  *              Alan Cox        :       TCP fast path debugging
  96  *              Alan Cox        :       Window clamping
  97  *              Michael Riepe   :       Bug in tcp_check()
  98  *              Matt Dillon     :       More TCP improvements and RST bug fixes
  99  *              Matt Dillon     :       Yet more small nasties remove from the
 100  *                                      TCP code (Be very nice to this man if 
 101  *                                      tcp finally works 100%) 8)
 102  *              Alan Cox        :       BSD accept semantics. 
 103  *              Alan Cox        :       Reset on closedown bug.
 104  *      Peter De Schrijver      :       ENOTCONN check missing in tcp_sendto().
 105  *              Michael Pall    :       Handle select() after URG properly in 
 106  *                                      all cases.
 107  *              Michael Pall    :       Undo the last fix in tcp_read_urg() 
 108  *                                      (multi URG PUSH broke rlogin).
 109  *              Michael Pall    :       Fix the multi URG PUSH problem in 
 110  *                                      tcp_readable(), select() after URG 
 111  *                                      works now.
 112  *              Michael Pall    :       recv(...,MSG_OOB) never blocks in the 
 113  *                                      BSD api.
 114  *              Alan Cox        :       Changed the semantics of sk->socket to 
 115  *                                      fix a race and a signal problem with
 116  *                                      accept() and async I/O.
 117  *              Alan Cox        :       Relaxed the rules on tcp_sendto().
 118  *              Yury Shevchuk   :       Really fixed accept() blocking problem.
 119  *              Craig I. Hagan  :       Allow for BSD compatible TIME_WAIT for
 120  *                                      clients/servers which listen in on
 121  *                                      fixed ports.
 122  *              Alan Cox        :       Cleaned the above up and shrank it to
 123  *                                      a sensible code size.
 124  *              Alan Cox        :       Self connect lockup fix.
 125  *              Alan Cox        :       No connect to multicast.
 126  *              Ross Biro       :       Close unaccepted children on master
 127  *                                      socket close.
 128  *              Alan Cox        :       Reset tracing code.
 129  *              Alan Cox        :       Spurious resets on shutdown.
 130  *              Alan Cox        :       Giant 15 minute/60 second timer error
 131  *              Alan Cox        :       Small whoops in selecting before an 
 132  *                                      accept.
 133  *              Alan Cox        :       Kept the state trace facility since 
 134  *                                      it's handy for debugging.
 135  *              Alan Cox        :       More reset handler fixes.
 136  *              Alan Cox        :       Started rewriting the code based on 
 137  *                                      the RFC's for other useful protocol 
 138  *                                      references see: Comer, KA9Q NOS, and 
 139  *                                      for a reference on the difference 
 140  *                                      between specifications and how BSD
 141  *                                      works see the 4.4lite source.
 142  *              A.N.Kuznetsov   :       Don't time wait on completion of tidy 
 143  *                                      close.
 144  *              Linus Torvalds  :       Fin/Shutdown & copied_seq changes.
 145  *              Linus Torvalds  :       Fixed BSD port reuse to work first syn
 146  *              Alan Cox        :       Reimplemented timers as per the RFC 
 147  *                                      and using multiple timers for sanity. 
 148  *              Alan Cox        :       Small bug fixes, and a lot of new
 149  *                                      comments.
 150  *              Alan Cox        :       Fixed dual reader crash by locking
 151  *                                      the buffers (much like datagram.c)
 152  *              Alan Cox        :       Fixed stuck sockets in probe. A probe
 153  *                                      now gets fed up of retrying without
 154  *                                      (even a no space) answer.
 155  *              Alan Cox        :       Extracted closing code better
 156  *              Alan Cox        :       Fixed the closing state machine to
 157  *                                      resemble the RFC.
 158  *              Alan Cox        :       More 'per spec' fixes.
 159  *              Jorge Cwik      :       Even faster checksumming.
 160  *              Alan Cox        :       tcp_data() doesn't ack illegal PSH
 161  *                                      only frames. At least one pc tcp stack
 162  *                                      generates them.
 163  *              Alan Cox        :       Cache last socket.
 164  *              Alan Cox        :       Per route irtt.
 165  *              Matt Day        :       Select() match BSD precisely on error
 166  *              Alan Cox        :       New buffers
 167  *              Marc Tamsky     :       Various sk->prot->retransmits and 
 168  *                                      sk->retransmits misupdating fixed.
 169  *                                      Fixed tcp_write_timeout: stuck close,
 170  *                                      and TCP syn retries gets used now.
 171  *              Mark Yarvis     :       In tcp_read_wakeup(), don't send an
 172  *                                      ack if stat is TCP_CLOSED.
 173  *              Alan Cox        :       Look up device on a retransmit - routes may
 174  *                                      change. Doesn't yet cope with MSS shrink right
 175  *                                      but its a start!
 176  *              Marc Tamsky     :       Closing in closing fixes.
 177  *              Mike Shaver     :       RFC1122 verifications.
 178  *              Alan Cox        :       rcv_saddr errors.
 179  *              Alan Cox        :       Block double connect().
 180  *              Alan Cox        :       Small hooks for enSKIP.
 181  *              Alexey Kuznetsov:       Path MTU discovery.
 182  *              Alan Cox        :       Support soft errors.
 183  *              Alan Cox        :       Fix MTU discovery pathalogical case
 184  *                                      when the remote claims no mtu!
 185  *              Marc Tamsky     :       TCP_CLOSE fix.
 186  *              Colin (G3TNE)   :       Send a reset on syn ack replies in 
 187  *                                      window but wrong (fixes NT lpd problems)
 188  *              Pedro Roque     :       Better TCP window handling, delayed ack.
 189  *              Joerg Reuter    :       No modification of locked buffers in 
 190  *                                      tcp_do_retransmit()
 191  *
 192  * To Fix:
 193  *              Fast path the code. Two things here - fix the window calculation
 194  *              so it doesn't iterate over the queue, also spot packets with no funny
 195  *              options arriving in order and process directly.
 196  *
 197  *              Rewrite output state machine to use a single queue.
 198  *              Speed up input assembly algorithm.
 199  *              RFC1323 - PAWS and window scaling. PAWS is required for IPv6 so we
 200  *              could do with it working on IPv4
 201  *              User settable/learned rtt/max window/mtu
 202  *
 203  *              Change the fundamental structure to a single send queue maintained
 204  *              by TCP (removing the bogus ip stuff [thus fixing mtu drops on
 205  *              active routes too]). Cut the queue off in tcp_retransmit/
 206  *              tcp_transmit.
 207  *              Change the receive queue to assemble as it goes. This lets us
 208  *              dispose of most of tcp_sequence, half of tcp_ack and chunks of
 209  *              tcp_data/tcp_read as well as the window shrink crud.
 210  *              Separate out duplicated code - tcp_alloc_skb, tcp_build_ack
 211  *              tcp_queue_skb seem obvious routines to extract.
 212  *      
 213  *              This program is free software; you can redistribute it and/or
 214  *              modify it under the terms of the GNU General Public License
 215  *              as published by the Free Software Foundation; either version
 216  *              2 of the License, or(at your option) any later version.
 217  *
 218  * Description of States:
 219  *
 220  *      TCP_SYN_SENT            sent a connection request, waiting for ack
 221  *
 222  *      TCP_SYN_RECV            received a connection request, sent ack,
 223  *                              waiting for final ack in three-way handshake.
 224  *
 225  *      TCP_ESTABLISHED         connection established
 226  *
 227  *      TCP_FIN_WAIT1           our side has shutdown, waiting to complete
 228  *                              transmission of remaining buffered data
 229  *
 230  *      TCP_FIN_WAIT2           all buffered data sent, waiting for remote
 231  *                              to shutdown
 232  *
 233  *      TCP_CLOSING             both sides have shutdown but we still have
 234  *                              data we have to finish sending
 235  *
 236  *      TCP_TIME_WAIT           timeout to catch resent junk before entering
 237  *                              closed, can only be entered from FIN_WAIT2
 238  *                              or CLOSING.  Required because the other end
 239  *                              may not have gotten our last ACK causing it
 240  *                              to retransmit the data packet (which we ignore)
 241  *
 242  *      TCP_CLOSE_WAIT          remote side has shutdown and is waiting for
 243  *                              us to finish writing our data and to shutdown
 244  *                              (we have to close() to move on to LAST_ACK)
 245  *
 246  *      TCP_LAST_ACK            out side has shutdown after remote has
 247  *                              shutdown.  There may still be data in our
 248  *                              buffer that we have to finish sending
 249  *              
 250  *      TCP_CLOSE               socket is finished
 251  */
 252 
 253 /*
 254  * RFC1122 status:
 255  * NOTE: I'm not going to be doing comments in the code for this one except
 256  * for violations and the like.  tcp.c is just too big... If I say something
 257  * "does?" or "doesn't?", it means I'm not sure, and will have to hash it out
 258  * with Alan. -- MS 950903
 259  * 
 260  * Use of PSH (4.2.2.2)
 261  *   MAY aggregate data sent without the PSH flag. (does)
 262  *   MAY queue data received without the PSH flag. (does)
 263  *   SHOULD collapse successive PSH flags when it packetizes data. (doesn't)
 264  *   MAY implement PSH on send calls. (doesn't, thus:)
 265  *     MUST NOT buffer data indefinitely (doesn't [1 second])
 266  *     MUST set PSH on last segment (does)
 267  *   MAY pass received PSH to application layer (doesn't)
 268  *   SHOULD send maximum-sized segment whenever possible. (almost always does)
 269  * 
 270  * Window Size (4.2.2.3, 4.2.2.16)
 271  *   MUST treat window size as an unsigned number (does)
 272  *   SHOULD treat window size as a 32-bit number (does not)
 273  *   MUST NOT shrink window once it is offered (does not normally)
 274  *   
 275  * Urgent Pointer (4.2.2.4)
 276  * **MUST point urgent pointer to last byte of urgent data (not right
 277  *     after). (doesn't, to be like BSD)
 278  *   MUST inform application layer asynchronously of incoming urgent
 279  *     data. (does)
 280  *   MUST provide application with means of determining the amount of
 281  *     urgent data pending. (does)
 282  * **MUST support urgent data sequence of arbitrary length. (doesn't, but
 283  *   it's sort of tricky to fix, as urg_ptr is a 16-bit quantity)
 284  *      [Follows BSD 1 byte of urgent data]
 285  * 
 286  * TCP Options (4.2.2.5)
 287  *   MUST be able to receive TCP options in any segment. (does)
 288  *   MUST ignore unsupported options (does)
 289  *   
 290  * Maximum Segment Size Option (4.2.2.6)
 291  *   MUST implement both sending and receiving MSS. (does)
 292  *   SHOULD send an MSS with every SYN where receive MSS != 536 (MAY send
 293  *     it always). (does, even when MSS == 536, which is legal)
 294  *   MUST assume MSS == 536 if no MSS received at connection setup (does)
 295  *   MUST calculate "effective send MSS" correctly:
 296  *     min(physical_MTU, remote_MSS+20) - sizeof(tcphdr) - sizeof(ipopts)
 297  *     (does - but allows operator override)
 298  *  
 299  * TCP Checksum (4.2.2.7)
 300  *   MUST generate and check TCP checksum. (does)
 301  * 
 302  * Initial Sequence Number Selection (4.2.2.8)
 303  *   MUST use the RFC 793 clock selection mechanism.  (doesn't, but it's
 304  *     OK: RFC 793 specifies a 250KHz clock, while we use 1MHz, which is
 305  *     necessary for 10Mbps networks - and harder than BSD to spoof!)
 306  * 
 307  * Simultaneous Open Attempts (4.2.2.10)
 308  *   MUST support simultaneous open attempts (does)
 309  * 
 310  * Recovery from Old Duplicate SYN (4.2.2.11)
 311  *   MUST keep track of active vs. passive open (does)
 312  * 
 313  * RST segment (4.2.2.12)
 314  *   SHOULD allow an RST segment to contain data (does, but doesn't do
 315  *     anything with it, which is standard)
 316  * 
 317  * Closing a Connection (4.2.2.13)
 318  *   MUST inform application of whether connectin was closed by RST or
 319  *     normal close. (does)
 320  *   MAY allow "half-duplex" close (treat connection as closed for the
 321  *     local app, even before handshake is done). (does)
 322  *   MUST linger in TIME_WAIT for 2 * MSL (does)
 323  * 
 324  * Retransmission Timeout (4.2.2.15)
 325  *   MUST implement Jacobson's slow start and congestion avoidance
 326  *     stuff. (does) 
 327  * 
 328  * Probing Zero Windows (4.2.2.17)
 329  *   MUST support probing of zero windows. (does)
 330  *   MAY keep offered window closed indefinitely. (does)
 331  *   MUST allow remote window to stay closed indefinitely. (does)
 332  * 
 333  * Passive Open Calls (4.2.2.18)
 334  *   MUST NOT let new passive open affect other connections. (doesn't)
 335  *   MUST support passive opens (LISTENs) concurrently. (does)
 336  *   
 337  * Time to Live (4.2.2.19)
 338  *   MUST make TCP TTL configurable. (does - IP_TTL option)
 339  * 
 340  * Event Processing (4.2.2.20)
 341  *   SHOULD queue out-of-order segments. (does)
 342  *   MUST aggregate ACK segments whenever possible. (does but badly)
 343  *   
 344  * Retransmission Timeout Calculation (4.2.3.1)
 345  *   MUST implement Karn's algorithm and Jacobson's algorithm for RTO
 346  *     calculation. (does, or at least explains them in the comments 8*b)
 347  *  SHOULD initialize RTO to 0 and RTT to 3. (does)
 348  * 
 349  * When to Send an ACK Segment (4.2.3.2)
 350  *   SHOULD implement delayed ACK. (does)
 351  *   MUST keep ACK delay < 0.5 sec. (does)
 352  * 
 353  * When to Send a Window Update (4.2.3.3)
 354  *   MUST implement receiver-side SWS. (does)
 355  *   
 356  * When to Send Data (4.2.3.4)
 357  *   MUST implement sender-side SWS. (does)
 358  *   SHOULD implement Nagle algorithm. (does)
 359  * 
 360  * TCP Connection Failures (4.2.3.5)
 361  *  MUST handle excessive retransmissions "properly" (see the RFC). (does)
 362  *   SHOULD inform application layer of soft errors. (does)
 363  *   
 364  * TCP Keep-Alives (4.2.3.6)
 365  *   MAY provide keep-alives. (does)
 366  *   MUST make keep-alives configurable on a per-connection basis. (does)
 367  *   MUST default to no keep-alives. (does)
 368  * **MUST make keep-alive interval configurable. (doesn't)
 369  * **MUST make default keep-alive interval > 2 hours. (doesn't)
 370  *   MUST NOT interpret failure to ACK keep-alive packet as dead
 371  *     connection. (doesn't)
 372  *   SHOULD send keep-alive with no data. (does)
 373  * 
 374  * TCP Multihoming (4.2.3.7)
 375  *   MUST get source address from IP layer before sending first
 376  *     SYN. (does)
 377  *   MUST use same local address for all segments of a connection. (does)
 378  * 
 379  * IP Options (4.2.3.8)
 380  *   MUST ignore unsupported IP options. (does)
 381  *   MAY support Time Stamp and Record Route. (does)
 382  *   MUST allow application to specify a source route. (does)
 383  *   MUST allow receieved Source Route option to set route for all future
 384  *     segments on this connection. (does not (security issues))
 385  * 
 386  * ICMP messages (4.2.3.9)
 387  *   MUST act on ICMP errors. (does)
 388  *   MUST slow transmission upon receipt of a Source Quench. (does)
 389  *   MUST NOT abort connection upon receipt of soft Destination
 390  *     Unreachables (0, 1, 5), Time Exceededs and Parameter
 391  *     Problems. (doesn't)
 392  *   SHOULD report soft Destination Unreachables etc. to the
 393  *     application. (does)
 394  *   SHOULD abort connection upon receipt of hard Destination Unreachable
 395  *     messages (2, 3, 4). (does)
 396  * 
 397  * Remote Address Validation (4.2.3.10)
 398  *   MUST reject as an error OPEN for invalid remote IP address. (does)
 399  *   MUST ignore SYN with invalid source address. (does)
 400  *   MUST silently discard incoming SYN for broadcast/multicast
 401  *     address. (does) 
 402  * 
 403  * Asynchronous Reports (4.2.4.1)
 404  * MUST provide mechanism for reporting soft errors to application
 405  *     layer. (does)
 406  * 
 407  * Type of Service (4.2.4.2)
 408  *   MUST allow application layer to set Type of Service. (does IP_TOS)
 409  * 
 410  * (Whew. -- MS 950903)
 411  **/
 412 
 413 #include <linux/config.h>
 414 #include <linux/types.h>
 415 #include <linux/fcntl.h>
 416 
 417 #include <net/icmp.h>
 418 #include <net/tcp.h>
 419 
 420 #include <asm/segment.h>
 421 
 422 unsigned long seq_offset;
 423 struct tcp_mib  tcp_statistics;
 424 
 425 static void tcp_close(struct sock *sk, int timeout);
 426 
 427 /*
 428  *      The less said about this the better, but it works and will do for 1.2  (and 1.4 ;))
 429  */
 430 
 431 struct wait_queue *master_select_wakeup;
 432 
 433 /*
 434  *      Find someone to 'accept'. Must be called with
 435  *      sk->inuse=1 or cli()
 436  */ 
 437 
 438 static struct sk_buff *tcp_find_established(struct sock *s)
     /* [previous][next][first][last][top][bottom][index][help] */
 439 {
 440         struct sk_buff *p=skb_peek(&s->receive_queue);
 441         if(p==NULL)
 442                 return NULL;
 443         do
 444         {
 445                 if(p->sk->state == TCP_ESTABLISHED || p->sk->state >= TCP_FIN_WAIT1)
 446                         return p;
 447                 p=p->next;
 448         }
 449         while(p!=(struct sk_buff *)&s->receive_queue);
 450         return NULL;
 451 }
 452 
 453 /*
 454  *      Remove a completed connection and return it. This is used by
 455  *      tcp_accept() to get connections from the queue.
 456  */
 457 
 458 static struct sk_buff *tcp_dequeue_established(struct sock *s)
     /* [previous][next][first][last][top][bottom][index][help] */
 459 {
 460         struct sk_buff *skb;
 461         unsigned long flags;
 462         save_flags(flags);
 463         cli(); 
 464         skb=tcp_find_established(s);
 465         if(skb!=NULL)
 466                 skb_unlink(skb);        /* Take it off the queue */
 467         restore_flags(flags);
 468         return skb;
 469 }
 470 
 471 /* 
 472  *      This routine closes sockets which have been at least partially
 473  *      opened, but not yet accepted. Currently it is only called by
 474  *      tcp_close, and timeout mirrors the value there. 
 475  */
 476 
 477 static void tcp_close_pending (struct sock *sk) 
     /* [previous][next][first][last][top][bottom][index][help] */
 478 {
 479         struct sk_buff *skb;
 480 
 481         while ((skb = skb_dequeue(&sk->receive_queue)) != NULL) 
 482         {
 483                 skb->sk->dead=1;
 484                 tcp_close(skb->sk, 0);
 485                 kfree_skb(skb, FREE_READ);
 486         }
 487         return;
 488 }
 489 
 490 /*
 491  *      Enter the time wait state. 
 492  */
 493 
 494 void tcp_time_wait(struct sock *sk)
     /* [previous][next][first][last][top][bottom][index][help] */
 495 {
 496         tcp_set_state(sk,TCP_TIME_WAIT);
 497         sk->shutdown = SHUTDOWN_MASK;
 498         if (!sk->dead)
 499                 sk->state_change(sk);
 500         tcp_reset_msl_timer(sk, TIME_CLOSE, TCP_TIMEWAIT_LEN);
 501 }
 502 
 503 
 504 /*
 505  * This routine is called by the ICMP module when it gets some
 506  * sort of error condition.  If err < 0 then the socket should
 507  * be closed and the error returned to the user.  If err > 0
 508  * it's just the icmp type << 8 | icmp code.  After adjustment
 509  * header points to the first 8 bytes of the tcp header.  We need
 510  * to find the appropriate port.
 511  */
 512 
 513 void tcp_err(int type, int code, unsigned char *header, __u32 daddr,
     /* [previous][next][first][last][top][bottom][index][help] */
 514         __u32 saddr, struct inet_protocol *protocol)
 515 {
 516         struct tcphdr *th = (struct tcphdr *)header;
 517         struct sock *sk;
 518         
 519         /*
 520          *      This one is _WRONG_. FIXME urgently.
 521          */
 522 #ifndef CONFIG_NO_PATH_MTU_DISCOVERY     
 523         struct iphdr *iph=(struct iphdr *)(header-sizeof(struct iphdr));
 524 #endif  
 525         th =(struct tcphdr *)header;
 526         sk = get_sock(&tcp_prot, th->source, daddr, th->dest, saddr);
 527 
 528         if (sk == NULL) 
 529                 return;
 530   
 531         if (type == ICMP_SOURCE_QUENCH) 
 532         {
 533                 /*
 534                  * FIXME:
 535                  * For now we will just trigger a linear backoff.
 536                  * The slow start code should cause a real backoff here.
 537                  */
 538                 if (sk->cong_window > 4)
 539                         sk->cong_window--;
 540                 return;
 541         }
 542         
 543         if (type == ICMP_PARAMETERPROB)
 544         {
 545                 sk->err=EPROTO;
 546                 sk->error_report(sk);
 547         }
 548 
 549 #ifndef CONFIG_NO_PATH_MTU_DISCOVERY
 550         if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
 551         {
 552                 struct rtable * rt;
 553                 /*
 554                  * Ugly trick to pass MTU to protocol layer.
 555                  * Really we should add argument "info" to error handler.
 556                  */
 557                 unsigned short new_mtu = ntohs(iph->id);
 558 
 559                 if ((rt = sk->ip_route_cache) != NULL)
 560                         if (rt->rt_mtu > new_mtu)
 561                                 rt->rt_mtu = new_mtu;
 562 
 563                 if (sk->mtu > new_mtu - sizeof(struct iphdr) - sizeof(struct tcphdr)
 564                         && new_mtu > sizeof(struct iphdr)+sizeof(struct tcphdr))
 565                         sk->mtu = new_mtu - sizeof(struct iphdr) - sizeof(struct tcphdr);
 566 
 567                 return;
 568         }
 569 #endif
 570 
 571         /*
 572          * If we've already connected we will keep trying
 573          * until we time out, or the user gives up.
 574          */
 575 
 576         if (code < 13)
 577         {       
 578                 if(icmp_err_convert[code].fatal || sk->state == TCP_SYN_SENT || sk->state == TCP_SYN_RECV)
 579                 {
 580                         sk->err = icmp_err_convert[code].errno;
 581                         if (sk->state == TCP_SYN_SENT || sk->state == TCP_SYN_RECV) 
 582                         {
 583                                 tcp_statistics.TcpAttemptFails++;
 584                                 tcp_set_state(sk,TCP_CLOSE);
 585                                 sk->error_report(sk);           /* Wake people up to see the error (see connect in sock.c) */
 586                         }
 587                 }
 588                 else    /* Only an error on timeout */
 589                         sk->err_soft = icmp_err_convert[code].errno;
 590         }
 591 }
 592 
 593 
 594 /*
 595  *      Walk down the receive queue counting readable data until we hit the end or we find a gap
 596  *      in the received data queue (ie a frame missing that needs sending to us). Not
 597  *      sorting using two queues as data arrives makes life so much harder.
 598  */
 599 
 600 static int tcp_readable(struct sock *sk)
     /* [previous][next][first][last][top][bottom][index][help] */
 601 {
 602         unsigned long counted;
 603         unsigned long amount;
 604         struct sk_buff *skb;
 605         int sum;
 606         unsigned long flags;
 607 
 608         if(sk && sk->debug)
 609                 printk("tcp_readable: %p - ",sk);
 610 
 611         save_flags(flags);
 612         cli();
 613         if (sk == NULL || (skb = skb_peek(&sk->receive_queue)) == NULL)
 614         {
 615                 restore_flags(flags);
 616                 if(sk && sk->debug) 
 617                         printk("empty\n");
 618                 return(0);
 619         }
 620   
 621         counted = sk->copied_seq;       /* Where we are at the moment */
 622         amount = 0;
 623   
 624         /* 
 625          *      Do until a push or until we are out of data. 
 626          */
 627          
 628         do 
 629         {
 630                 if (before(counted, skb->seq))          /* Found a hole so stops here */
 631                         break;
 632                 sum = skb->len - (counted - skb->seq);  /* Length - header but start from where we are up to (avoid overlaps) */
 633                 if (skb->h.th->syn)
 634                         sum++;
 635                 if (sum > 0) 
 636                 {                                       /* Add it up, move on */
 637                         amount += sum;
 638                         if (skb->h.th->syn) 
 639                                 amount--;
 640                         counted += sum;
 641                 }
 642                 /*
 643                  * Don't count urg data ... but do it in the right place!
 644                  * Consider: "old_data (ptr is here) URG PUSH data"
 645                  * The old code would stop at the first push because
 646                  * it counted the urg (amount==1) and then does amount--
 647                  * *after* the loop.  This means tcp_readable() always
 648                  * returned zero if any URG PUSH was in the queue, even
 649                  * though there was normal data available. If we subtract
 650                  * the urg data right here, we even get it to work for more
 651                  * than one URG PUSH skb without normal data.
 652                  * This means that select() finally works now with urg data
 653                  * in the queue.  Note that rlogin was never affected
 654                  * because it doesn't use select(); it uses two processes
 655                  * and a blocking read().  And the queue scan in tcp_read()
 656                  * was correct.  Mike <pall@rz.uni-karlsruhe.de>
 657                  */
 658                 if (skb->h.th->urg)
 659                         amount--;       /* don't count urg data */
 660                 if (amount && skb->h.th->psh) break;
 661                 skb = skb->next;
 662         }
 663         while(skb != (struct sk_buff *)&sk->receive_queue);
 664 
 665         restore_flags(flags);
 666         if(sk->debug)
 667                 printk("got %lu bytes.\n",amount);
 668         return(amount);
 669 }
 670 
 671 /*
 672  * LISTEN is a special case for select..
 673  */
 674 static int tcp_listen_select(struct sock *sk, int sel_type, select_table *wait)
     /* [previous][next][first][last][top][bottom][index][help] */
 675 {
 676         if (sel_type == SEL_IN) {
 677                 int retval;
 678 
 679                 sk->inuse = 1;
 680                 retval = (tcp_find_established(sk) != NULL);
 681                 release_sock(sk);
 682                 if (!retval)
 683                         select_wait(&master_select_wakeup,wait);
 684                 return retval;
 685         }
 686         return 0;
 687 }
 688 
 689 
 690 /*
 691  *      Wait for a TCP event.
 692  *
 693  *      Note that we don't need to set "sk->inuse", as the upper select layers
 694  *      take care of normal races (between the test and the event) and we don't
 695  *      go look at any of the socket buffers directly.
 696  */
 697 static int tcp_select(struct sock *sk, int sel_type, select_table *wait)
     /* [previous][next][first][last][top][bottom][index][help] */
 698 {
 699         if (sk->state == TCP_LISTEN)
 700                 return tcp_listen_select(sk, sel_type, wait);
 701 
 702         switch(sel_type) {
 703         case SEL_IN:
 704                 if (sk->err)
 705                         return 1;
 706                 if (sk->state == TCP_SYN_SENT || sk->state == TCP_SYN_RECV)
 707                         break;
 708 
 709                 if (sk->shutdown & RCV_SHUTDOWN)
 710                         return 1;
 711                         
 712                 if (sk->acked_seq == sk->copied_seq)
 713                         break;
 714 
 715                 if (sk->urg_seq != sk->copied_seq ||
 716                     sk->acked_seq != sk->copied_seq+1 ||
 717                     sk->urginline || !sk->urg_data)
 718                         return 1;
 719                 break;
 720 
 721         case SEL_OUT:
 722                 if (sk->err)
 723                         return 1;
 724                 if (sk->shutdown & SEND_SHUTDOWN) 
 725                         return 0;
 726                 if (sk->state == TCP_SYN_SENT || sk->state == TCP_SYN_RECV)
 727                         break;
 728                 /*
 729                  * This is now right thanks to a small fix
 730                  * by Matt Dillon.
 731                  */
 732 
 733                 if (sock_wspace(sk) < sk->mtu+128+sk->prot->max_header)
 734                         break;
 735                 return 1;
 736 
 737         case SEL_EX:
 738                 if (sk->urg_data)
 739                         return 1;
 740                 break;
 741         }
 742         select_wait(sk->sleep, wait);
 743         return 0;
 744 }
 745 
 746 int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
     /* [previous][next][first][last][top][bottom][index][help] */
 747 {
 748         int err;
 749         switch(cmd) 
 750         {
 751 
 752                 case TIOCINQ:
 753 #ifdef FIXME    /* FIXME: */
 754                 case FIONREAD:
 755 #endif
 756                 {
 757                         unsigned long amount;
 758 
 759                         if (sk->state == TCP_LISTEN) 
 760                                 return(-EINVAL);
 761 
 762                         sk->inuse = 1;
 763                         amount = tcp_readable(sk);
 764                         release_sock(sk);
 765                         err=verify_area(VERIFY_WRITE,(void *)arg, sizeof(int));
 766                         if(err)
 767                                 return err;
 768                         put_user(amount, (int *)arg);
 769                         return(0);
 770                 }
 771                 case SIOCATMARK:
 772                 {
 773                         int answ = sk->urg_data && sk->urg_seq == sk->copied_seq;
 774 
 775                         err = verify_area(VERIFY_WRITE,(void *) arg, sizeof(int));
 776                         if (err)
 777                                 return err;
 778                         put_user(answ,(int *) arg);
 779                         return(0);
 780                 }
 781                 case TIOCOUTQ:
 782                 {
 783                         unsigned long amount;
 784 
 785                         if (sk->state == TCP_LISTEN) return(-EINVAL);
 786                         amount = sock_wspace(sk);
 787                         err=verify_area(VERIFY_WRITE,(void *)arg, sizeof(int));
 788                         if(err)
 789                                 return err;
 790                         put_user(amount, (int *)arg);
 791                         return(0);
 792                 }
 793                 default:
 794                         return(-EINVAL);
 795         }
 796 }
 797 
 798 
 799 /*
 800  *      This routine computes a TCP checksum. 
 801  *
 802  *      Modified January 1995 from a go-faster DOS routine by
 803  *      Jorge Cwik <jorge@laser.satlink.net>
 804  */
 805  
 806 void tcp_send_check(struct tcphdr *th, unsigned long saddr, 
     /* [previous][next][first][last][top][bottom][index][help] */
 807                 unsigned long daddr, int len, struct sock *sk)
 808 {
 809         th->check = 0;
 810         th->check = tcp_check(th, len, saddr, daddr,
 811                 csum_partial((char *)th,len,0));
 812         return;
 813 }
 814 
 815 
 816 /* 
 817  *      This routine builds a generic TCP header. 
 818  */
 819  
 820 extern __inline int tcp_build_header(struct tcphdr *th, struct sock *sk, int push)
     /* [previous][next][first][last][top][bottom][index][help] */
 821 {
 822 
 823         memcpy(th,(void *) &(sk->dummy_th), sizeof(*th));
 824         th->seq = htonl(sk->write_seq);
 825         th->psh =(push == 0) ? 1 : 0;
 826         th->doff = sizeof(*th)/4;
 827         th->ack = 1;
 828         th->fin = 0;
 829         sk->ack_backlog = 0;
 830         sk->bytes_rcv = 0;
 831         sk->ack_timed = 0;
 832         th->ack_seq = htonl(sk->acked_seq);
 833         sk->window = tcp_select_window(sk);
 834         th->window = htons(sk->window);
 835 
 836         return(sizeof(*th));
 837 }
 838 
 839 /*
 840  *      This routine copies from a user buffer into a socket,
 841  *      and starts the transmit system.
 842  */
 843 
 844 static int tcp_sendmsg(struct sock *sk, struct msghdr *msg,
     /* [previous][next][first][last][top][bottom][index][help] */
 845           int len, int nonblock, int flags)
 846 {
 847         int copied = 0;
 848         int copy;
 849         int tmp;
 850         int seglen;
 851         int iovct=0;
 852         struct sk_buff *skb;
 853         struct sk_buff *send_tmp;
 854         struct proto *prot;
 855         struct device *dev = NULL;
 856         unsigned char *from;
 857         
 858         /*
 859          *      Do sanity checking for sendmsg/sendto/send
 860          */
 861          
 862         if (flags & ~(MSG_OOB|MSG_DONTROUTE))
 863                 return -EINVAL;
 864         if (msg->msg_name)
 865         {
 866                 struct sockaddr_in *addr=(struct sockaddr_in *)msg->msg_name;
 867                 if(sk->state == TCP_CLOSE)
 868                         return -ENOTCONN;
 869                 if (msg->msg_namelen < sizeof(*addr))
 870                         return -EINVAL;
 871                 if (addr->sin_family && addr->sin_family != AF_INET) 
 872                         return -EINVAL;
 873                 if (addr->sin_port != sk->dummy_th.dest) 
 874                         return -EISCONN;
 875                 if (addr->sin_addr.s_addr != sk->daddr) 
 876                         return -EISCONN;
 877         }
 878         
 879         /*
 880          *      Ok commence sending
 881          */
 882         
 883         while(iovct<msg->msg_iovlen)
 884         {
 885                 seglen=msg->msg_iov[iovct].iov_len;
 886                 from=msg->msg_iov[iovct++].iov_base;
 887                 sk->inuse=1;
 888                 prot = sk->prot;
 889                 while(seglen > 0) 
 890                 {
 891                         if (sk->err) 
 892                         {                       /* Stop on an error */
 893                                 release_sock(sk);
 894                                 if (copied) 
 895                                         return(copied);
 896                                 return sock_error(sk);
 897                         }
 898 
 899                         /*
 900                          *      First thing we do is make sure that we are established. 
 901                          */
 902         
 903                         if (sk->shutdown & SEND_SHUTDOWN) 
 904                         {
 905                                 release_sock(sk);
 906                                 sk->err = EPIPE;
 907                                 if (copied) 
 908                                         return(copied);
 909                                 sk->err = 0;
 910                                 return(-EPIPE);
 911                         }
 912 
 913                         /* 
 914                          *      Wait for a connection to finish.
 915                          */
 916                 
 917                         while(sk->state != TCP_ESTABLISHED && sk->state != TCP_CLOSE_WAIT) 
 918                         {
 919                                 if (sk->err) 
 920                                 {
 921                                         release_sock(sk);
 922                                         if (copied) 
 923                                                 return(copied);
 924                                         return sock_error(sk);
 925                                 }               
 926         
 927                                 if (sk->state != TCP_SYN_SENT && sk->state != TCP_SYN_RECV) 
 928                                 {
 929                                         release_sock(sk);
 930                                         if (copied) 
 931                                                 return(copied);
 932         
 933                                         if (sk->err) 
 934                                                 return sock_error(sk);
 935 
 936                                         if (sk->keepopen) 
 937                                         {
 938                                                 send_sig(SIGPIPE, current, 0);
 939                                         }
 940                                         return(-EPIPE);
 941                                 }
 942         
 943                                 if (nonblock || copied) 
 944                                 {
 945                                         release_sock(sk);
 946                                         if (copied) 
 947                                                 return(copied);
 948                                         return(-EAGAIN);
 949                                 }
 950         
 951                                 release_sock(sk);
 952                                 cli();
 953                         
 954                                 if (sk->state != TCP_ESTABLISHED &&
 955                                         sk->state != TCP_CLOSE_WAIT && sk->err == 0) 
 956                                 {
 957                                         interruptible_sleep_on(sk->sleep);      
 958                                         if (current->signal & ~current->blocked)
 959                                         {
 960                                                 sti();
 961                                                 if (copied) 
 962                                                         return(copied);
 963                                                 return(-ERESTARTSYS);
 964                                         }
 965                                 }
 966                                 sk->inuse = 1;
 967                                 sti();
 968                         }
 969         
 970                 /*
 971                  * The following code can result in copy <= if sk->mss is ever
 972                  * decreased.  It shouldn't be.  sk->mss is min(sk->mtu, sk->max_window).
 973                  * sk->mtu is constant once SYN processing is finished.  I.e. we
 974                  * had better not get here until we've seen his SYN and at least one
 975                  * valid ack.  (The SYN sets sk->mtu and the ack sets sk->max_window.)
 976                  * But ESTABLISHED should guarantee that.  sk->max_window is by definition
 977                  * non-decreasing.  Note that any ioctl to set user_mss must be done
 978                  * before the exchange of SYN's.  If the initial ack from the other
 979                  * end has a window of 0, max_window and thus mss will both be 0.
 980                  */
 981         
 982                 /* 
 983                  *      Now we need to check if we have a half built packet. 
 984                  */
 985 #ifndef CONFIG_NO_PATH_MTU_DISCOVERY
 986                 /*
 987                  *      FIXME:  I'm almost sure that this fragment is BUG,
 988                  *              but it works... I do not know why 8) --ANK
 989                  *
 990                  *      Really, we should rebuild all the queues...
 991                  *      It's difficult. Temprorary hack is to send all
 992                  *      queued segments with allowed fragmentation.
 993                  */
 994                 {
 995                         int new_mss = min(sk->mtu, sk->max_window);
 996                         if (new_mss < sk->mss)
 997                         {
 998                                 tcp_send_partial(sk);
 999                                 sk->mss = new_mss;
1000                         }
1001                 }
1002 #endif
1003         
1004                         if ((skb = tcp_dequeue_partial(sk)) != NULL) 
1005                         {
1006                                 int hdrlen;
1007 
1008                                  /* IP header + TCP header */
1009                                 hdrlen = ((unsigned long)skb->h.th - (unsigned long)skb->data)
1010                                          + sizeof(struct tcphdr);
1011         
1012                                 /* Add more stuff to the end of skb->len */
1013                                 if (!(flags & MSG_OOB)) 
1014                                 {
1015                                         copy = min(sk->mss - (skb->len - hdrlen), seglen);
1016                                         if (copy <= 0) 
1017                                         {
1018                                                 printk("TCP: **bug**: \"copy\" <= 0\n");
1019                                                 return -EFAULT;
1020                                         }                 
1021                                         memcpy_fromfs(skb_put(skb,copy), from, copy);
1022                                         from += copy;
1023                                         copied += copy;
1024                                         len -= copy;
1025                                         sk->write_seq += copy;
1026                                         seglen -= copy;
1027                                 }
1028                                 if ((skb->len - hdrlen) >= sk->mss ||
1029                                         (flags & MSG_OOB) || !sk->packets_out)
1030                                         tcp_send_skb(sk, skb);
1031                                 else
1032                                         tcp_enqueue_partial(skb, sk);
1033                                 continue;
1034                         }
1035 
1036                 /*
1037                  * We also need to worry about the window.
1038                  * If window < 1/2 the maximum window we've seen from this
1039                  *   host, don't use it.  This is sender side
1040                  *   silly window prevention, as specified in RFC1122.
1041                  *   (Note that this is different than earlier versions of
1042                  *   SWS prevention, e.g. RFC813.).  What we actually do is 
1043                  *   use the whole MSS.  Since the results in the right
1044                  *   edge of the packet being outside the window, it will
1045                  *   be queued for later rather than sent.
1046                  */
1047 
1048                         copy = sk->window_seq - sk->write_seq;
1049                         if (copy <= 0 || copy < (sk->max_window >> 1) || copy > sk->mss)
1050                                 copy = sk->mss;
1051                         if (copy > seglen)
1052                                 copy = seglen;
1053 
1054                 /*
1055                  *      We should really check the window here also. 
1056                  */
1057                  
1058                         send_tmp = NULL;
1059                         if (copy < sk->mss && !(flags & MSG_OOB) && sk->packets_out) 
1060                         {
1061                                 /*
1062                                  *      We will release the socket in case we sleep here. 
1063                                  */
1064                                 release_sock(sk);
1065                                 /*
1066                                  *      NB: following must be mtu, because mss can be increased.
1067                                  *      mss is always <= mtu 
1068                                  */
1069                                 skb = sock_wmalloc(sk, sk->mtu + 128 + prot->max_header + 15, 0, GFP_KERNEL);
1070                                 sk->inuse = 1;
1071                                 send_tmp = skb;
1072                         } 
1073                         else 
1074                         {
1075                                 /*
1076                                  *      We will release the socket in case we sleep here. 
1077                                  */
1078                                 release_sock(sk);
1079                                 skb = sock_wmalloc(sk, copy + prot->max_header + 15 , 0, GFP_KERNEL);
1080                                 sk->inuse = 1;
1081                         }
1082         
1083                         /*
1084                          *      If we didn't get any memory, we need to sleep. 
1085                          */
1086         
1087                         if (skb == NULL) 
1088                         {
1089                                 sk->socket->flags |= SO_NOSPACE;
1090                                 if (nonblock) 
1091                                 {
1092                                         release_sock(sk);
1093                                         if (copied) 
1094                                                 return(copied);
1095                                         return(-EAGAIN);
1096                                 }
1097 
1098                                 release_sock(sk);
1099                                 cli();
1100                                 if (sk->wmem_alloc*2 > sk->sndbuf &&
1101                                     (sk->state == TCP_ESTABLISHED||sk->state == TCP_CLOSE_WAIT)
1102                                         && sk->err == 0) 
1103                                 {
1104                                         sk->socket->flags &= ~SO_NOSPACE;
1105                                         interruptible_sleep_on(sk->sleep);
1106                                         if (current->signal & ~current->blocked) 
1107                                         {
1108                                                 sti();
1109                                                 if (copied) 
1110                                                         return(copied);
1111                                                 return(-ERESTARTSYS);
1112                                         }
1113                                 }
1114                                 sk->inuse = 1;
1115                                 sti();
1116                                 continue;
1117                         }
1118 
1119                         skb->sk = sk;
1120                         skb->free = 0;
1121                         skb->localroute = sk->localroute|(flags&MSG_DONTROUTE);
1122         
1123                         /*
1124                          * FIXME: we need to optimize this.
1125                          * Perhaps some hints here would be good.
1126                          */
1127                 
1128                         tmp = prot->build_header(skb, sk->saddr, sk->daddr, &dev,
1129                                  IPPROTO_TCP, sk->opt, skb->truesize,sk->ip_tos,sk->ip_ttl,&sk->ip_route_cache);
1130                         if (tmp < 0 ) 
1131                         {
1132                                 sock_wfree(sk, skb);
1133                                 release_sock(sk);
1134                                 if (copied) 
1135                                         return(copied);
1136                                 return(tmp);
1137                         }
1138 #ifndef CONFIG_NO_PATH_MTU_DISCOVERY
1139                         skb->ip_hdr->frag_off |= htons(IP_DF);
1140 #endif
1141                         skb->dev = dev;
1142                         skb->h.th =(struct tcphdr *)skb_put(skb,sizeof(struct tcphdr));
1143                         tmp = tcp_build_header(skb->h.th, sk, seglen-copy);
1144                         if (tmp < 0) 
1145                         {
1146                                 sock_wfree(sk, skb);
1147                                 release_sock(sk);
1148                                 if (copied) 
1149                                         return(copied);
1150                                 return(tmp);
1151                         }
1152         
1153                         if (flags & MSG_OOB) 
1154                         {
1155                                 skb->h.th->urg = 1;
1156                                 skb->h.th->urg_ptr = ntohs(copy);
1157                         }
1158 
1159                         memcpy_fromfs(skb_put(skb,copy), from, copy);
1160                 
1161                         from += copy;
1162                         copied += copy;
1163                         len -= copy;
1164                         seglen -= copy;
1165                         skb->free = 0;
1166                         sk->write_seq += copy;
1167                 
1168                         if (send_tmp != NULL) 
1169                         {
1170                                 tcp_enqueue_partial(send_tmp, sk);
1171                                 continue;
1172                         }
1173                         tcp_send_skb(sk, skb);
1174                 }
1175         }
1176         sk->err = 0;
1177 
1178 /*
1179  *      Nagle's rule. Turn Nagle off with TCP_NODELAY for highly
1180  *      interactive fast network servers. It's meant to be on and
1181  *      it really improves the throughput though not the echo time
1182  *      on my slow slip link - Alan
1183  */
1184 
1185 /*
1186  *      Avoid possible race on send_tmp - c/o Johannes Stille 
1187  */
1188  
1189         if(sk->partial && ((!sk->packets_out) 
1190      /* If not nagling we can send on the before case too.. */
1191               || (sk->nonagle && before(sk->write_seq , sk->window_seq))
1192         ))
1193                 tcp_send_partial(sk);
1194 
1195         release_sock(sk);
1196         return(copied);
1197 }
1198 
1199 /*
1200  *      Send an ack if one is backlogged at this point. Ought to merge
1201  *      this with tcp_send_ack().
1202  *      This is called for delayed acks also.
1203  */
1204  
1205 void tcp_read_wakeup(struct sock *sk)
     /* [previous][next][first][last][top][bottom][index][help] */
1206 {
1207         int tmp;
1208         struct device *dev = NULL;
1209         struct tcphdr *t1;
1210         struct sk_buff *buff;
1211 
1212         if (!sk->ack_backlog) 
1213                 return;
1214 
1215         /*
1216          * If we're closed, don't send an ack, or we'll get a RST
1217          * from the closed destination.
1218          */
1219         if ((sk->state == TCP_CLOSE) || (sk->state == TCP_TIME_WAIT))
1220                 return; 
1221 
1222         /*
1223          * FIXME: we need to put code here to prevent this routine from
1224          * being called.  Being called once in a while is ok, so only check
1225          * if this is the second time in a row.
1226          */
1227 
1228         /*
1229          * We need to grab some memory, and put together an ack,
1230          * and then put it into the queue to be sent.
1231          */
1232 
1233         buff = sock_wmalloc(sk,MAX_ACK_SIZE,1, GFP_ATOMIC);
1234         if (buff == NULL) 
1235         {
1236                 /* Try again real soon. */
1237                 tcp_reset_xmit_timer(sk, TIME_WRITE, HZ);
1238                 return;
1239         }
1240 
1241         buff->sk = sk;
1242         buff->localroute = sk->localroute;
1243         
1244         /*
1245          *      Put in the IP header and routing stuff. 
1246          */
1247 
1248         tmp = sk->prot->build_header(buff, sk->saddr, sk->daddr, &dev,
1249                                IPPROTO_TCP, sk->opt, MAX_ACK_SIZE,sk->ip_tos,sk->ip_ttl,&sk->ip_route_cache);
1250         if (tmp < 0) 
1251         {
1252                 buff->free = 1;
1253                 sock_wfree(sk, buff);
1254                 return;
1255         }
1256 
1257         t1 =(struct tcphdr *)skb_put(buff,sizeof(struct tcphdr));
1258 
1259         memcpy(t1,(void *) &sk->dummy_th, sizeof(*t1));
1260         t1->seq = htonl(sk->sent_seq);
1261         t1->ack = 1;
1262         t1->res1 = 0;
1263         t1->res2 = 0;
1264         t1->rst = 0;
1265         t1->urg = 0;
1266         t1->syn = 0;
1267         t1->psh = 0;
1268 
1269 
1270         sk->ack_backlog = 0;
1271         sk->bytes_rcv = 0;
1272 
1273         sk->window = tcp_select_window(sk);
1274         t1->window = htons(sk->window);
1275         t1->ack_seq = htonl(sk->acked_seq);
1276         t1->doff = sizeof(*t1)/4;
1277         tcp_send_check(t1, sk->saddr, sk->daddr, sizeof(*t1), sk);
1278         sk->prot->queue_xmit(sk, dev, buff, 1);
1279         tcp_statistics.TcpOutSegs++;
1280 }
1281 
1282 
1283 /*
1284  *      FIXME:
1285  *      This routine frees used buffers.
1286  *      It should consider sending an ACK to let the
1287  *      other end know we now have a bigger window.
1288  */
1289 
1290 static void cleanup_rbuf(struct sock *sk)
     /* [previous][next][first][last][top][bottom][index][help] */
1291 {
1292         unsigned long flags;
1293         struct sk_buff *skb;
1294         unsigned long rspace;
1295 
1296         save_flags(flags);
1297         cli();
1298 
1299         /*
1300          * See if we have anything to free up?
1301          */
1302 
1303         skb = skb_peek(&sk->receive_queue);
1304         if (!skb || !skb->used || skb->users) {
1305                 restore_flags(flags);
1306                 return;
1307         }
1308 
1309         /*
1310          *      We have to loop through all the buffer headers,
1311          *      and try to free up all the space we can.
1312          */
1313 
1314         do {
1315                 skb_unlink(skb);
1316                 skb->sk = sk;
1317                 kfree_skb(skb, FREE_READ);
1318                 skb = skb_peek(&sk->receive_queue);
1319         } while (skb && skb->used && !skb->users);
1320         restore_flags(flags);
1321 
1322         /*
1323          *      FIXME:
1324          *      At this point we should send an ack if the difference
1325          *      in the window, and the amount of space is bigger than
1326          *      TCP_WINDOW_DIFF.
1327          */
1328 
1329         rspace=sock_rspace(sk);
1330         if(sk->debug)
1331                 printk("sk->rspace = %lu\n", rspace);
1332         /*
1333          * This area has caused the most trouble.  The current strategy
1334          * is to simply do nothing if the other end has room to send at
1335          * least 3 full packets, because the ack from those will auto-
1336          * matically update the window.  If the other end doesn't think
1337          * we have much space left, but we have room for at least 1 more
1338          * complete packet than it thinks we do, we will send an ack
1339          * immediately.  Otherwise we will wait up to .5 seconds in case
1340          * the user reads some more.
1341          */
1342         sk->ack_backlog++;
1343 
1344         /*
1345          * It's unclear whether to use sk->mtu or sk->mss here.  They differ only
1346          * if the other end is offering a window smaller than the agreed on MSS
1347          * (called sk->mtu here).  In theory there's no connection between send
1348          * and receive, and so no reason to think that they're going to send
1349          * small packets.  For the moment I'm using the hack of reducing the mss
1350          * only on the send side, so I'm putting mtu here.
1351          */
1352 
1353         if (rspace > (sk->window - sk->bytes_rcv + sk->mtu)) 
1354         {
1355                 /* Send an ack right now. */
1356                 tcp_read_wakeup(sk);
1357         } 
1358         else 
1359         {
1360                 /* Force it to send an ack soon. */
1361                 int was_active = del_timer(&sk->retransmit_timer);
1362                 if (!was_active || jiffies+TCP_ACK_TIME < sk->timer.expires) 
1363                 {
1364                         tcp_reset_xmit_timer(sk, TIME_WRITE, TCP_ACK_TIME);
1365                 } 
1366                 else
1367                         add_timer(&sk->retransmit_timer);
1368         }
1369 } 
1370 
1371 
1372 /*
1373  *      Handle reading urgent data. BSD has very simple semantics for
1374  *      this, no blocking and very strange errors 8)
1375  */
1376  
1377 static int tcp_recv_urg(struct sock * sk, int nonblock,
     /* [previous][next][first][last][top][bottom][index][help] */
1378              struct msghdr *msg, int len, int flags, int *addr_len)
1379 {
1380         /*
1381          *      No URG data to read
1382          */
1383         if (sk->urginline || !sk->urg_data || sk->urg_data == URG_READ)
1384                 return -EINVAL; /* Yes this is right ! */
1385                 
1386         if (sk->err) 
1387                 return sock_error(sk);
1388                 
1389         if (sk->state == TCP_CLOSE || sk->done) 
1390         {
1391                 if (!sk->done) 
1392                 {
1393                         sk->done = 1;
1394                         return 0;
1395                 }
1396                 return -ENOTCONN;
1397         }
1398 
1399         if (sk->shutdown & RCV_SHUTDOWN) 
1400         {
1401                 sk->done = 1;
1402                 return 0;
1403         }
1404         sk->inuse = 1;
1405         if (sk->urg_data & URG_VALID) 
1406         {
1407                 char c = sk->urg_data;
1408                 if (!(flags & MSG_PEEK))
1409                         sk->urg_data = URG_READ;
1410                 memcpy_toiovec(msg->msg_iov, &c, 1);
1411                 if(msg->msg_name)
1412                 {
1413                         struct sockaddr_in *sin=(struct sockaddr_in *)msg->msg_name;
1414                         sin->sin_family=AF_INET;
1415                         sin->sin_addr.s_addr=sk->daddr;
1416                         sin->sin_port=sk->dummy_th.dest;
1417                 }
1418                 if(addr_len)
1419                         *addr_len=sizeof(struct sockaddr_in);
1420                 release_sock(sk);
1421                 return 1;
1422         }
1423         release_sock(sk);
1424         
1425         /*
1426          * Fixed the recv(..., MSG_OOB) behaviour.  BSD docs and
1427          * the available implementations agree in this case:
1428          * this call should never block, independent of the
1429          * blocking state of the socket.
1430          * Mike <pall@rz.uni-karlsruhe.de>
1431          */
1432         return -EAGAIN;
1433 }
1434 
1435 
1436 /*
1437  *      This routine copies from a sock struct into the user buffer. 
1438  */
1439  
1440 static int tcp_recvmsg(struct sock *sk, struct msghdr *msg,
     /* [previous][next][first][last][top][bottom][index][help] */
1441         int len, int nonblock, int flags, int *addr_len)
1442 {
1443         struct wait_queue wait = { current, NULL };
1444         int copied = 0;
1445         u32 peek_seq;
1446         volatile u32 *seq;      /* So gcc doesn't overoptimise */
1447         unsigned long used;
1448 
1449         /* 
1450          *      This error should be checked. 
1451          */
1452          
1453         if (sk->state == TCP_LISTEN)
1454                 return -ENOTCONN;
1455 
1456         /*
1457          *      Urgent data needs to be handled specially. 
1458          */
1459          
1460         if (flags & MSG_OOB)
1461                 return tcp_recv_urg(sk, nonblock, msg, len, flags, addr_len);
1462 
1463         /*
1464          *      Copying sequence to update. This is volatile to handle
1465          *      the multi-reader case neatly (memcpy_to/fromfs might be 
1466          *      inline and thus not flush cached variables otherwise).
1467          */
1468          
1469         peek_seq = sk->copied_seq;
1470         seq = &sk->copied_seq;
1471         if (flags & MSG_PEEK)
1472                 seq = &peek_seq;
1473 
1474         add_wait_queue(sk->sleep, &wait);
1475         sk->inuse = 1;
1476         while (len > 0) 
1477         {
1478                 struct sk_buff * skb;
1479                 u32 offset;
1480         
1481                 /*
1482                  * Are we at urgent data? Stop if we have read anything.
1483                  */
1484                  
1485                 if (copied && sk->urg_data && sk->urg_seq == *seq)
1486                         break;
1487 
1488                 /*
1489                  *      Next get a buffer.
1490                  */
1491                  
1492                 current->state = TASK_INTERRUPTIBLE;
1493 
1494                 skb = skb_peek(&sk->receive_queue);
1495                 do 
1496                 {
1497                         if (!skb)
1498                                 break;
1499                         if (before(*seq, skb->seq))
1500                                 break;
1501                         offset = *seq - skb->seq;
1502                         if (skb->h.th->syn)
1503                                 offset--;
1504                         if (offset < skb->len)
1505                                 goto found_ok_skb;
1506                         if (skb->h.th->fin)
1507                                 goto found_fin_ok;
1508                         if (!(flags & MSG_PEEK))
1509                                 skb->used = 1;
1510                         skb = skb->next;
1511                 }
1512                 while (skb != (struct sk_buff *)&sk->receive_queue);
1513 
1514                 if (copied)
1515                         break;
1516 
1517                 if (sk->err) 
1518                 {
1519                         copied = sock_error(sk);
1520                         break;
1521                 }
1522 
1523                 if (sk->state == TCP_CLOSE) 
1524                 {
1525                         if (!sk->done) 
1526                         {
1527                                 sk->done = 1;
1528                                 break;
1529                         }
1530                         copied = -ENOTCONN;
1531                         break;
1532                 }
1533 
1534                 if (sk->shutdown & RCV_SHUTDOWN) 
1535                 {
1536                         sk->done = 1;
1537                         break;
1538                 }
1539                         
1540                 if (nonblock) 
1541                 {
1542                         copied = -EAGAIN;
1543                         break;
1544                 }
1545 
1546                 cleanup_rbuf(sk);
1547                 release_sock(sk);
1548                 sk->socket->flags |= SO_WAITDATA;
1549                 schedule();
1550                 sk->socket->flags &= ~SO_WAITDATA;
1551                 sk->inuse = 1;
1552 
1553                 if (current->signal & ~current->blocked) 
1554                 {
1555                         copied = -ERESTARTSYS;
1556                         break;
1557                 }
1558                 continue;
1559 
1560         found_ok_skb:
1561                 /*
1562                  *      Lock the buffer. We can be fairly relaxed as
1563                  *      an interrupt will never steal a buffer we are 
1564                  *      using unless I've missed something serious in
1565                  *      tcp_data.
1566                  */
1567                 
1568                 skb->users++;
1569                 
1570                 /*
1571                  *      Ok so how much can we use ? 
1572                  */
1573                  
1574                 used = skb->len - offset;
1575                 if (len < used)
1576                         used = len;
1577                 /*
1578                  *      Do we have urgent data here? 
1579                  */
1580                 
1581                 if (sk->urg_data) 
1582                 {
1583                         u32 urg_offset = sk->urg_seq - *seq;
1584                         if (urg_offset < used) 
1585                         {
1586                                 if (!urg_offset) 
1587                                 {
1588                                         if (!sk->urginline) 
1589                                         {
1590                                                 ++*seq;
1591                                                 offset++;
1592                                                 used--;
1593                                         }
1594                                 }
1595                                 else
1596                                         used = urg_offset;
1597                         }
1598                 }
1599                 
1600                 /*
1601                  *      Copy it - We _MUST_ update *seq first so that we
1602                  *      don't ever double read when we have dual readers
1603                  */
1604                  
1605                 *seq += used;
1606 
1607                 /*
1608                  *      This memcpy_tofs can sleep. If it sleeps and we
1609                  *      do a second read it relies on the skb->users to avoid
1610                  *      a crash when cleanup_rbuf() gets called.
1611                  */
1612                  
1613                 memcpy_toiovec(msg->msg_iov,((unsigned char *)skb->h.th) +
1614                         skb->h.th->doff*4 + offset, used);
1615                 copied += used;
1616                 len -= used;
1617                 
1618                 /*
1619                  *      We now will not sleep again until we are finished
1620                  *      with skb. Sorry if you are doing the SMP port
1621                  *      but you'll just have to fix it neatly ;)
1622                  */
1623                  
1624                 skb->users --;
1625                 
1626                 if (after(sk->copied_seq,sk->urg_seq))
1627                         sk->urg_data = 0;
1628                 if (used + offset < skb->len)
1629                         continue;
1630                 
1631                 /*
1632                  *      Process the FIN.
1633                  */
1634 
1635                 if (skb->h.th->fin)
1636                         goto found_fin_ok;
1637                 if (flags & MSG_PEEK)
1638                         continue;
1639                 skb->used = 1;
1640                 continue;
1641 
1642         found_fin_ok:
1643                 ++*seq;
1644                 if (flags & MSG_PEEK)
1645                         break;
1646                         
1647                 /*
1648                  *      All is done
1649                  */
1650                  
1651                 skb->used = 1;
1652                 sk->shutdown |= RCV_SHUTDOWN;
1653                 break;
1654 
1655         }
1656         
1657         if(copied>0 && msg->msg_name)
1658         {
1659                 struct sockaddr_in *sin=(struct sockaddr_in *)msg->msg_name;
1660                 sin->sin_family=AF_INET;
1661                 sin->sin_addr.s_addr=sk->daddr;
1662                 sin->sin_port=sk->dummy_th.dest;
1663         }
1664         if(addr_len)
1665                 *addr_len=sizeof(struct sockaddr_in);
1666                 
1667         remove_wait_queue(sk->sleep, &wait);
1668         current->state = TASK_RUNNING;
1669 
1670         /* Clean up data we have read: This will do ACK frames */
1671         cleanup_rbuf(sk);
1672         release_sock(sk);
1673         return copied;
1674 }
1675 
1676 
1677 
1678 /*
1679  *      State processing on a close. This implements the state shift for
1680  *      sending our FIN frame. Note that we only send a FIN for some 
1681  *      states. A shutdown() may have already sent the FIN, or we may be
1682  *      closed.
1683  */
1684  
1685 static int tcp_close_state(struct sock *sk, int dead)
     /* [previous][next][first][last][top][bottom][index][help] */
1686 {
1687         int ns=TCP_CLOSE;
1688         int send_fin=0;
1689         switch(sk->state)
1690         {
1691                 case TCP_SYN_SENT:      /* No SYN back, no FIN needed */
1692                         break;
1693                 case TCP_SYN_RECV:
1694                 case TCP_ESTABLISHED:   /* Closedown begin */
1695                         ns=TCP_FIN_WAIT1;
1696                         send_fin=1;
1697                         break;
1698                 case TCP_FIN_WAIT1:     /* Already closing, or FIN sent: no change */
1699                 case TCP_FIN_WAIT2:
1700                 case TCP_CLOSING:
1701                         ns=sk->state;
1702                         break;
1703                 case TCP_CLOSE:
1704                 case TCP_LISTEN:
1705                         break;
1706                 case TCP_CLOSE_WAIT:    /* They have FIN'd us. We send our FIN and
1707                                            wait only for the ACK */
1708                         ns=TCP_LAST_ACK;
1709                         send_fin=1;
1710         }
1711         
1712         tcp_set_state(sk,ns);
1713                 
1714         /*
1715          *      This is a (useful) BSD violating of the RFC. There is a
1716          *      problem with TCP as specified in that the other end could
1717          *      keep a socket open forever with no application left this end.
1718          *      We use a 3 minute timeout (about the same as BSD) then kill
1719          *      our end. If they send after that then tough - BUT: long enough
1720          *      that we won't make the old 4*rto = almost no time - whoops
1721          *      reset mistake.
1722          */
1723         if(dead && ns==TCP_FIN_WAIT2)
1724         {
1725                 int timer_active=del_timer(&sk->timer);
1726                 if(timer_active)
1727                         add_timer(&sk->timer);
1728                 else
1729                         tcp_reset_msl_timer(sk, TIME_CLOSE, TCP_FIN_TIMEOUT);
1730         }
1731         
1732         return send_fin;
1733 }
1734 
1735 /*
1736  *      Shutdown the sending side of a connection. Much like close except
1737  *      that we don't receive shut down or set sk->dead=1.
1738  */
1739 
1740 void tcp_shutdown(struct sock *sk, int how)
     /* [previous][next][first][last][top][bottom][index][help] */
1741 {
1742         /*
1743          *      We need to grab some memory, and put together a FIN,
1744          *      and then put it into the queue to be sent.
1745          *              Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
1746          */
1747 
1748         if (!(how & SEND_SHUTDOWN)) 
1749                 return;
1750          
1751         /*
1752          *      If we've already sent a FIN, or it's a closed state
1753          */
1754          
1755         if (sk->state == TCP_FIN_WAIT1 ||
1756             sk->state == TCP_FIN_WAIT2 ||
1757             sk->state == TCP_CLOSING ||
1758             sk->state == TCP_LAST_ACK ||
1759             sk->state == TCP_TIME_WAIT || 
1760             sk->state == TCP_CLOSE ||
1761             sk->state == TCP_LISTEN
1762           )
1763         {
1764                 return;
1765         }
1766         sk->inuse = 1;
1767 
1768         /*
1769          * flag that the sender has shutdown
1770          */
1771 
1772         sk->shutdown |= SEND_SHUTDOWN;
1773 
1774         /*
1775          *  Clear out any half completed packets. 
1776          */
1777 
1778         if (sk->partial)
1779                 tcp_send_partial(sk);
1780                 
1781         /*
1782          *      FIN if needed
1783          */
1784          
1785         if(tcp_close_state(sk,0))
1786                 tcp_send_fin(sk);
1787                 
1788         release_sock(sk);
1789 }
1790 
1791 static void tcp_close(struct sock *sk, int timeout)
     /* [previous][next][first][last][top][bottom][index][help] */
1792 {
1793         /*
1794          * We need to grab some memory, and put together a FIN, 
1795          * and then put it into the queue to be sent.
1796          */
1797         
1798         sk->inuse = 1;
1799         
1800         tcp_cache_zap();
1801         if(sk->state == TCP_LISTEN)
1802         {
1803                 /* Special case */
1804                 tcp_set_state(sk, TCP_CLOSE);
1805                 tcp_close_pending(sk);
1806                 release_sock(sk);
1807                 return;
1808         }
1809         
1810         sk->keepopen = 1;
1811         sk->shutdown = SHUTDOWN_MASK;
1812 
1813         if (!sk->dead) 
1814                 sk->state_change(sk);
1815 
1816         if (timeout == 0) 
1817         {
1818                 struct sk_buff *skb;
1819                 
1820                 /*
1821                  *  We need to flush the recv. buffs.  We do this only on the
1822                  *  descriptor close, not protocol-sourced closes, because the
1823                  *  reader process may not have drained the data yet!
1824                  */
1825                  
1826                 while((skb=skb_dequeue(&sk->receive_queue))!=NULL)
1827                         kfree_skb(skb, FREE_READ);
1828                 /*
1829                  *      Get rid off any half-completed packets. 
1830                  */
1831 
1832                 if (sk->partial) 
1833                         tcp_send_partial(sk);
1834         }
1835 
1836                 
1837         /*
1838          *      Timeout is not the same thing - however the code likes
1839          *      to send both the same way (sigh).
1840          */
1841          
1842         if(timeout)
1843         {
1844                 tcp_set_state(sk, TCP_CLOSE);   /* Dead */
1845         }
1846         else
1847         {
1848                 if(tcp_close_state(sk,1)==1)
1849                 {
1850                         tcp_send_fin(sk);
1851                 }
1852         }
1853         release_sock(sk);
1854 }
1855 
1856 
1857 /*
1858  *      This will accept the next outstanding connection. 
1859  */
1860  
1861 static struct sock *tcp_accept(struct sock *sk, int flags)
     /* [previous][next][first][last][top][bottom][index][help] */
1862 {
1863         struct sock *newsk;
1864         struct sk_buff *skb;
1865   
1866   /*
1867    * We need to make sure that this socket is listening,
1868    * and that it has something pending.
1869    */
1870 
1871         if (sk->state != TCP_LISTEN) 
1872         {
1873                 sk->err = EINVAL;
1874                 return(NULL); 
1875         }
1876 
1877         /* Avoid the race. */
1878         cli();
1879         sk->inuse = 1;
1880 
1881         while((skb = tcp_dequeue_established(sk)) == NULL) 
1882         {
1883                 if (flags & O_NONBLOCK) 
1884                 {
1885                         sti();
1886                         release_sock(sk);
1887                         sk->err = EAGAIN;
1888                         return(NULL);
1889                 }
1890 
1891                 release_sock(sk);
1892                 interruptible_sleep_on(sk->sleep);
1893                 if (current->signal & ~current->blocked) 
1894                 {
1895                         sti();
1896                         sk->err = ERESTARTSYS;
1897                         return(NULL);
1898                 }
1899                 sk->inuse = 1;
1900         }
1901         sti();
1902 
1903         /*
1904          *      Now all we need to do is return skb->sk. 
1905          */
1906 
1907         newsk = skb->sk;
1908 
1909         kfree_skb(skb, FREE_READ);
1910         sk->ack_backlog--;
1911         release_sock(sk);
1912         return(newsk);
1913 }
1914 
1915 /*
1916  *      This will initiate an outgoing connection. 
1917  */
1918  
1919 static int tcp_connect(struct sock *sk, struct sockaddr_in *usin, int addr_len)
     /* [previous][next][first][last][top][bottom][index][help] */
1920 {
1921         struct sk_buff *buff;
1922         struct device *dev=NULL;
1923         unsigned char *ptr;
1924         int tmp;
1925         int atype;
1926         struct tcphdr *t1;
1927         struct rtable *rt;
1928 
1929         if (sk->state != TCP_CLOSE) 
1930                 return(-EISCONN);
1931 
1932         /*
1933          *      Don't allow a double connect.
1934          */
1935                 
1936         if(sk->daddr)
1937                 return -EINVAL;
1938         
1939         if (addr_len < 8) 
1940                 return(-EINVAL);
1941 
1942         if (usin->sin_family && usin->sin_family != AF_INET) 
1943                 return(-EAFNOSUPPORT);
1944 
1945         /*
1946          *      connect() to INADDR_ANY means loopback (BSD'ism).
1947          */
1948         
1949         if(usin->sin_addr.s_addr==INADDR_ANY)
1950                 usin->sin_addr.s_addr=ip_my_addr();
1951                   
1952         /*
1953          *      Don't want a TCP connection going to a broadcast address 
1954          */
1955 
1956         if ((atype=ip_chk_addr(usin->sin_addr.s_addr)) == IS_BROADCAST || atype==IS_MULTICAST) 
1957                 return -ENETUNREACH;
1958   
1959         sk->inuse = 1;
1960         sk->daddr = usin->sin_addr.s_addr;
1961         sk->write_seq = tcp_init_seq();
1962         sk->window_seq = sk->write_seq;
1963         sk->rcv_ack_seq = sk->write_seq -1;
1964         sk->err = 0;
1965         sk->dummy_th.dest = usin->sin_port;
1966         release_sock(sk);
1967 
1968         buff = sock_wmalloc(sk,MAX_SYN_SIZE,0, GFP_KERNEL);
1969         if (buff == NULL) 
1970         {
1971                 return(-ENOMEM);
1972         }
1973         sk->inuse = 1;
1974         buff->sk = sk;
1975         buff->free = 0;
1976         buff->localroute = sk->localroute;
1977         
1978 
1979         /*
1980          *      Put in the IP header and routing stuff.
1981          */
1982          
1983         tmp = sk->prot->build_header(buff, sk->saddr, sk->daddr, &dev,
1984                 IPPROTO_TCP, NULL, MAX_SYN_SIZE,sk->ip_tos,sk->ip_ttl,&sk->ip_route_cache);
1985         if (tmp < 0) 
1986         {
1987                 sock_wfree(sk, buff);
1988                 release_sock(sk);
1989                 return(-ENETUNREACH);
1990         }
1991         if ((rt = sk->ip_route_cache) != NULL && !sk->saddr)
1992                 sk->saddr = rt->rt_src;
1993         sk->rcv_saddr = sk->saddr;
1994 
1995         t1 = (struct tcphdr *) skb_put(buff,sizeof(struct tcphdr));
1996 
1997         memcpy(t1,(void *)&(sk->dummy_th), sizeof(*t1));
1998         buff->seq = sk->write_seq++;
1999         t1->seq = htonl(buff->seq);
2000         sk->sent_seq = sk->write_seq;
2001         buff->end_seq = sk->write_seq;
2002         t1->ack = 0;
2003         t1->window = 2;
2004         t1->res1=0;
2005         t1->res2=0;
2006         t1->rst = 0;
2007         t1->urg = 0;
2008         t1->psh = 0;
2009         t1->syn = 1;
2010         t1->urg_ptr = 0;
2011         t1->doff = 6;
2012         /* use 512 or whatever user asked for */
2013         
2014         if(rt!=NULL && (rt->rt_flags&RTF_WINDOW))
2015                 sk->window_clamp=rt->rt_window;
2016         else
2017                 sk->window_clamp=0;
2018 
2019         if (sk->user_mss)
2020                 sk->mtu = sk->user_mss;
2021         else if (rt)
2022                 sk->mtu = rt->rt_mtu - sizeof(struct iphdr) - sizeof(struct tcphdr);
2023         else 
2024                 sk->mtu = 576 - sizeof(struct iphdr) - sizeof(struct tcphdr);
2025 
2026         /*
2027          *      but not bigger than device MTU 
2028          */
2029 
2030         if(sk->mtu <32)
2031                 sk->mtu = 32;   /* Sanity limit */
2032                 
2033         sk->mtu = min(sk->mtu, dev->mtu - sizeof(struct iphdr) - sizeof(struct tcphdr));
2034 
2035 #ifdef CONFIG_SKIP
2036         
2037         /*
2038          *      SKIP devices set their MTU to 65535. This is so they can take packets
2039          *      unfragmented to security process then fragment. They could lie to the
2040          *      TCP layer about a suitable MTU, but its easier to let skip sort it out
2041          *      simply because the final package we want unfragmented is going to be
2042          *
2043          *      [IPHDR][IPSP][Security data][Modified TCP data][Security data]
2044          */
2045          
2046         if(skip_pick_mtu!=NULL)         /* If SKIP is loaded.. */
2047                 sk->mtu=skip_pick_mtu(sk->mtu,dev);
2048 #endif
2049         
2050         /*
2051          *      Put in the TCP options to say MTU. 
2052          */
2053 
2054         ptr = skb_put(buff,4);
2055         ptr[0] = 2;
2056         ptr[1] = 4;
2057         ptr[2] = (sk->mtu) >> 8;
2058         ptr[3] = (sk->mtu) & 0xff;
2059         tcp_send_check(t1, sk->saddr, sk->daddr,
2060                   sizeof(struct tcphdr) + 4, sk);
2061 
2062         /*
2063          *      This must go first otherwise a really quick response will get reset. 
2064          */
2065 
2066         tcp_cache_zap();
2067         tcp_set_state(sk,TCP_SYN_SENT);
2068         if(rt&&rt->rt_flags&RTF_IRTT)
2069                 sk->rto = rt->rt_irtt;
2070         else
2071                 sk->rto = TCP_TIMEOUT_INIT;
2072         sk->retransmit_timer.function=&tcp_retransmit_timer;
2073         sk->retransmit_timer.data = (unsigned long)sk;
2074         tcp_reset_xmit_timer(sk, TIME_WRITE, sk->rto);  /* Timer for repeating the SYN until an answer  */
2075         sk->retransmits = 0;                            /* Now works the right way instead of a hacked 
2076                                                                                         initial setting */
2077 
2078         sk->prot->queue_xmit(sk, dev, buff, 0);  
2079         tcp_reset_xmit_timer(sk, TIME_WRITE, sk->rto);
2080         tcp_statistics.TcpActiveOpens++;
2081         tcp_statistics.TcpOutSegs++;
2082   
2083         release_sock(sk);
2084         return(0);
2085 }
2086 
2087 /*
2088  *      Socket option code for TCP. 
2089  */
2090   
2091 int tcp_setsockopt(struct sock *sk, int level, int optname, char *optval, int optlen)
     /* [previous][next][first][last][top][bottom][index][help] */
2092 {
2093         int val,err;
2094 
2095         if(level!=SOL_TCP)
2096                 return ip_setsockopt(sk,level,optname,optval,optlen);
2097 
2098         if (optval == NULL) 
2099                 return(-EINVAL);
2100 
2101         err=verify_area(VERIFY_READ, optval, sizeof(int));
2102         if(err)
2103                 return err;
2104         
2105         val = get_user((int *)optval);
2106 
2107         switch(optname)
2108         {
2109                 case TCP_MAXSEG:
2110 /*
2111  * values greater than interface MTU won't take effect.  however at
2112  * the point when this call is done we typically don't yet know
2113  * which interface is going to be used
2114  */
2115                         if(val<1||val>MAX_WINDOW)
2116                                 return -EINVAL;
2117                         sk->user_mss=val;
2118                         return 0;
2119                 case TCP_NODELAY:
2120                         sk->nonagle=(val==0)?0:1;
2121                         return 0;
2122                 default:
2123                         return(-ENOPROTOOPT);
2124         }
2125 }
2126 
2127 int tcp_getsockopt(struct sock *sk, int level, int optname, char *optval, int *optlen)
     /* [previous][next][first][last][top][bottom][index][help] */
2128 {
2129         int val,err;
2130 
2131         if(level!=SOL_TCP)
2132                 return ip_getsockopt(sk,level,optname,optval,optlen);
2133                         
2134         switch(optname)
2135         {
2136                 case TCP_MAXSEG:
2137                         val=sk->user_mss;
2138                         break;
2139                 case TCP_NODELAY:
2140                         val=sk->nonagle;
2141                         break;
2142                 default:
2143                         return(-ENOPROTOOPT);
2144         }
2145         err=verify_area(VERIFY_WRITE, optlen, sizeof(int));
2146         if(err)
2147                 return err;
2148         put_user(sizeof(int),(int *) optlen);
2149 
2150         err=verify_area(VERIFY_WRITE, optval, sizeof(int));
2151         if(err)
2152                 return err;
2153         put_user(val,(int *)optval);
2154 
2155         return(0);
2156 }       
2157 
2158 
2159 struct proto tcp_prot = {
2160         tcp_close,
2161         ip_build_header,
2162         tcp_connect,
2163         tcp_accept,
2164         ip_queue_xmit,
2165         tcp_retransmit,
2166         tcp_write_wakeup,
2167         tcp_read_wakeup,
2168         tcp_rcv,
2169         tcp_select,
2170         tcp_ioctl,
2171         NULL,
2172         tcp_shutdown,
2173         tcp_setsockopt,
2174         tcp_getsockopt,
2175         tcp_sendmsg,
2176         tcp_recvmsg,
2177         NULL,           /* No special bind() */
2178         128,
2179         0,
2180         "TCP",
2181         0, 0,
2182         {NULL,}
2183 };

/* [previous][next][first][last][top][bottom][index][help] */