tcp_ipv4.c
上传用户:jlfgdled
上传日期:2013-04-10
资源大小:33168k
文件大小:57k
源码类别:

Linux/Unix编程

开发平台:

Unix_Linux

  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: $Id: tcp_ipv4.c,v 1.237.2.1 2002/01/15 08:49:49 davem Exp $
  9.  *
  10.  * IPv4 specific functions
  11.  *
  12.  *
  13.  * code split from:
  14.  * linux/ipv4/tcp.c
  15.  * linux/ipv4/tcp_input.c
  16.  * linux/ipv4/tcp_output.c
  17.  *
  18.  * See tcp.c for author information
  19.  *
  20.  * This program is free software; you can redistribute it and/or
  21.  *      modify it under the terms of the GNU General Public License
  22.  *      as published by the Free Software Foundation; either version
  23.  *      2 of the License, or (at your option) any later version.
  24.  */
  25. /*
  26.  * Changes:
  27.  * David S. Miller : New socket lookup architecture.
  28.  * This code is dedicated to John Dyson.
  29.  * David S. Miller : Change semantics of established hash,
  30.  * half is devoted to TIME_WAIT sockets
  31.  * and the rest go in the other half.
  32.  * Andi Kleen : Add support for syncookies and fixed
  33.  * some bugs: ip options weren't passed to
  34.  * the TCP layer, missed a check for an ACK bit.
  35.  * Andi Kleen : Implemented fast path mtu discovery.
  36.  *       Fixed many serious bugs in the
  37.  * open_request handling and moved
  38.  * most of it into the af independent code.
  39.  * Added tail drop and some other bugfixes.
  40.  * Added new listen sematics.
  41.  * Mike McLagan : Routing by source
  42.  * Juan Jose Ciarlante: ip_dynaddr bits
  43.  * Andi Kleen: various fixes.
  44.  * Vitaly E. Lavrov : Transparent proxy revived after year coma.
  45.  * Andi Kleen : Fix new listen.
  46.  * Andi Kleen : Fix accept error reporting.
  47.  */
  48. #include <linux/config.h>
  49. #include <linux/types.h>
  50. #include <linux/fcntl.h>
  51. #include <linux/random.h>
  52. #include <linux/cache.h>
  53. #include <linux/init.h>
  54. #include <net/icmp.h>
  55. #include <net/tcp.h>
  56. #include <net/ipv6.h>
  57. #include <net/inet_common.h>
  58. #include <linux/inet.h>
  59. #include <linux/stddef.h>
  60. #include <linux/ipsec.h>
  61. extern int sysctl_ip_dynaddr;
  62. extern int sysctl_ip_default_ttl;
  63. int sysctl_tcp_tw_reuse = 0;
  64. /* Check TCP sequence numbers in ICMP packets. */
  65. #define ICMP_MIN_LENGTH 8
  66. /* Socket used for sending RSTs */ 
  67. static struct inode tcp_inode;
  68. static struct socket *tcp_socket=&tcp_inode.u.socket_i;
  69. void tcp_v4_send_check(struct sock *sk, struct tcphdr *th, int len, 
  70.        struct sk_buff *skb);
  71. /*
  72.  * ALL members must be initialised to prevent gcc-2.7.2.3 miscompilation
  73.  */
  74. struct tcp_hashinfo __cacheline_aligned tcp_hashinfo = {
  75. __tcp_ehash:          NULL,
  76. __tcp_bhash:          NULL,
  77. __tcp_bhash_size:     0,
  78. __tcp_ehash_size:     0,
  79. __tcp_listening_hash: { NULL, },
  80. __tcp_lhash_lock:     RW_LOCK_UNLOCKED,
  81. __tcp_lhash_users:    ATOMIC_INIT(0),
  82. __tcp_lhash_wait:
  83.   __WAIT_QUEUE_HEAD_INITIALIZER(tcp_hashinfo.__tcp_lhash_wait),
  84. __tcp_portalloc_lock: SPIN_LOCK_UNLOCKED
  85. };
  86. /*
  87.  * This array holds the first and last local port number.
  88.  * For high-usage systems, use sysctl to change this to
  89.  * 32768-61000
  90.  */
  91. int sysctl_local_port_range[2] = { 1024, 4999 };
  92. int tcp_port_rover = (1024 - 1);
  93. static __inline__ int tcp_hashfn(__u32 laddr, __u16 lport,
  94.  __u32 faddr, __u16 fport)
  95. {
  96. int h = ((laddr ^ lport) ^ (faddr ^ fport));
  97. h ^= h>>16;
  98. h ^= h>>8;
  99. return h & (tcp_ehash_size - 1);
  100. }
  101. static __inline__ int tcp_sk_hashfn(struct sock *sk)
  102. {
  103. __u32 laddr = sk->rcv_saddr;
  104. __u16 lport = sk->num;
  105. __u32 faddr = sk->daddr;
  106. __u16 fport = sk->dport;
  107. return tcp_hashfn(laddr, lport, faddr, fport);
  108. }
  109. /* Allocate and initialize a new TCP local port bind bucket.
  110.  * The bindhash mutex for snum's hash chain must be held here.
  111.  */
  112. struct tcp_bind_bucket *tcp_bucket_create(struct tcp_bind_hashbucket *head,
  113.   unsigned short snum)
  114. {
  115. struct tcp_bind_bucket *tb;
  116. tb = kmem_cache_alloc(tcp_bucket_cachep, SLAB_ATOMIC);
  117. if(tb != NULL) {
  118. tb->port = snum;
  119. tb->fastreuse = 0;
  120. tb->owners = NULL;
  121. if((tb->next = head->chain) != NULL)
  122. tb->next->pprev = &tb->next;
  123. head->chain = tb;
  124. tb->pprev = &head->chain;
  125. }
  126. return tb;
  127. }
  128. /* Caller must disable local BH processing. */
  129. static __inline__ void __tcp_inherit_port(struct sock *sk, struct sock *child)
  130. {
  131. struct tcp_bind_hashbucket *head = &tcp_bhash[tcp_bhashfn(child->num)];
  132. struct tcp_bind_bucket *tb;
  133. spin_lock(&head->lock);
  134. tb = (struct tcp_bind_bucket *)sk->prev;
  135. if ((child->bind_next = tb->owners) != NULL)
  136. tb->owners->bind_pprev = &child->bind_next;
  137. tb->owners = child;
  138. child->bind_pprev = &tb->owners;
  139. child->prev = (struct sock *) tb;
  140. spin_unlock(&head->lock);
  141. }
  142. __inline__ void tcp_inherit_port(struct sock *sk, struct sock *child)
  143. {
  144. local_bh_disable();
  145. __tcp_inherit_port(sk, child);
  146. local_bh_enable();
  147. }
  148. static inline void tcp_bind_hash(struct sock *sk, struct tcp_bind_bucket *tb, unsigned short snum)
  149. {
  150. sk->num = snum;
  151. if ((sk->bind_next = tb->owners) != NULL)
  152. tb->owners->bind_pprev = &sk->bind_next;
  153. tb->owners = sk;
  154. sk->bind_pprev = &tb->owners;
  155. sk->prev = (struct sock *) tb;
  156. }
  157. static inline int tcp_bind_conflict(struct sock *sk, struct tcp_bind_bucket *tb)
  158. {
  159. struct sock *sk2 = tb->owners;
  160. int sk_reuse = sk->reuse;
  161. for( ; sk2 != NULL; sk2 = sk2->bind_next) {
  162. if (sk != sk2 &&
  163.     sk2->reuse <= 1 &&
  164.     sk->bound_dev_if == sk2->bound_dev_if) {
  165. if (!sk_reuse ||
  166.     !sk2->reuse ||
  167.     sk2->state == TCP_LISTEN) {
  168. if (!sk2->rcv_saddr ||
  169.     !sk->rcv_saddr ||
  170.     (sk2->rcv_saddr == sk->rcv_saddr))
  171. break;
  172. }
  173. }
  174. }
  175. return sk2 != NULL;
  176. }
  177. /* Obtain a reference to a local port for the given sock,
  178.  * if snum is zero it means select any available local port.
  179.  */
  180. static int tcp_v4_get_port(struct sock *sk, unsigned short snum)
  181. {
  182. struct tcp_bind_hashbucket *head;
  183. struct tcp_bind_bucket *tb;
  184. int ret;
  185. local_bh_disable();
  186. if (snum == 0) {
  187. int low = sysctl_local_port_range[0];
  188. int high = sysctl_local_port_range[1];
  189. int remaining = (high - low) + 1;
  190. int rover;
  191. spin_lock(&tcp_portalloc_lock);
  192. rover = tcp_port_rover;
  193. do { rover++;
  194. if ((rover < low) || (rover > high))
  195. rover = low;
  196. head = &tcp_bhash[tcp_bhashfn(rover)];
  197. spin_lock(&head->lock);
  198. for (tb = head->chain; tb; tb = tb->next)
  199. if (tb->port == rover)
  200. goto next;
  201. break;
  202. next:
  203. spin_unlock(&head->lock);
  204. } while (--remaining > 0);
  205. tcp_port_rover = rover;
  206. spin_unlock(&tcp_portalloc_lock);
  207. /* Exhausted local port range during search? */
  208. ret = 1;
  209. if (remaining <= 0)
  210. goto fail;
  211. /* OK, here is the one we will use.  HEAD is
  212.  * non-NULL and we hold it's mutex.
  213.  */
  214. snum = rover;
  215. tb = NULL;
  216. } else {
  217. head = &tcp_bhash[tcp_bhashfn(snum)];
  218. spin_lock(&head->lock);
  219. for (tb = head->chain; tb != NULL; tb = tb->next)
  220. if (tb->port == snum)
  221. break;
  222. }
  223. if (tb != NULL && tb->owners != NULL) {
  224. if (sk->reuse > 1)
  225. goto success;
  226. if (tb->fastreuse > 0 && sk->reuse != 0 && sk->state != TCP_LISTEN) {
  227. goto success;
  228. } else {
  229. ret = 1;
  230. if (tcp_bind_conflict(sk, tb))
  231. goto fail_unlock;
  232. }
  233. }
  234. ret = 1;
  235. if (tb == NULL &&
  236.     (tb = tcp_bucket_create(head, snum)) == NULL)
  237. goto fail_unlock;
  238. if (tb->owners == NULL) {
  239. if (sk->reuse && sk->state != TCP_LISTEN)
  240. tb->fastreuse = 1;
  241. else
  242. tb->fastreuse = 0;
  243. } else if (tb->fastreuse &&
  244.    ((sk->reuse == 0) || (sk->state == TCP_LISTEN)))
  245. tb->fastreuse = 0;
  246. success:
  247. if (sk->prev == NULL)
  248. tcp_bind_hash(sk, tb, snum);
  249. BUG_TRAP(sk->prev == (struct sock *) tb);
  250.   ret = 0;
  251. fail_unlock:
  252. spin_unlock(&head->lock);
  253. fail:
  254. local_bh_enable();
  255. return ret;
  256. }
  257. /* Get rid of any references to a local port held by the
  258.  * given sock.
  259.  */
  260. __inline__ void __tcp_put_port(struct sock *sk)
  261. {
  262. struct tcp_bind_hashbucket *head = &tcp_bhash[tcp_bhashfn(sk->num)];
  263. struct tcp_bind_bucket *tb;
  264. spin_lock(&head->lock);
  265. tb = (struct tcp_bind_bucket *) sk->prev;
  266. if (sk->bind_next)
  267. sk->bind_next->bind_pprev = sk->bind_pprev;
  268. *(sk->bind_pprev) = sk->bind_next;
  269. sk->prev = NULL;
  270. sk->num = 0;
  271. if (tb->owners == NULL) {
  272. if (tb->next)
  273. tb->next->pprev = tb->pprev;
  274. *(tb->pprev) = tb->next;
  275. kmem_cache_free(tcp_bucket_cachep, tb);
  276. }
  277. spin_unlock(&head->lock);
  278. }
  279. void tcp_put_port(struct sock *sk)
  280. {
  281. local_bh_disable();
  282. __tcp_put_port(sk);
  283. local_bh_enable();
  284. }
  285. /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it can be very bad on SMP.
  286.  * Look, when several writers sleep and reader wakes them up, all but one
  287.  * immediately hit write lock and grab all the cpus. Exclusive sleep solves
  288.  * this, _but_ remember, it adds useless work on UP machines (wake up each
  289.  * exclusive lock release). It should be ifdefed really.
  290.  */
  291. void tcp_listen_wlock(void)
  292. {
  293. write_lock(&tcp_lhash_lock);
  294. if (atomic_read(&tcp_lhash_users)) {
  295. DECLARE_WAITQUEUE(wait, current);
  296. add_wait_queue_exclusive(&tcp_lhash_wait, &wait);
  297. for (;;) {
  298. set_current_state(TASK_UNINTERRUPTIBLE);
  299. if (atomic_read(&tcp_lhash_users) == 0)
  300. break;
  301. write_unlock_bh(&tcp_lhash_lock);
  302. schedule();
  303. write_lock_bh(&tcp_lhash_lock);
  304. }
  305. __set_current_state(TASK_RUNNING);
  306. remove_wait_queue(&tcp_lhash_wait, &wait);
  307. }
  308. }
  309. static __inline__ void __tcp_v4_hash(struct sock *sk, const int listen_possible)
  310. {
  311. struct sock **skp;
  312. rwlock_t *lock;
  313. BUG_TRAP(sk->pprev==NULL);
  314. if(listen_possible && sk->state == TCP_LISTEN) {
  315. skp = &tcp_listening_hash[tcp_sk_listen_hashfn(sk)];
  316. lock = &tcp_lhash_lock;
  317. tcp_listen_wlock();
  318. } else {
  319. skp = &tcp_ehash[(sk->hashent = tcp_sk_hashfn(sk))].chain;
  320. lock = &tcp_ehash[sk->hashent].lock;
  321. write_lock(lock);
  322. }
  323. if((sk->next = *skp) != NULL)
  324. (*skp)->pprev = &sk->next;
  325. *skp = sk;
  326. sk->pprev = skp;
  327. sock_prot_inc_use(sk->prot);
  328. write_unlock(lock);
  329. if (listen_possible && sk->state == TCP_LISTEN)
  330. wake_up(&tcp_lhash_wait);
  331. }
  332. static void tcp_v4_hash(struct sock *sk)
  333. {
  334. if (sk->state != TCP_CLOSE) {
  335. local_bh_disable();
  336. __tcp_v4_hash(sk, 1);
  337. local_bh_enable();
  338. }
  339. }
  340. void tcp_unhash(struct sock *sk)
  341. {
  342. rwlock_t *lock;
  343. if (!sk->pprev)
  344. goto ende;
  345. if (sk->state == TCP_LISTEN) {
  346. local_bh_disable();
  347. tcp_listen_wlock();
  348. lock = &tcp_lhash_lock;
  349. } else {
  350. struct tcp_ehash_bucket *head = &tcp_ehash[sk->hashent];
  351. lock = &head->lock;
  352. write_lock_bh(&head->lock);
  353. }
  354. if(sk->pprev) {
  355. if(sk->next)
  356. sk->next->pprev = sk->pprev;
  357. *sk->pprev = sk->next;
  358. sk->pprev = NULL;
  359. sock_prot_dec_use(sk->prot);
  360. }
  361. write_unlock_bh(lock);
  362.  ende:
  363. if (sk->state == TCP_LISTEN)
  364. wake_up(&tcp_lhash_wait);
  365. }
  366. /* Don't inline this cruft.  Here are some nice properties to
  367.  * exploit here.  The BSD API does not allow a listening TCP
  368.  * to specify the remote port nor the remote address for the
  369.  * connection.  So always assume those are both wildcarded
  370.  * during the search since they can never be otherwise.
  371.  */
  372. static struct sock *__tcp_v4_lookup_listener(struct sock *sk, u32 daddr, unsigned short hnum, int dif)
  373. {
  374. struct sock *result = NULL;
  375. int score, hiscore;
  376. hiscore=0;
  377. for(; sk; sk = sk->next) {
  378. if(sk->num == hnum) {
  379. __u32 rcv_saddr = sk->rcv_saddr;
  380. score = 1;
  381. if(rcv_saddr) {
  382. if (rcv_saddr != daddr)
  383. continue;
  384. score++;
  385. }
  386. if (sk->bound_dev_if) {
  387. if (sk->bound_dev_if != dif)
  388. continue;
  389. score++;
  390. }
  391. if (score == 3)
  392. return sk;
  393. if (score > hiscore) {
  394. hiscore = score;
  395. result = sk;
  396. }
  397. }
  398. }
  399. return result;
  400. }
  401. /* Optimize the common listener case. */
  402. __inline__ struct sock *tcp_v4_lookup_listener(u32 daddr, unsigned short hnum, int dif)
  403. {
  404. struct sock *sk;
  405. read_lock(&tcp_lhash_lock);
  406. sk = tcp_listening_hash[tcp_lhashfn(hnum)];
  407. if (sk) {
  408. if (sk->num == hnum &&
  409.     sk->next == NULL &&
  410.     (!sk->rcv_saddr || sk->rcv_saddr == daddr) &&
  411.     !sk->bound_dev_if)
  412. goto sherry_cache;
  413. sk = __tcp_v4_lookup_listener(sk, daddr, hnum, dif);
  414. }
  415. if (sk) {
  416. sherry_cache:
  417. sock_hold(sk);
  418. }
  419. read_unlock(&tcp_lhash_lock);
  420. return sk;
  421. }
  422. /* Sockets in TCP_CLOSE state are _always_ taken out of the hash, so
  423.  * we need not check it for TCP lookups anymore, thanks Alexey. -DaveM
  424.  *
  425.  * Local BH must be disabled here.
  426.  */
  427. static inline struct sock *__tcp_v4_lookup_established(u32 saddr, u16 sport,
  428.        u32 daddr, u16 hnum, int dif)
  429. {
  430. struct tcp_ehash_bucket *head;
  431. TCP_V4_ADDR_COOKIE(acookie, saddr, daddr)
  432. __u32 ports = TCP_COMBINED_PORTS(sport, hnum);
  433. struct sock *sk;
  434. int hash;
  435. /* Optimize here for direct hit, only listening connections can
  436.  * have wildcards anyways.
  437.  */
  438. hash = tcp_hashfn(daddr, hnum, saddr, sport);
  439. head = &tcp_ehash[hash];
  440. read_lock(&head->lock);
  441. for(sk = head->chain; sk; sk = sk->next) {
  442. if(TCP_IPV4_MATCH(sk, acookie, saddr, daddr, ports, dif))
  443. goto hit; /* You sunk my battleship! */
  444. }
  445. /* Must check for a TIME_WAIT'er before going to listener hash. */
  446. for(sk = (head + tcp_ehash_size)->chain; sk; sk = sk->next)
  447. if(TCP_IPV4_MATCH(sk, acookie, saddr, daddr, ports, dif))
  448. goto hit;
  449. read_unlock(&head->lock);
  450. return NULL;
  451. hit:
  452. sock_hold(sk);
  453. read_unlock(&head->lock);
  454. return sk;
  455. }
  456. static inline struct sock *__tcp_v4_lookup(u32 saddr, u16 sport,
  457.    u32 daddr, u16 hnum, int dif)
  458. {
  459. struct sock *sk;
  460. sk = __tcp_v4_lookup_established(saddr, sport, daddr, hnum, dif);
  461. if (sk)
  462. return sk;
  463. return tcp_v4_lookup_listener(daddr, hnum, dif);
  464. }
  465. __inline__ struct sock *tcp_v4_lookup(u32 saddr, u16 sport, u32 daddr, u16 dport, int dif)
  466. {
  467. struct sock *sk;
  468. local_bh_disable();
  469. sk = __tcp_v4_lookup(saddr, sport, daddr, ntohs(dport), dif);
  470. local_bh_enable();
  471. return sk;
  472. }
  473. static inline __u32 tcp_v4_init_sequence(struct sock *sk, struct sk_buff *skb)
  474. {
  475. return secure_tcp_sequence_number(skb->nh.iph->daddr,
  476.   skb->nh.iph->saddr,
  477.   skb->h.th->dest,
  478.   skb->h.th->source);
  479. }
  480. /* called with local bh disabled */
  481. static int __tcp_v4_check_established(struct sock *sk, __u16 lport,
  482.       struct tcp_tw_bucket **twp)
  483. {
  484. u32 daddr = sk->rcv_saddr;
  485. u32 saddr = sk->daddr;
  486. int dif = sk->bound_dev_if;
  487. TCP_V4_ADDR_COOKIE(acookie, saddr, daddr)
  488. __u32 ports = TCP_COMBINED_PORTS(sk->dport, lport);
  489. int hash = tcp_hashfn(daddr, lport, saddr, sk->dport);
  490. struct tcp_ehash_bucket *head = &tcp_ehash[hash];
  491. struct sock *sk2, **skp;
  492. struct tcp_tw_bucket *tw;
  493. write_lock(&head->lock);
  494. /* Check TIME-WAIT sockets first. */
  495. for(skp = &(head + tcp_ehash_size)->chain; (sk2=*skp) != NULL;
  496.     skp = &sk2->next) {
  497. tw = (struct tcp_tw_bucket*)sk2;
  498. if(TCP_IPV4_MATCH(sk2, acookie, saddr, daddr, ports, dif)) {
  499. struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
  500. /* With PAWS, it is safe from the viewpoint
  501.    of data integrity. Even without PAWS it
  502.    is safe provided sequence spaces do not
  503.    overlap i.e. at data rates <= 80Mbit/sec.
  504.    Actually, the idea is close to VJ's one,
  505.    only timestamp cache is held not per host,
  506.    but per port pair and TW bucket is used
  507.    as state holder.
  508.    If TW bucket has been already destroyed we
  509.    fall back to VJ's scheme and use initial
  510.    timestamp retrieved from peer table.
  511.  */
  512. if (tw->ts_recent_stamp &&
  513.     (!twp || (sysctl_tcp_tw_reuse &&
  514.       xtime.tv_sec - tw->ts_recent_stamp > 1))) {
  515. if ((tp->write_seq = tw->snd_nxt+65535+2) == 0)
  516. tp->write_seq = 1;
  517. tp->ts_recent = tw->ts_recent;
  518. tp->ts_recent_stamp = tw->ts_recent_stamp;
  519. sock_hold(sk2);
  520. skp = &head->chain;
  521. goto unique;
  522. } else
  523. goto not_unique;
  524. }
  525. }
  526. tw = NULL;
  527. /* And established part... */
  528. for(skp = &head->chain; (sk2=*skp)!=NULL; skp = &sk2->next) {
  529. if(TCP_IPV4_MATCH(sk2, acookie, saddr, daddr, ports, dif))
  530. goto not_unique;
  531. }
  532. unique:
  533. /* Must record num and sport now. Otherwise we will see
  534.  * in hash table socket with a funny identity. */
  535. sk->num = lport;
  536. sk->sport = htons(lport);
  537. BUG_TRAP(sk->pprev==NULL);
  538. if ((sk->next = *skp) != NULL)
  539. (*skp)->pprev = &sk->next;
  540. *skp = sk;
  541. sk->pprev = skp;
  542. sk->hashent = hash;
  543. sock_prot_inc_use(sk->prot);
  544. write_unlock(&head->lock);
  545. if (twp) {
  546. *twp = tw;
  547. NET_INC_STATS_BH(TimeWaitRecycled);
  548. } else if (tw) {
  549. /* Silly. Should hash-dance instead... */
  550. tcp_tw_deschedule(tw);
  551. tcp_timewait_kill(tw);
  552. NET_INC_STATS_BH(TimeWaitRecycled);
  553. tcp_tw_put(tw);
  554. }
  555. return 0;
  556. not_unique:
  557. write_unlock(&head->lock);
  558. return -EADDRNOTAVAIL;
  559. }
  560. /*
  561.  * Bind a port for a connect operation and hash it.
  562.  */
  563. static int tcp_v4_hash_connect(struct sock *sk)
  564. {
  565. unsigned short snum = sk->num;
  566. struct tcp_bind_hashbucket *head;
  567. struct tcp_bind_bucket *tb;
  568. if (snum == 0) {
  569. int rover;
  570. int low = sysctl_local_port_range[0];
  571. int high = sysctl_local_port_range[1];
  572. int remaining = (high - low) + 1;
  573. struct tcp_tw_bucket *tw = NULL;
  574. local_bh_disable();
  575. /* TODO. Actually it is not so bad idea to remove
  576.  * tcp_portalloc_lock before next submission to Linus.
  577.  * As soon as we touch this place at all it is time to think.
  578.  *
  579.  * Now it protects single _advisory_ variable tcp_port_rover,
  580.  * hence it is mostly useless.
  581.  * Code will work nicely if we just delete it, but
  582.  * I am afraid in contented case it will work not better or
  583.  * even worse: another cpu just will hit the same bucket
  584.  * and spin there.
  585.  * So some cpu salt could remove both contention and
  586.  * memory pingpong. Any ideas how to do this in a nice way?
  587.  */
  588. spin_lock(&tcp_portalloc_lock);
  589. rover = tcp_port_rover;
  590. do {
  591. rover++;
  592. if ((rover < low) || (rover > high))
  593. rover = low;
  594. head = &tcp_bhash[tcp_bhashfn(rover)];
  595. spin_lock(&head->lock);
  596. /* Does not bother with rcv_saddr checks,
  597.  * because the established check is already
  598.  * unique enough.
  599.  */
  600. for (tb = head->chain; tb; tb = tb->next) {
  601. if (tb->port == rover) {
  602. BUG_TRAP(tb->owners != NULL);
  603. if (tb->fastreuse >= 0)
  604. goto next_port;
  605. if (!__tcp_v4_check_established(sk, rover, &tw))
  606. goto ok;
  607. goto next_port;
  608. }
  609. }
  610. tb = tcp_bucket_create(head, rover);
  611. if (!tb) {
  612. spin_unlock(&head->lock);
  613. break;
  614. }
  615. tb->fastreuse = -1;
  616. goto ok;
  617. next_port:
  618. spin_unlock(&head->lock);
  619. } while (--remaining > 0);
  620. tcp_port_rover = rover;
  621. spin_unlock(&tcp_portalloc_lock);
  622. local_bh_enable();
  623. return -EADDRNOTAVAIL;
  624. ok:
  625. /* All locks still held and bhs disabled */
  626. tcp_port_rover = rover;
  627. spin_unlock(&tcp_portalloc_lock);
  628. tcp_bind_hash(sk, tb, rover);
  629. if (!sk->pprev) {
  630. sk->sport = htons(rover);
  631. __tcp_v4_hash(sk, 0);
  632. }
  633. spin_unlock(&head->lock);
  634. if (tw) {
  635. tcp_tw_deschedule(tw);
  636. tcp_timewait_kill(tw);
  637. tcp_tw_put(tw);
  638. }
  639. local_bh_enable();
  640. return 0;
  641. }
  642. head  = &tcp_bhash[tcp_bhashfn(snum)];
  643. tb  = (struct tcp_bind_bucket *)sk->prev;
  644. spin_lock_bh(&head->lock);
  645. if (tb->owners == sk && sk->bind_next == NULL) {
  646. __tcp_v4_hash(sk, 0);
  647. spin_unlock_bh(&head->lock);
  648. return 0;
  649. } else {
  650. int ret;
  651. spin_unlock(&head->lock);
  652. /* No definite answer... Walk to established hash table */
  653. ret = __tcp_v4_check_established(sk, snum, NULL);
  654. local_bh_enable();
  655. return ret;
  656. }
  657. }
  658. /* This will initiate an outgoing connection. */
  659. int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
  660. {
  661. struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
  662. struct sockaddr_in *usin = (struct sockaddr_in *) uaddr;
  663. struct rtable *rt;
  664. u32 daddr, nexthop;
  665. int tmp;
  666. int err;
  667. if (addr_len < sizeof(struct sockaddr_in))
  668. return(-EINVAL);
  669. if (usin->sin_family != AF_INET)
  670. return(-EAFNOSUPPORT);
  671. nexthop = daddr = usin->sin_addr.s_addr;
  672. if (sk->protinfo.af_inet.opt && sk->protinfo.af_inet.opt->srr) {
  673. if (daddr == 0)
  674. return -EINVAL;
  675. nexthop = sk->protinfo.af_inet.opt->faddr;
  676. }
  677. tmp = ip_route_connect(&rt, nexthop, sk->saddr,
  678.        RT_CONN_FLAGS(sk), sk->bound_dev_if);
  679. if (tmp < 0)
  680. return tmp;
  681. if (rt->rt_flags&(RTCF_MULTICAST|RTCF_BROADCAST)) {
  682. ip_rt_put(rt);
  683. return -ENETUNREACH;
  684. }
  685. __sk_dst_set(sk, &rt->u.dst);
  686. sk->route_caps = rt->u.dst.dev->features;
  687. if (!sk->protinfo.af_inet.opt || !sk->protinfo.af_inet.opt->srr)
  688. daddr = rt->rt_dst;
  689. if (!sk->saddr)
  690. sk->saddr = rt->rt_src;
  691. sk->rcv_saddr = sk->saddr;
  692. if (tp->ts_recent_stamp && sk->daddr != daddr) {
  693. /* Reset inherited state */
  694. tp->ts_recent = 0;
  695. tp->ts_recent_stamp = 0;
  696. tp->write_seq = 0;
  697. }
  698. if (sysctl_tcp_tw_recycle &&
  699.     !tp->ts_recent_stamp &&
  700.     rt->rt_dst == daddr) {
  701. struct inet_peer *peer = rt_get_peer(rt);
  702. /* VJ's idea. We save last timestamp seen from
  703.  * the destination in peer table, when entering state TIME-WAIT
  704.  * and initialize ts_recent from it, when trying new connection.
  705.  */
  706. if (peer && peer->tcp_ts_stamp + TCP_PAWS_MSL >= xtime.tv_sec) {
  707. tp->ts_recent_stamp = peer->tcp_ts_stamp;
  708. tp->ts_recent = peer->tcp_ts;
  709. }
  710. }
  711. sk->dport = usin->sin_port;
  712. sk->daddr = daddr;
  713. tp->ext_header_len = 0;
  714. if (sk->protinfo.af_inet.opt)
  715. tp->ext_header_len = sk->protinfo.af_inet.opt->optlen;
  716. tp->mss_clamp = 536;
  717. /* Socket identity is still unknown (sport may be zero).
  718.  * However we set state to SYN-SENT and not releasing socket
  719.  * lock select source port, enter ourselves into the hash tables and
  720.  * complete initalization after this.
  721.  */
  722. tcp_set_state(sk, TCP_SYN_SENT);
  723. err = tcp_v4_hash_connect(sk);
  724. if (err)
  725. goto failure;
  726. if (!tp->write_seq)
  727. tp->write_seq = secure_tcp_sequence_number(sk->saddr, sk->daddr,
  728.    sk->sport, usin->sin_port);
  729. sk->protinfo.af_inet.id = tp->write_seq^jiffies;
  730. err = tcp_connect(sk);
  731. if (err)
  732. goto failure;
  733. return 0;
  734. failure:
  735. tcp_set_state(sk, TCP_CLOSE);
  736. __sk_dst_reset(sk);
  737. sk->route_caps = 0;
  738. sk->dport = 0;
  739. return err;
  740. }
  741. static __inline__ int tcp_v4_iif(struct sk_buff *skb)
  742. {
  743. return ((struct rtable*)skb->dst)->rt_iif;
  744. }
  745. static __inline__ unsigned tcp_v4_synq_hash(u32 raddr, u16 rport)
  746. {
  747. unsigned h = raddr ^ rport;
  748. h ^= h>>16;
  749. h ^= h>>8;
  750. return h&(TCP_SYNQ_HSIZE-1);
  751. }
  752. static struct open_request *tcp_v4_search_req(struct tcp_opt *tp, 
  753.       struct open_request ***prevp,
  754.       __u16 rport,
  755.       __u32 raddr, __u32 laddr)
  756. {
  757. struct tcp_listen_opt *lopt = tp->listen_opt;
  758. struct open_request *req, **prev;  
  759. for (prev = &lopt->syn_table[tcp_v4_synq_hash(raddr, rport)];
  760.      (req = *prev) != NULL;
  761.      prev = &req->dl_next) {
  762. if (req->rmt_port == rport &&
  763.     req->af.v4_req.rmt_addr == raddr &&
  764.     req->af.v4_req.loc_addr == laddr &&
  765.     TCP_INET_FAMILY(req->class->family)) {
  766. BUG_TRAP(req->sk == NULL);
  767. *prevp = prev;
  768. return req; 
  769. }
  770. }
  771. return NULL;
  772. }
  773. static void tcp_v4_synq_add(struct sock *sk, struct open_request *req)
  774. {
  775. struct tcp_opt *tp = &sk->tp_pinfo.af_tcp;
  776. struct tcp_listen_opt *lopt = tp->listen_opt;
  777. unsigned h = tcp_v4_synq_hash(req->af.v4_req.rmt_addr, req->rmt_port);
  778. req->expires = jiffies + TCP_TIMEOUT_INIT;
  779. req->retrans = 0;
  780. req->sk = NULL;
  781. req->dl_next = lopt->syn_table[h];
  782. write_lock(&tp->syn_wait_lock);
  783. lopt->syn_table[h] = req;
  784. write_unlock(&tp->syn_wait_lock);
  785. tcp_synq_added(sk);
  786. }
  787. /* 
  788.  * This routine does path mtu discovery as defined in RFC1191.
  789.  */
  790. static inline void do_pmtu_discovery(struct sock *sk, struct iphdr *ip, unsigned mtu)
  791. {
  792. struct dst_entry *dst;
  793. struct tcp_opt *tp = &sk->tp_pinfo.af_tcp;
  794. /* We are not interested in TCP_LISTEN and open_requests (SYN-ACKs
  795.  * send out by Linux are always <576bytes so they should go through
  796.  * unfragmented).
  797.  */
  798. if (sk->state == TCP_LISTEN)
  799. return; 
  800. /* We don't check in the destentry if pmtu discovery is forbidden
  801.  * on this route. We just assume that no packet_to_big packets
  802.  * are send back when pmtu discovery is not active.
  803.        * There is a small race when the user changes this flag in the
  804.  * route, but I think that's acceptable.
  805.  */
  806. if ((dst = __sk_dst_check(sk, 0)) == NULL)
  807. return;
  808. ip_rt_update_pmtu(dst, mtu);
  809. /* Something is about to be wrong... Remember soft error
  810.  * for the case, if this connection will not able to recover.
  811.  */
  812. if (mtu < dst->pmtu && ip_dont_fragment(sk, dst))
  813. sk->err_soft = EMSGSIZE;
  814. if (sk->protinfo.af_inet.pmtudisc != IP_PMTUDISC_DONT &&
  815.     tp->pmtu_cookie > dst->pmtu) {
  816. tcp_sync_mss(sk, dst->pmtu);
  817. /* Resend the TCP packet because it's  
  818.  * clear that the old packet has been
  819.  * dropped. This is the new "fast" path mtu
  820.  * discovery.
  821.  */
  822. tcp_simple_retransmit(sk);
  823. } /* else let the usual retransmit timer handle it */
  824. }
  825. /*
  826.  * This routine is called by the ICMP module when it gets some
  827.  * sort of error condition.  If err < 0 then the socket should
  828.  * be closed and the error returned to the user.  If err > 0
  829.  * it's just the icmp type << 8 | icmp code.  After adjustment
  830.  * header points to the first 8 bytes of the tcp header.  We need
  831.  * to find the appropriate port.
  832.  *
  833.  * The locking strategy used here is very "optimistic". When
  834.  * someone else accesses the socket the ICMP is just dropped
  835.  * and for some paths there is no check at all.
  836.  * A more general error queue to queue errors for later handling
  837.  * is probably better.
  838.  *
  839.  */
  840. void tcp_v4_err(struct sk_buff *skb, u32 info)
  841. {
  842. struct iphdr *iph = (struct iphdr*)skb->data;
  843. struct tcphdr *th = (struct tcphdr*)(skb->data+(iph->ihl<<2));
  844. struct tcp_opt *tp;
  845. int type = skb->h.icmph->type;
  846. int code = skb->h.icmph->code;
  847. struct sock *sk;
  848. __u32 seq;
  849. int err;
  850. if (skb->len < (iph->ihl << 2) + 8) {
  851. ICMP_INC_STATS_BH(IcmpInErrors); 
  852. return;
  853. }
  854. sk = tcp_v4_lookup(iph->daddr, th->dest, iph->saddr, th->source, tcp_v4_iif(skb));
  855. if (sk == NULL) {
  856. ICMP_INC_STATS_BH(IcmpInErrors);
  857. return;
  858. }
  859. if (sk->state == TCP_TIME_WAIT) {
  860. tcp_tw_put((struct tcp_tw_bucket*)sk);
  861. return;
  862. }
  863. bh_lock_sock(sk);
  864. /* If too many ICMPs get dropped on busy
  865.  * servers this needs to be solved differently.
  866.  */
  867. if (sk->lock.users != 0)
  868. NET_INC_STATS_BH(LockDroppedIcmps);
  869. if (sk->state == TCP_CLOSE)
  870. goto out;
  871. tp = &sk->tp_pinfo.af_tcp;
  872. seq = ntohl(th->seq);
  873. if (sk->state != TCP_LISTEN && !between(seq, tp->snd_una, tp->snd_nxt)) {
  874. NET_INC_STATS(OutOfWindowIcmps);
  875. goto out;
  876. }
  877. switch (type) {
  878. case ICMP_SOURCE_QUENCH:
  879. /* This is deprecated, but if someone generated it,
  880.  * we have no reasons to ignore it.
  881.  */
  882. if (sk->lock.users == 0)
  883. tcp_enter_cwr(tp);
  884. goto out;
  885. case ICMP_PARAMETERPROB:
  886. err = EPROTO;
  887. break; 
  888. case ICMP_DEST_UNREACH:
  889. if (code > NR_ICMP_UNREACH)
  890. goto out;
  891. if (code == ICMP_FRAG_NEEDED) { /* PMTU discovery (RFC1191) */
  892. if (sk->lock.users == 0)
  893. do_pmtu_discovery(sk, iph, info);
  894. goto out;
  895. }
  896. err = icmp_err_convert[code].errno;
  897. break;
  898. case ICMP_TIME_EXCEEDED:
  899. err = EHOSTUNREACH;
  900. break;
  901. default:
  902. goto out;
  903. }
  904. switch (sk->state) {
  905. struct open_request *req, **prev;
  906. case TCP_LISTEN:
  907. if (sk->lock.users != 0)
  908. goto out;
  909. req = tcp_v4_search_req(tp, &prev,
  910. th->dest,
  911. iph->daddr, iph->saddr); 
  912. if (!req)
  913. goto out;
  914. /* ICMPs are not backlogged, hence we cannot get
  915.    an established socket here.
  916.  */
  917. BUG_TRAP(req->sk == NULL);
  918. if (seq != req->snt_isn) {
  919. NET_INC_STATS_BH(OutOfWindowIcmps);
  920. goto out;
  921. }
  922. /* 
  923.  * Still in SYN_RECV, just remove it silently.
  924.  * There is no good way to pass the error to the newly
  925.  * created socket, and POSIX does not want network
  926.  * errors returned from accept(). 
  927.  */ 
  928. tcp_synq_drop(sk, req, prev);
  929. goto out;
  930. case TCP_SYN_SENT:
  931. case TCP_SYN_RECV:  /* Cannot happen.
  932.        It can f.e. if SYNs crossed.
  933.      */ 
  934. if (sk->lock.users == 0) {
  935. TCP_INC_STATS_BH(TcpAttemptFails);
  936. sk->err = err;
  937. sk->error_report(sk);
  938. tcp_done(sk);
  939. } else {
  940. sk->err_soft = err;
  941. }
  942. goto out;
  943. }
  944. /* If we've already connected we will keep trying
  945.  * until we time out, or the user gives up.
  946.  *
  947.  * rfc1122 4.2.3.9 allows to consider as hard errors
  948.  * only PROTO_UNREACH and PORT_UNREACH (well, FRAG_FAILED too,
  949.  * but it is obsoleted by pmtu discovery).
  950.  *
  951.  * Note, that in modern internet, where routing is unreliable
  952.  * and in each dark corner broken firewalls sit, sending random
  953.  * errors ordered by their masters even this two messages finally lose
  954.  * their original sense (even Linux sends invalid PORT_UNREACHs)
  955.  *
  956.  * Now we are in compliance with RFCs.
  957.  * --ANK (980905)
  958.  */
  959. if (sk->lock.users == 0 && sk->protinfo.af_inet.recverr) {
  960. sk->err = err;
  961. sk->error_report(sk);
  962. } else { /* Only an error on timeout */
  963. sk->err_soft = err;
  964. }
  965. out:
  966. bh_unlock_sock(sk);
  967. sock_put(sk);
  968. }
  969. /* This routine computes an IPv4 TCP checksum. */
  970. void tcp_v4_send_check(struct sock *sk, struct tcphdr *th, int len, 
  971.        struct sk_buff *skb)
  972. {
  973. if (skb->ip_summed == CHECKSUM_HW) {
  974. th->check = ~tcp_v4_check(th, len, sk->saddr, sk->daddr, 0);
  975. skb->csum = offsetof(struct tcphdr, check);
  976. } else {
  977. th->check = tcp_v4_check(th, len, sk->saddr, sk->daddr,
  978.  csum_partial((char *)th, th->doff<<2, skb->csum));
  979. }
  980. }
  981. /*
  982.  * This routine will send an RST to the other tcp.
  983.  *
  984.  * Someone asks: why I NEVER use socket parameters (TOS, TTL etc.)
  985.  *       for reset.
  986.  * Answer: if a packet caused RST, it is not for a socket
  987.  * existing in our system, if it is matched to a socket,
  988.  * it is just duplicate segment or bug in other side's TCP.
  989.  * So that we build reply only basing on parameters
  990.  * arrived with segment.
  991.  * Exception: precedence violation. We do not implement it in any case.
  992.  */
  993. static void tcp_v4_send_reset(struct sk_buff *skb)
  994. {
  995. struct tcphdr *th = skb->h.th;
  996. struct tcphdr rth;
  997. struct ip_reply_arg arg;
  998. /* Never send a reset in response to a reset. */
  999. if (th->rst)
  1000. return;
  1001. if (((struct rtable*)skb->dst)->rt_type != RTN_LOCAL)
  1002. return;
  1003. /* Swap the send and the receive. */
  1004. memset(&rth, 0, sizeof(struct tcphdr)); 
  1005. rth.dest = th->source;
  1006. rth.source = th->dest; 
  1007. rth.doff = sizeof(struct tcphdr)/4;
  1008. rth.rst = 1;
  1009. if (th->ack) {
  1010. rth.seq = th->ack_seq;
  1011. } else {
  1012. rth.ack = 1;
  1013. rth.ack_seq = htonl(ntohl(th->seq) + th->syn + th->fin
  1014.     + skb->len - (th->doff<<2));
  1015. }
  1016. memset(&arg, 0, sizeof arg); 
  1017. arg.iov[0].iov_base = (unsigned char *)&rth; 
  1018. arg.iov[0].iov_len  = sizeof rth;
  1019. arg.csum = csum_tcpudp_nofold(skb->nh.iph->daddr, 
  1020.       skb->nh.iph->saddr, /*XXX*/
  1021.       sizeof(struct tcphdr),
  1022.       IPPROTO_TCP,
  1023.       0); 
  1024. arg.n_iov = 1;
  1025. arg.csumoffset = offsetof(struct tcphdr, check) / 2; 
  1026. tcp_socket->sk->protinfo.af_inet.ttl = sysctl_ip_default_ttl;
  1027. ip_send_reply(tcp_socket->sk, skb, &arg, sizeof rth);
  1028. TCP_INC_STATS_BH(TcpOutSegs);
  1029. TCP_INC_STATS_BH(TcpOutRsts);
  1030. }
  1031. /* The code following below sending ACKs in SYN-RECV and TIME-WAIT states
  1032.    outside socket context is ugly, certainly. What can I do?
  1033.  */
  1034. static void tcp_v4_send_ack(struct sk_buff *skb, u32 seq, u32 ack, u32 win, u32 ts)
  1035. {
  1036. struct tcphdr *th = skb->h.th;
  1037. struct {
  1038. struct tcphdr th;
  1039. u32 tsopt[3];
  1040. } rep;
  1041. struct ip_reply_arg arg;
  1042. memset(&rep.th, 0, sizeof(struct tcphdr));
  1043. memset(&arg, 0, sizeof arg);
  1044. arg.iov[0].iov_base = (unsigned char *)&rep; 
  1045. arg.iov[0].iov_len  = sizeof(rep.th);
  1046. arg.n_iov = 1;
  1047. if (ts) {
  1048. rep.tsopt[0] = htonl((TCPOPT_NOP << 24) |
  1049.      (TCPOPT_NOP << 16) |
  1050.      (TCPOPT_TIMESTAMP << 8) |
  1051.      TCPOLEN_TIMESTAMP);
  1052. rep.tsopt[1] = htonl(tcp_time_stamp);
  1053. rep.tsopt[2] = htonl(ts);
  1054. arg.iov[0].iov_len = sizeof(rep);
  1055. }
  1056. /* Swap the send and the receive. */
  1057. rep.th.dest = th->source;
  1058. rep.th.source = th->dest; 
  1059. rep.th.doff = arg.iov[0].iov_len/4;
  1060. rep.th.seq = htonl(seq);
  1061. rep.th.ack_seq = htonl(ack);
  1062. rep.th.ack = 1;
  1063. rep.th.window = htons(win);
  1064. arg.csum = csum_tcpudp_nofold(skb->nh.iph->daddr, 
  1065.       skb->nh.iph->saddr, /*XXX*/
  1066.       arg.iov[0].iov_len,
  1067.       IPPROTO_TCP,
  1068.       0);
  1069. arg.csumoffset = offsetof(struct tcphdr, check) / 2; 
  1070. ip_send_reply(tcp_socket->sk, skb, &arg, arg.iov[0].iov_len);
  1071. TCP_INC_STATS_BH(TcpOutSegs);
  1072. }
  1073. static void tcp_v4_timewait_ack(struct sock *sk, struct sk_buff *skb)
  1074. {
  1075. struct tcp_tw_bucket *tw = (struct tcp_tw_bucket *)sk;
  1076. tcp_v4_send_ack(skb, tw->snd_nxt, tw->rcv_nxt,
  1077. tw->rcv_wnd>>tw->rcv_wscale, tw->ts_recent);
  1078. tcp_tw_put(tw);
  1079. }
  1080. static void tcp_v4_or_send_ack(struct sk_buff *skb, struct open_request *req)
  1081. {
  1082. tcp_v4_send_ack(skb, req->snt_isn+1, req->rcv_isn+1, req->rcv_wnd,
  1083. req->ts_recent);
  1084. }
  1085. static struct dst_entry* tcp_v4_route_req(struct sock *sk, struct open_request *req)
  1086. {
  1087. struct rtable *rt;
  1088. struct ip_options *opt;
  1089. opt = req->af.v4_req.opt;
  1090. if(ip_route_output(&rt, ((opt && opt->srr) ?
  1091.  opt->faddr :
  1092.  req->af.v4_req.rmt_addr),
  1093.    req->af.v4_req.loc_addr,
  1094.    RT_CONN_FLAGS(sk), sk->bound_dev_if)) {
  1095. IP_INC_STATS_BH(IpOutNoRoutes);
  1096. return NULL;
  1097. }
  1098. if (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway) {
  1099. ip_rt_put(rt);
  1100. IP_INC_STATS_BH(IpOutNoRoutes);
  1101. return NULL;
  1102. }
  1103. return &rt->u.dst;
  1104. }
  1105. /*
  1106.  * Send a SYN-ACK after having received an ACK. 
  1107.  * This still operates on a open_request only, not on a big
  1108.  * socket.
  1109.  */ 
  1110. static int tcp_v4_send_synack(struct sock *sk, struct open_request *req,
  1111.       struct dst_entry *dst)
  1112. {
  1113. int err = -1;
  1114. struct sk_buff * skb;
  1115. /* First, grab a route. */
  1116. if (dst == NULL &&
  1117.     (dst = tcp_v4_route_req(sk, req)) == NULL)
  1118. goto out;
  1119. skb = tcp_make_synack(sk, dst, req);
  1120. if (skb) {
  1121. struct tcphdr *th = skb->h.th;
  1122. th->check = tcp_v4_check(th, skb->len,
  1123.  req->af.v4_req.loc_addr, req->af.v4_req.rmt_addr,
  1124.  csum_partial((char *)th, skb->len, skb->csum));
  1125. err = ip_build_and_send_pkt(skb, sk, req->af.v4_req.loc_addr,
  1126.     req->af.v4_req.rmt_addr, req->af.v4_req.opt);
  1127. if (err == NET_XMIT_CN)
  1128. err = 0;
  1129. }
  1130. out:
  1131. dst_release(dst);
  1132. return err;
  1133. }
  1134. /*
  1135.  * IPv4 open_request destructor.
  1136.  */ 
  1137. static void tcp_v4_or_free(struct open_request *req)
  1138. {
  1139. if (req->af.v4_req.opt)
  1140. kfree(req->af.v4_req.opt);
  1141. }
  1142. static inline void syn_flood_warning(struct sk_buff *skb)
  1143. {
  1144. static unsigned long warntime;
  1145. if (jiffies - warntime > HZ*60) {
  1146. warntime = jiffies;
  1147. printk(KERN_INFO 
  1148.        "possible SYN flooding on port %d. Sending cookies.n",  
  1149.        ntohs(skb->h.th->dest));
  1150. }
  1151. }
  1152. /* 
  1153.  * Save and compile IPv4 options into the open_request if needed. 
  1154.  */
  1155. static inline struct ip_options * 
  1156. tcp_v4_save_options(struct sock *sk, struct sk_buff *skb)
  1157. {
  1158. struct ip_options *opt = &(IPCB(skb)->opt);
  1159. struct ip_options *dopt = NULL; 
  1160. if (opt && opt->optlen) {
  1161. int opt_size = optlength(opt); 
  1162. dopt = kmalloc(opt_size, GFP_ATOMIC);
  1163. if (dopt) {
  1164. if (ip_options_echo(dopt, skb)) {
  1165. kfree(dopt);
  1166. dopt = NULL;
  1167. }
  1168. }
  1169. }
  1170. return dopt;
  1171. }
  1172. /* 
  1173.  * Maximum number of SYN_RECV sockets in queue per LISTEN socket.
  1174.  * One SYN_RECV socket costs about 80bytes on a 32bit machine.
  1175.  * It would be better to replace it with a global counter for all sockets
  1176.  * but then some measure against one socket starving all other sockets
  1177.  * would be needed.
  1178.  *
  1179.  * It was 128 by default. Experiments with real servers show, that
  1180.  * it is absolutely not enough even at 100conn/sec. 256 cures most
  1181.  * of problems. This value is adjusted to 128 for very small machines
  1182.  * (<=32Mb of memory) and to 1024 on normal or better ones (>=256Mb).
  1183.  * Further increasing requires to change hash table size.
  1184.  */
  1185. int sysctl_max_syn_backlog = 256; 
  1186. struct or_calltable or_ipv4 = {
  1187. PF_INET,
  1188. tcp_v4_send_synack,
  1189. tcp_v4_or_send_ack,
  1190. tcp_v4_or_free,
  1191. tcp_v4_send_reset
  1192. };
  1193. int tcp_v4_conn_request(struct sock *sk, struct sk_buff *skb)
  1194. {
  1195. struct tcp_opt tp;
  1196. struct open_request *req;
  1197. __u32 saddr = skb->nh.iph->saddr;
  1198. __u32 daddr = skb->nh.iph->daddr;
  1199. __u32 isn = TCP_SKB_CB(skb)->when;
  1200. struct dst_entry *dst = NULL;
  1201. #ifdef CONFIG_SYN_COOKIES
  1202. int want_cookie = 0;
  1203. #else
  1204. #define want_cookie 0 /* Argh, why doesn't gcc optimize this :( */
  1205. #endif
  1206. /* Never answer to SYNs send to broadcast or multicast */
  1207. if (((struct rtable *)skb->dst)->rt_flags & 
  1208.     (RTCF_BROADCAST|RTCF_MULTICAST))
  1209. goto drop; 
  1210. /* TW buckets are converted to open requests without
  1211.  * limitations, they conserve resources and peer is
  1212.  * evidently real one.
  1213.  */
  1214. if (tcp_synq_is_full(sk) && !isn) {
  1215. #ifdef CONFIG_SYN_COOKIES
  1216. if (sysctl_tcp_syncookies) {
  1217. want_cookie = 1; 
  1218. } else
  1219. #endif
  1220. goto drop;
  1221. }
  1222. /* Accept backlog is full. If we have already queued enough
  1223.  * of warm entries in syn queue, drop request. It is better than
  1224.  * clogging syn queue with openreqs with exponentially increasing
  1225.  * timeout.
  1226.  */
  1227. if (tcp_acceptq_is_full(sk) && tcp_synq_young(sk) > 1)
  1228. goto drop;
  1229. req = tcp_openreq_alloc();
  1230. if (req == NULL)
  1231. goto drop;
  1232. tcp_clear_options(&tp);
  1233. tp.mss_clamp = 536;
  1234. tp.user_mss = sk->tp_pinfo.af_tcp.user_mss;
  1235. tcp_parse_options(skb, &tp, 0);
  1236. if (want_cookie) {
  1237. tcp_clear_options(&tp);
  1238. tp.saw_tstamp = 0;
  1239. }
  1240. if (tp.saw_tstamp && tp.rcv_tsval == 0) {
  1241. /* Some OSes (unknown ones, but I see them on web server, which
  1242.  * contains information interesting only for windows'
  1243.  * users) do not send their stamp in SYN. It is easy case.
  1244.  * We simply do not advertise TS support.
  1245.  */
  1246. tp.saw_tstamp = 0;
  1247. tp.tstamp_ok = 0;
  1248. }
  1249. tp.tstamp_ok = tp.saw_tstamp;
  1250. tcp_openreq_init(req, &tp, skb);
  1251. req->af.v4_req.loc_addr = daddr;
  1252. req->af.v4_req.rmt_addr = saddr;
  1253. req->af.v4_req.opt = tcp_v4_save_options(sk, skb);
  1254. req->class = &or_ipv4;
  1255. if (!want_cookie)
  1256. TCP_ECN_create_request(req, skb->h.th);
  1257. if (want_cookie) {
  1258. #ifdef CONFIG_SYN_COOKIES
  1259. syn_flood_warning(skb);
  1260. #endif
  1261. isn = cookie_v4_init_sequence(sk, skb, &req->mss);
  1262. } else if (isn == 0) {
  1263. struct inet_peer *peer = NULL;
  1264. /* VJ's idea. We save last timestamp seen
  1265.  * from the destination in peer table, when entering
  1266.  * state TIME-WAIT, and check against it before
  1267.  * accepting new connection request.
  1268.  *
  1269.  * If "isn" is not zero, this request hit alive
  1270.  * timewait bucket, so that all the necessary checks
  1271.  * are made in the function processing timewait state.
  1272.  */
  1273. if (tp.saw_tstamp &&
  1274.     sysctl_tcp_tw_recycle &&
  1275.     (dst = tcp_v4_route_req(sk, req)) != NULL &&
  1276.     (peer = rt_get_peer((struct rtable*)dst)) != NULL &&
  1277.     peer->v4daddr == saddr) {
  1278. if (xtime.tv_sec < peer->tcp_ts_stamp + TCP_PAWS_MSL &&
  1279.     (s32)(peer->tcp_ts - req->ts_recent) > TCP_PAWS_WINDOW) {
  1280. NET_INC_STATS_BH(PAWSPassiveRejected);
  1281. dst_release(dst);
  1282. goto drop_and_free;
  1283. }
  1284. }
  1285. /* Kill the following clause, if you dislike this way. */
  1286. else if (!sysctl_tcp_syncookies &&
  1287.  (sysctl_max_syn_backlog - tcp_synq_len(sk)
  1288.   < (sysctl_max_syn_backlog>>2)) &&
  1289.  (!peer || !peer->tcp_ts_stamp) &&
  1290.  (!dst || !dst->rtt)) {
  1291. /* Without syncookies last quarter of
  1292.  * backlog is filled with destinations, proven to be alive.
  1293.  * It means that we continue to communicate
  1294.  * to destinations, already remembered
  1295.  * to the moment of synflood.
  1296.  */
  1297. NETDEBUG(if (net_ratelimit()) 
  1298. printk(KERN_DEBUG "TCP: drop open request from %u.%u.%u.%u/%un", 
  1299. NIPQUAD(saddr), ntohs(skb->h.th->source)));
  1300. dst_release(dst);
  1301. goto drop_and_free;
  1302. }
  1303. isn = tcp_v4_init_sequence(sk, skb);
  1304. }
  1305. req->snt_isn = isn;
  1306. if (tcp_v4_send_synack(sk, req, dst))
  1307. goto drop_and_free;
  1308. if (want_cookie) {
  1309.     tcp_openreq_free(req); 
  1310. } else {
  1311. tcp_v4_synq_add(sk, req);
  1312. }
  1313. return 0;
  1314. drop_and_free:
  1315. tcp_openreq_free(req); 
  1316. drop:
  1317. TCP_INC_STATS_BH(TcpAttemptFails);
  1318. return 0;
  1319. }
  1320. /* 
  1321.  * The three way handshake has completed - we got a valid synack - 
  1322.  * now create the new socket. 
  1323.  */
  1324. struct sock * tcp_v4_syn_recv_sock(struct sock *sk, struct sk_buff *skb,
  1325.    struct open_request *req,
  1326.    struct dst_entry *dst)
  1327. {
  1328. struct tcp_opt *newtp;
  1329. struct sock *newsk;
  1330. if (tcp_acceptq_is_full(sk))
  1331. goto exit_overflow;
  1332. if (dst == NULL &&
  1333.     (dst = tcp_v4_route_req(sk, req)) == NULL)
  1334. goto exit;
  1335. newsk = tcp_create_openreq_child(sk, req, skb);
  1336. if (!newsk)
  1337. goto exit;
  1338. newsk->dst_cache = dst;
  1339. newsk->route_caps = dst->dev->features;
  1340. newtp = &(newsk->tp_pinfo.af_tcp);
  1341. newsk->daddr = req->af.v4_req.rmt_addr;
  1342. newsk->saddr = req->af.v4_req.loc_addr;
  1343. newsk->rcv_saddr = req->af.v4_req.loc_addr;
  1344. newsk->protinfo.af_inet.opt = req->af.v4_req.opt;
  1345. req->af.v4_req.opt = NULL;
  1346. newsk->protinfo.af_inet.mc_index = tcp_v4_iif(skb);
  1347. newsk->protinfo.af_inet.mc_ttl = skb->nh.iph->ttl;
  1348. newtp->ext_header_len = 0;
  1349. if (newsk->protinfo.af_inet.opt)
  1350. newtp->ext_header_len = newsk->protinfo.af_inet.opt->optlen;
  1351. newsk->protinfo.af_inet.id = newtp->write_seq^jiffies;
  1352. tcp_sync_mss(newsk, dst->pmtu);
  1353. newtp->advmss = dst->advmss;
  1354. tcp_initialize_rcv_mss(newsk);
  1355. __tcp_v4_hash(newsk, 0);
  1356. __tcp_inherit_port(sk, newsk);
  1357. return newsk;
  1358. exit_overflow:
  1359. NET_INC_STATS_BH(ListenOverflows);
  1360. exit:
  1361. NET_INC_STATS_BH(ListenDrops);
  1362. dst_release(dst);
  1363. return NULL;
  1364. }
  1365. static struct sock *tcp_v4_hnd_req(struct sock *sk,struct sk_buff *skb)
  1366. {
  1367. struct open_request *req, **prev;
  1368. struct tcphdr *th = skb->h.th;
  1369. struct iphdr *iph = skb->nh.iph;
  1370. struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
  1371. struct sock *nsk;
  1372. /* Find possible connection requests. */
  1373. req = tcp_v4_search_req(tp, &prev,
  1374. th->source,
  1375. iph->saddr, iph->daddr);
  1376. if (req)
  1377. return tcp_check_req(sk, skb, req, prev);
  1378. nsk = __tcp_v4_lookup_established(skb->nh.iph->saddr,
  1379.   th->source,
  1380.   skb->nh.iph->daddr,
  1381.   ntohs(th->dest),
  1382.   tcp_v4_iif(skb));
  1383. if (nsk) {
  1384. if (nsk->state != TCP_TIME_WAIT) {
  1385. bh_lock_sock(nsk);
  1386. return nsk;
  1387. }
  1388. tcp_tw_put((struct tcp_tw_bucket*)nsk);
  1389. return NULL;
  1390. }
  1391. #ifdef CONFIG_SYN_COOKIES
  1392. if (!th->rst && !th->syn && th->ack)
  1393. sk = cookie_v4_check(sk, skb, &(IPCB(skb)->opt));
  1394. #endif
  1395. return sk;
  1396. }
  1397. static int tcp_v4_checksum_init(struct sk_buff *skb)
  1398. {
  1399. if (skb->ip_summed == CHECKSUM_HW) {
  1400. skb->ip_summed = CHECKSUM_UNNECESSARY;
  1401. if (!tcp_v4_check(skb->h.th,skb->len,skb->nh.iph->saddr,
  1402.   skb->nh.iph->daddr,skb->csum))
  1403. return 0;
  1404. NETDEBUG(if (net_ratelimit()) printk(KERN_DEBUG "hw tcp v4 csum failedn"));
  1405. skb->ip_summed = CHECKSUM_NONE;
  1406. }
  1407. if (skb->len <= 76) {
  1408. if (tcp_v4_check(skb->h.th,skb->len,skb->nh.iph->saddr,
  1409.  skb->nh.iph->daddr,
  1410.  skb_checksum(skb, 0, skb->len, 0)))
  1411. return -1;
  1412. skb->ip_summed = CHECKSUM_UNNECESSARY;
  1413. } else {
  1414. skb->csum = ~tcp_v4_check(skb->h.th,skb->len,skb->nh.iph->saddr,
  1415.   skb->nh.iph->daddr,0);
  1416. }
  1417. return 0;
  1418. }
  1419. /* The socket must have it's spinlock held when we get
  1420.  * here.
  1421.  *
  1422.  * We have a potential double-lock case here, so even when
  1423.  * doing backlog processing we use the BH locking scheme.
  1424.  * This is because we cannot sleep with the original spinlock
  1425.  * held.
  1426.  */
  1427. int tcp_v4_do_rcv(struct sock *sk, struct sk_buff *skb)
  1428. {
  1429. #ifdef CONFIG_FILTER
  1430. struct sk_filter *filter = sk->filter;
  1431. if (filter && sk_filter(skb, filter))
  1432. goto discard;
  1433. #endif /* CONFIG_FILTER */
  1434.    IP_INC_STATS_BH(IpInDelivers);
  1435. if (sk->state == TCP_ESTABLISHED) { /* Fast path */
  1436. TCP_CHECK_TIMER(sk);
  1437. if (tcp_rcv_established(sk, skb, skb->h.th, skb->len))
  1438. goto reset;
  1439. TCP_CHECK_TIMER(sk);
  1440. return 0; 
  1441. }
  1442. if (skb->len < (skb->h.th->doff<<2) || tcp_checksum_complete(skb))
  1443. goto csum_err;
  1444. if (sk->state == TCP_LISTEN) { 
  1445. struct sock *nsk = tcp_v4_hnd_req(sk, skb);
  1446. if (!nsk)
  1447. goto discard;
  1448. if (nsk != sk) {
  1449. if (tcp_child_process(sk, nsk, skb))
  1450. goto reset;
  1451. return 0;
  1452. }
  1453. }
  1454. TCP_CHECK_TIMER(sk);
  1455. if (tcp_rcv_state_process(sk, skb, skb->h.th, skb->len))
  1456. goto reset;
  1457. TCP_CHECK_TIMER(sk);
  1458. return 0;
  1459. reset:
  1460. tcp_v4_send_reset(skb);
  1461. discard:
  1462. kfree_skb(skb);
  1463. /* Be careful here. If this function gets more complicated and
  1464.  * gcc suffers from register pressure on the x86, sk (in %ebx) 
  1465.  * might be destroyed here. This current version compiles correctly,
  1466.  * but you have been warned.
  1467.  */
  1468. return 0;
  1469. csum_err:
  1470. TCP_INC_STATS_BH(TcpInErrs);
  1471. goto discard;
  1472. }
  1473. /*
  1474.  * From tcp_input.c
  1475.  */
  1476. int tcp_v4_rcv(struct sk_buff *skb)
  1477. {
  1478. struct tcphdr *th;
  1479. struct sock *sk;
  1480. int ret;
  1481. if (skb->pkt_type!=PACKET_HOST)
  1482. goto discard_it;
  1483. /* Count it even if it's bad */
  1484. TCP_INC_STATS_BH(TcpInSegs);
  1485. if (!pskb_may_pull(skb, sizeof(struct tcphdr)))
  1486. goto discard_it;
  1487. th = skb->h.th;
  1488. if (th->doff < sizeof(struct tcphdr)/4)
  1489. goto bad_packet;
  1490. if (!pskb_may_pull(skb, th->doff*4))
  1491. goto discard_it;
  1492. /* An explanation is required here, I think.
  1493.  * Packet length and doff are validated by header prediction,
  1494.  * provided case of th->doff==0 is elimineted.
  1495.  * So, we defer the checks. */
  1496. if ((skb->ip_summed != CHECKSUM_UNNECESSARY &&
  1497.      tcp_v4_checksum_init(skb) < 0))
  1498. goto bad_packet;
  1499. th = skb->h.th;
  1500. TCP_SKB_CB(skb)->seq = ntohl(th->seq);
  1501. TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin +
  1502.     skb->len - th->doff*4);
  1503. TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq);
  1504. TCP_SKB_CB(skb)->when = 0;
  1505. TCP_SKB_CB(skb)->flags = skb->nh.iph->tos;
  1506. TCP_SKB_CB(skb)->sacked = 0;
  1507. sk = __tcp_v4_lookup(skb->nh.iph->saddr, th->source,
  1508.      skb->nh.iph->daddr, ntohs(th->dest), tcp_v4_iif(skb));
  1509. if (!sk)
  1510. goto no_tcp_socket;
  1511. process:
  1512. if(!ipsec_sk_policy(sk,skb))
  1513. goto discard_and_relse;
  1514. if (sk->state == TCP_TIME_WAIT)
  1515. goto do_time_wait;
  1516. skb->dev = NULL;
  1517. bh_lock_sock(sk);
  1518. ret = 0;
  1519. if (!sk->lock.users) {
  1520. if (!tcp_prequeue(sk, skb))
  1521. ret = tcp_v4_do_rcv(sk, skb);
  1522. } else
  1523. sk_add_backlog(sk, skb);
  1524. bh_unlock_sock(sk);
  1525. sock_put(sk);
  1526. return ret;
  1527. no_tcp_socket:
  1528. if (skb->len < (th->doff<<2) || tcp_checksum_complete(skb)) {
  1529. bad_packet:
  1530. TCP_INC_STATS_BH(TcpInErrs);
  1531. } else {
  1532. tcp_v4_send_reset(skb);
  1533. }
  1534. discard_it:
  1535. /* Discard frame. */
  1536. kfree_skb(skb);
  1537.    return 0;
  1538. discard_and_relse:
  1539. sock_put(sk);
  1540. goto discard_it;
  1541. do_time_wait:
  1542. if (skb->len < (th->doff<<2) || tcp_checksum_complete(skb)) {
  1543. TCP_INC_STATS_BH(TcpInErrs);
  1544. goto discard_and_relse;
  1545. }
  1546. switch(tcp_timewait_state_process((struct tcp_tw_bucket *)sk,
  1547.   skb, th, skb->len)) {
  1548. case TCP_TW_SYN:
  1549. {
  1550. struct sock *sk2;
  1551. sk2 = tcp_v4_lookup_listener(skb->nh.iph->daddr, ntohs(th->dest), tcp_v4_iif(skb));
  1552. if (sk2 != NULL) {
  1553. tcp_tw_deschedule((struct tcp_tw_bucket *)sk);
  1554. tcp_timewait_kill((struct tcp_tw_bucket *)sk);
  1555. tcp_tw_put((struct tcp_tw_bucket *)sk);
  1556. sk = sk2;
  1557. goto process;
  1558. }
  1559. /* Fall through to ACK */
  1560. }
  1561. case TCP_TW_ACK:
  1562. tcp_v4_timewait_ack(sk, skb);
  1563. break;
  1564. case TCP_TW_RST:
  1565. goto no_tcp_socket;
  1566. case TCP_TW_SUCCESS:;
  1567. }
  1568. goto discard_it;
  1569. }
  1570. /* With per-bucket locks this operation is not-atomic, so that
  1571.  * this version is not worse.
  1572.  */
  1573. static void __tcp_v4_rehash(struct sock *sk)
  1574. {
  1575. sk->prot->unhash(sk);
  1576. sk->prot->hash(sk);
  1577. }
  1578. static int tcp_v4_reselect_saddr(struct sock *sk)
  1579. {
  1580. int err;
  1581. struct rtable *rt;
  1582. __u32 old_saddr = sk->saddr;
  1583. __u32 new_saddr;
  1584. __u32 daddr = sk->daddr;
  1585. if(sk->protinfo.af_inet.opt && sk->protinfo.af_inet.opt->srr)
  1586. daddr = sk->protinfo.af_inet.opt->faddr;
  1587. /* Query new route. */
  1588. err = ip_route_connect(&rt, daddr, 0,
  1589.        RT_TOS(sk->protinfo.af_inet.tos)|sk->localroute,
  1590.        sk->bound_dev_if);
  1591. if (err)
  1592. return err;
  1593. __sk_dst_set(sk, &rt->u.dst);
  1594. sk->route_caps = rt->u.dst.dev->features;
  1595. new_saddr = rt->rt_src;
  1596. if (new_saddr == old_saddr)
  1597. return 0;
  1598. if (sysctl_ip_dynaddr > 1) {
  1599. printk(KERN_INFO "tcp_v4_rebuild_header(): shifting sk->saddr "
  1600.        "from %d.%d.%d.%d to %d.%d.%d.%dn",
  1601.        NIPQUAD(old_saddr), 
  1602.        NIPQUAD(new_saddr));
  1603. }
  1604. sk->saddr = new_saddr;
  1605. sk->rcv_saddr = new_saddr;
  1606. /* XXX The only one ugly spot where we need to
  1607.  * XXX really change the sockets identity after
  1608.  * XXX it has entered the hashes. -DaveM
  1609.  *
  1610.  * Besides that, it does not check for connection
  1611.  * uniqueness. Wait for troubles.
  1612.  */
  1613. __tcp_v4_rehash(sk);
  1614. return 0;
  1615. }
  1616. int tcp_v4_rebuild_header(struct sock *sk)
  1617. {
  1618. struct rtable *rt = (struct rtable *)__sk_dst_check(sk, 0);
  1619. u32 daddr;
  1620. int err;
  1621. /* Route is OK, nothing to do. */
  1622. if (rt != NULL)
  1623. return 0;
  1624. /* Reroute. */
  1625. daddr = sk->daddr;
  1626. if(sk->protinfo.af_inet.opt && sk->protinfo.af_inet.opt->srr)
  1627. daddr = sk->protinfo.af_inet.opt->faddr;
  1628. err = ip_route_output(&rt, daddr, sk->saddr,
  1629.       RT_CONN_FLAGS(sk), sk->bound_dev_if);
  1630. if (!err) {
  1631. __sk_dst_set(sk, &rt->u.dst);
  1632. sk->route_caps = rt->u.dst.dev->features;
  1633. return 0;
  1634. }
  1635. /* Routing failed... */
  1636. sk->route_caps = 0;
  1637. if (!sysctl_ip_dynaddr ||
  1638.     sk->state != TCP_SYN_SENT ||
  1639.     (sk->userlocks & SOCK_BINDADDR_LOCK) ||
  1640.     (err = tcp_v4_reselect_saddr(sk)) != 0)
  1641. sk->err_soft=-err;
  1642. return err;
  1643. }
  1644. static void v4_addr2sockaddr(struct sock *sk, struct sockaddr * uaddr)
  1645. {
  1646. struct sockaddr_in *sin = (struct sockaddr_in *) uaddr;
  1647. sin->sin_family = AF_INET;
  1648. sin->sin_addr.s_addr = sk->daddr;
  1649. sin->sin_port = sk->dport;
  1650. }
  1651. /* VJ's idea. Save last timestamp seen from this destination
  1652.  * and hold it at least for normal timewait interval to use for duplicate
  1653.  * segment detection in subsequent connections, before they enter synchronized
  1654.  * state.
  1655.  */
  1656. int tcp_v4_remember_stamp(struct sock *sk)
  1657. {
  1658. struct tcp_opt *tp = &sk->tp_pinfo.af_tcp;
  1659. struct rtable *rt = (struct rtable*)__sk_dst_get(sk);
  1660. struct inet_peer *peer = NULL;
  1661. int release_it = 0;
  1662. if (rt == NULL || rt->rt_dst != sk->daddr) {
  1663. peer = inet_getpeer(sk->daddr, 1);
  1664. release_it = 1;
  1665. } else {
  1666. if (rt->peer == NULL)
  1667. rt_bind_peer(rt, 1);
  1668. peer = rt->peer;
  1669. }
  1670. if (peer) {
  1671. if ((s32)(peer->tcp_ts - tp->ts_recent) <= 0 ||
  1672.     (peer->tcp_ts_stamp + TCP_PAWS_MSL < xtime.tv_sec &&
  1673.      peer->tcp_ts_stamp <= tp->ts_recent_stamp)) {
  1674. peer->tcp_ts_stamp = tp->ts_recent_stamp;
  1675. peer->tcp_ts = tp->ts_recent;
  1676. }
  1677. if (release_it)
  1678. inet_putpeer(peer);
  1679. return 1;
  1680. }
  1681. return 0;
  1682. }
  1683. int tcp_v4_tw_remember_stamp(struct tcp_tw_bucket *tw)
  1684. {
  1685. struct inet_peer *peer = NULL;
  1686. peer = inet_getpeer(tw->daddr, 1);
  1687. if (peer) {
  1688. if ((s32)(peer->tcp_ts - tw->ts_recent) <= 0 ||
  1689.     (peer->tcp_ts_stamp + TCP_PAWS_MSL < xtime.tv_sec &&
  1690.      peer->tcp_ts_stamp <= tw->ts_recent_stamp)) {
  1691. peer->tcp_ts_stamp = tw->ts_recent_stamp;
  1692. peer->tcp_ts = tw->ts_recent;
  1693. }
  1694. inet_putpeer(peer);
  1695. return 1;
  1696. }
  1697. return 0;
  1698. }
  1699. struct tcp_func ipv4_specific = {
  1700. ip_queue_xmit,
  1701. tcp_v4_send_check,
  1702. tcp_v4_rebuild_header,
  1703. tcp_v4_conn_request,
  1704. tcp_v4_syn_recv_sock,
  1705. tcp_v4_remember_stamp,
  1706. sizeof(struct iphdr),
  1707. ip_setsockopt,
  1708. ip_getsockopt,
  1709. v4_addr2sockaddr,
  1710. sizeof(struct sockaddr_in)
  1711. };
  1712. /* NOTE: A lot of things set to zero explicitly by call to
  1713.  *       sk_alloc() so need not be done here.
  1714.  */
  1715. static int tcp_v4_init_sock(struct sock *sk)
  1716. {
  1717. struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
  1718. skb_queue_head_init(&tp->out_of_order_queue);
  1719. tcp_init_xmit_timers(sk);
  1720. tcp_prequeue_init(tp);
  1721. tp->rto  = TCP_TIMEOUT_INIT;
  1722. tp->mdev = TCP_TIMEOUT_INIT;
  1723.       
  1724. /* So many TCP implementations out there (incorrectly) count the
  1725.  * initial SYN frame in their delayed-ACK and congestion control
  1726.  * algorithms that we must have the following bandaid to talk
  1727.  * efficiently to them.  -DaveM
  1728.  */
  1729. tp->snd_cwnd = 2;
  1730. /* See draft-stevens-tcpca-spec-01 for discussion of the
  1731.  * initialization of these values.
  1732.  */
  1733. tp->snd_ssthresh = 0x7fffffff; /* Infinity */
  1734. tp->snd_cwnd_clamp = ~0;
  1735. tp->mss_cache = 536;
  1736. tp->reordering = sysctl_tcp_reordering;
  1737. sk->state = TCP_CLOSE;
  1738. sk->write_space = tcp_write_space;
  1739. sk->use_write_queue = 1;
  1740. sk->tp_pinfo.af_tcp.af_specific = &ipv4_specific;
  1741. sk->sndbuf = sysctl_tcp_wmem[1];
  1742. sk->rcvbuf = sysctl_tcp_rmem[1];
  1743. atomic_inc(&tcp_sockets_allocated);
  1744. return 0;
  1745. }
  1746. static int tcp_v4_destroy_sock(struct sock *sk)
  1747. {
  1748. struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
  1749. tcp_clear_xmit_timers(sk);
  1750. /* Cleanup up the write buffer. */
  1751.    tcp_writequeue_purge(sk);
  1752. /* Cleans up our, hopefully empty, out_of_order_queue. */
  1753.    __skb_queue_purge(&tp->out_of_order_queue);
  1754. /* Clean prequeue, it must be empty really */
  1755. __skb_queue_purge(&tp->ucopy.prequeue);
  1756. /* Clean up a referenced TCP bind bucket. */
  1757. if(sk->prev != NULL)
  1758. tcp_put_port(sk);
  1759. /* If sendmsg cached page exists, toss it. */
  1760. if (tp->sndmsg_page != NULL)
  1761. __free_page(tp->sndmsg_page);
  1762. atomic_dec(&tcp_sockets_allocated);
  1763. return 0;
  1764. }
  1765. /* Proc filesystem TCP sock list dumping. */
  1766. static void get_openreq(struct sock *sk, struct open_request *req, char *tmpbuf, int i, int uid)
  1767. {
  1768. int ttd = req->expires - jiffies;
  1769. sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
  1770. " %02X %08X:%08X %02X:%08X %08X %5d %8d %u %d %p",
  1771. i,
  1772. req->af.v4_req.loc_addr,
  1773. ntohs(sk->sport),
  1774. req->af.v4_req.rmt_addr,
  1775. ntohs(req->rmt_port),
  1776. TCP_SYN_RECV,
  1777. 0,0, /* could print option size, but that is af dependent. */
  1778. 1,   /* timers active (only the expire timer) */  
  1779. ttd, 
  1780. req->retrans,
  1781. uid,
  1782. 0,  /* non standard timer */  
  1783. 0, /* open_requests have no inode */
  1784. atomic_read(&sk->refcnt),
  1785. req
  1786. ); 
  1787. }
  1788. static void get_tcp_sock(struct sock *sp, char *tmpbuf, int i)
  1789. {
  1790. unsigned int dest, src;
  1791. __u16 destp, srcp;
  1792. int timer_active;
  1793. unsigned long timer_expires;
  1794. struct tcp_opt *tp = &sp->tp_pinfo.af_tcp;
  1795. dest  = sp->daddr;
  1796. src   = sp->rcv_saddr;
  1797. destp = ntohs(sp->dport);
  1798. srcp  = ntohs(sp->sport);
  1799. if (tp->pending == TCP_TIME_RETRANS) {
  1800. timer_active = 1;
  1801. timer_expires = tp->timeout;
  1802. } else if (tp->pending == TCP_TIME_PROBE0) {
  1803. timer_active = 4;
  1804. timer_expires = tp->timeout;
  1805. } else if (timer_pending(&sp->timer)) {
  1806. timer_active = 2;
  1807. timer_expires = sp->timer.expires;
  1808. } else {
  1809. timer_active = 0;
  1810. timer_expires = jiffies;
  1811. }
  1812. sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
  1813. " %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %p %u %u %u %u %d",
  1814. i, src, srcp, dest, destp, sp->state, 
  1815. tp->write_seq-tp->snd_una, tp->rcv_nxt-tp->copied_seq,
  1816. timer_active, timer_expires-jiffies,
  1817. tp->retransmits,
  1818. sock_i_uid(sp),
  1819. tp->probes_out,
  1820. sock_i_ino(sp),
  1821. atomic_read(&sp->refcnt), sp,
  1822. tp->rto, tp->ack.ato, (tp->ack.quick<<1)|tp->ack.pingpong,
  1823. tp->snd_cwnd, tp->snd_ssthresh>=0xFFFF?-1:tp->snd_ssthresh
  1824. );
  1825. }
  1826. static void get_timewait_sock(struct tcp_tw_bucket *tw, char *tmpbuf, int i)
  1827. {
  1828. unsigned int dest, src;
  1829. __u16 destp, srcp;
  1830. int ttd = tw->ttd - jiffies;
  1831. if (ttd < 0)
  1832. ttd = 0;
  1833. dest  = tw->daddr;
  1834. src   = tw->rcv_saddr;
  1835. destp = ntohs(tw->dport);
  1836. srcp  = ntohs(tw->sport);
  1837. sprintf(tmpbuf, "%4d: %08X:%04X %08X:%04X"
  1838. " %02X %08X:%08X %02X:%08X %08X %5d %8d %d %d %p",
  1839. i, src, srcp, dest, destp, tw->substate, 0, 0,
  1840. 3, ttd, 0, 0, 0, 0,
  1841. atomic_read(&tw->refcnt), tw);
  1842. }
  1843. #define TMPSZ 150
  1844. int tcp_get_info(char *buffer, char **start, off_t offset, int length)
  1845. {
  1846. int len = 0, num = 0, i;
  1847. off_t begin, pos = 0;
  1848. char tmpbuf[TMPSZ+1];
  1849. if (offset < TMPSZ)
  1850. len += sprintf(buffer, "%-*sn", TMPSZ-1,
  1851.        "  sl  local_address rem_address   st tx_queue "
  1852.        "rx_queue tr tm->when retrnsmt   uid  timeout inode");
  1853. pos = TMPSZ;
  1854. /* First, walk listening socket table. */
  1855. tcp_listen_lock();
  1856. for(i = 0; i < TCP_LHTABLE_SIZE; i++) {
  1857. struct sock *sk;
  1858. struct tcp_listen_opt *lopt;
  1859. int k;
  1860. for (sk = tcp_listening_hash[i]; sk; sk = sk->next, num++) {
  1861. struct open_request *req;
  1862. int uid;
  1863. struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
  1864. if (!TCP_INET_FAMILY(sk->family))
  1865. goto skip_listen;
  1866. pos += TMPSZ;
  1867. if (pos >= offset) {
  1868. get_tcp_sock(sk, tmpbuf, num);
  1869. len += sprintf(buffer+len, "%-*sn", TMPSZ-1, tmpbuf);
  1870. if (pos >= offset + length) {
  1871. tcp_listen_unlock();
  1872. goto out_no_bh;
  1873. }
  1874. }
  1875. skip_listen:
  1876. uid = sock_i_uid(sk);
  1877. read_lock_bh(&tp->syn_wait_lock);
  1878. lopt = tp->listen_opt;
  1879. if (lopt && lopt->qlen != 0) {
  1880. for (k=0; k<TCP_SYNQ_HSIZE; k++) {
  1881. for (req = lopt->syn_table[k]; req; req = req->dl_next, num++) {
  1882. if (!TCP_INET_FAMILY(req->class->family))
  1883. continue;
  1884. pos += TMPSZ;
  1885. if (pos <= offset)
  1886. continue;
  1887. get_openreq(sk, req, tmpbuf, num, uid);
  1888. len += sprintf(buffer+len, "%-*sn", TMPSZ-1, tmpbuf);
  1889. if (pos >= offset + length) {
  1890. read_unlock_bh(&tp->syn_wait_lock);
  1891. tcp_listen_unlock();
  1892. goto out_no_bh;
  1893. }
  1894. }
  1895. }
  1896. }
  1897. read_unlock_bh(&tp->syn_wait_lock);
  1898. /* Completed requests are in normal socket hash table */
  1899. }
  1900. }
  1901. tcp_listen_unlock();
  1902. local_bh_disable();
  1903. /* Next, walk established hash chain. */
  1904. for (i = 0; i < tcp_ehash_size; i++) {
  1905. struct tcp_ehash_bucket *head = &tcp_ehash[i];
  1906. struct sock *sk;
  1907. struct tcp_tw_bucket *tw;
  1908. read_lock(&head->lock);
  1909. for(sk = head->chain; sk; sk = sk->next, num++) {
  1910. if (!TCP_INET_FAMILY(sk->family))
  1911. continue;
  1912. pos += TMPSZ;
  1913. if (pos <= offset)
  1914. continue;
  1915. get_tcp_sock(sk, tmpbuf, num);
  1916. len += sprintf(buffer+len, "%-*sn", TMPSZ-1, tmpbuf);
  1917. if (pos >= offset + length) {
  1918. read_unlock(&head->lock);
  1919. goto out;
  1920. }
  1921. }
  1922. for (tw = (struct tcp_tw_bucket *)tcp_ehash[i+tcp_ehash_size].chain;
  1923.      tw != NULL;
  1924.      tw = (struct tcp_tw_bucket *)tw->next, num++) {
  1925. if (!TCP_INET_FAMILY(tw->family))
  1926. continue;
  1927. pos += TMPSZ;
  1928. if (pos <= offset)
  1929. continue;
  1930. get_timewait_sock(tw, tmpbuf, num);
  1931. len += sprintf(buffer+len, "%-*sn", TMPSZ-1, tmpbuf);
  1932. if (pos >= offset + length) {
  1933. read_unlock(&head->lock);
  1934. goto out;
  1935. }
  1936. }
  1937. read_unlock(&head->lock);
  1938. }
  1939. out:
  1940. local_bh_enable();
  1941. out_no_bh:
  1942. begin = len - (pos - offset);
  1943. *start = buffer + begin;
  1944. len -= begin;
  1945. if (len > length)
  1946. len = length;
  1947. if (len < 0)
  1948. len = 0; 
  1949. return len;
  1950. }
  1951. struct proto tcp_prot = {
  1952. name: "TCP",
  1953. close: tcp_close,
  1954. connect: tcp_v4_connect,
  1955. disconnect: tcp_disconnect,
  1956. accept: tcp_accept,
  1957. ioctl: tcp_ioctl,
  1958. init: tcp_v4_init_sock,
  1959. destroy: tcp_v4_destroy_sock,
  1960. shutdown: tcp_shutdown,
  1961. setsockopt: tcp_setsockopt,
  1962. getsockopt: tcp_getsockopt,
  1963. sendmsg: tcp_sendmsg,
  1964. recvmsg: tcp_recvmsg,
  1965. backlog_rcv: tcp_v4_do_rcv,
  1966. hash: tcp_v4_hash,
  1967. unhash: tcp_unhash,
  1968. get_port: tcp_v4_get_port,
  1969. };
  1970. void __init tcp_v4_init(struct net_proto_family *ops)
  1971. {
  1972. int err;
  1973. tcp_inode.i_mode = S_IFSOCK;
  1974. tcp_inode.i_sock = 1;
  1975. tcp_inode.i_uid = 0;
  1976. tcp_inode.i_gid = 0;
  1977. init_waitqueue_head(&tcp_inode.i_wait);
  1978. init_waitqueue_head(&tcp_inode.u.socket_i.wait);
  1979. tcp_socket->inode = &tcp_inode;
  1980. tcp_socket->state = SS_UNCONNECTED;
  1981. tcp_socket->type=SOCK_RAW;
  1982. if ((err=ops->create(tcp_socket, IPPROTO_TCP))<0)
  1983. panic("Failed to create the TCP control socket.n");
  1984. tcp_socket->sk->allocation=GFP_ATOMIC;
  1985. tcp_socket->sk->protinfo.af_inet.ttl = MAXTTL;
  1986. /* Unhash it so that IP input processing does not even
  1987.  * see it, we do not wish this socket to see incoming
  1988.  * packets.
  1989.  */
  1990. tcp_socket->sk->prot->unhash(tcp_socket->sk);
  1991. }