inet_connection_sock.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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. * Support for INET connection oriented protocols.
  7. *
  8. * Authors: See the TCP sources
  9. *
  10. * This program is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU General Public License
  12. * as published by the Free Software Foundation; either version
  13. * 2 of the License, or(at your option) any later version.
  14. */
  15. #include <linux/module.h>
  16. #include <linux/jhash.h>
  17. #include <net/inet_connection_sock.h>
  18. #include <net/inet_hashtables.h>
  19. #include <net/inet_timewait_sock.h>
  20. #include <net/ip.h>
  21. #include <net/route.h>
  22. #include <net/tcp_states.h>
  23. #include <net/xfrm.h>
  24. #include <net/tcp.h>
  25. #ifdef INET_CSK_DEBUG
  26. const char inet_csk_timer_bug_msg[] = "inet_csk BUG: unknown timer value\n";
  27. EXPORT_SYMBOL(inet_csk_timer_bug_msg);
  28. #endif
  29. void inet_get_local_port_range(struct net *net, int *low, int *high)
  30. {
  31. unsigned int seq;
  32. do {
  33. seq = read_seqbegin(&net->ipv4.ip_local_ports.lock);
  34. *low = net->ipv4.ip_local_ports.range[0];
  35. *high = net->ipv4.ip_local_ports.range[1];
  36. } while (read_seqretry(&net->ipv4.ip_local_ports.lock, seq));
  37. }
  38. EXPORT_SYMBOL(inet_get_local_port_range);
  39. int inet_csk_bind_conflict(const struct sock *sk,
  40. const struct inet_bind_bucket *tb, bool relax)
  41. {
  42. struct sock *sk2;
  43. int reuse = sk->sk_reuse;
  44. int reuseport = sk->sk_reuseport;
  45. kuid_t uid = sock_i_uid((struct sock *)sk);
  46. /*
  47. * Unlike other sk lookup places we do not check
  48. * for sk_net here, since _all_ the socks listed
  49. * in tb->owners list belong to the same net - the
  50. * one this bucket belongs to.
  51. */
  52. sk_for_each_bound(sk2, &tb->owners) {
  53. if (sk != sk2 &&
  54. !inet_v6_ipv6only(sk2) &&
  55. (!sk->sk_bound_dev_if ||
  56. !sk2->sk_bound_dev_if ||
  57. sk->sk_bound_dev_if == sk2->sk_bound_dev_if)) {
  58. if ((!reuse || !sk2->sk_reuse ||
  59. sk2->sk_state == TCP_LISTEN) &&
  60. (!reuseport || !sk2->sk_reuseport ||
  61. (sk2->sk_state != TCP_TIME_WAIT &&
  62. !uid_eq(uid, sock_i_uid(sk2))))) {
  63. if (!sk2->sk_rcv_saddr || !sk->sk_rcv_saddr ||
  64. sk2->sk_rcv_saddr == sk->sk_rcv_saddr)
  65. break;
  66. }
  67. if (!relax && reuse && sk2->sk_reuse &&
  68. sk2->sk_state != TCP_LISTEN) {
  69. if (!sk2->sk_rcv_saddr || !sk->sk_rcv_saddr ||
  70. sk2->sk_rcv_saddr == sk->sk_rcv_saddr)
  71. break;
  72. }
  73. }
  74. }
  75. return sk2 != NULL;
  76. }
  77. EXPORT_SYMBOL_GPL(inet_csk_bind_conflict);
  78. /* Obtain a reference to a local port for the given sock,
  79. * if snum is zero it means select any available local port.
  80. */
  81. int inet_csk_get_port(struct sock *sk, unsigned short snum)
  82. {
  83. struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
  84. struct inet_bind_hashbucket *head;
  85. struct inet_bind_bucket *tb;
  86. int ret, attempts = 5;
  87. struct net *net = sock_net(sk);
  88. int smallest_size = -1, smallest_rover;
  89. kuid_t uid = sock_i_uid(sk);
  90. int attempt_half = (sk->sk_reuse == SK_CAN_REUSE) ? 1 : 0;
  91. local_bh_disable();
  92. if (!snum) {
  93. int remaining, rover, low, high;
  94. again:
  95. inet_get_local_port_range(net, &low, &high);
  96. if (attempt_half) {
  97. int half = low + ((high - low) >> 1);
  98. if (attempt_half == 1)
  99. high = half;
  100. else
  101. low = half;
  102. }
  103. remaining = (high - low) + 1;
  104. smallest_rover = rover = prandom_u32() % remaining + low;
  105. smallest_size = -1;
  106. do {
  107. if (inet_is_local_reserved_port(net, rover))
  108. goto next_nolock;
  109. head = &hashinfo->bhash[inet_bhashfn(net, rover,
  110. hashinfo->bhash_size)];
  111. spin_lock(&head->lock);
  112. inet_bind_bucket_for_each(tb, &head->chain)
  113. if (net_eq(ib_net(tb), net) && tb->port == rover) {
  114. if (((tb->fastreuse > 0 &&
  115. sk->sk_reuse &&
  116. sk->sk_state != TCP_LISTEN) ||
  117. (tb->fastreuseport > 0 &&
  118. sk->sk_reuseport &&
  119. uid_eq(tb->fastuid, uid))) &&
  120. (tb->num_owners < smallest_size || smallest_size == -1)) {
  121. smallest_size = tb->num_owners;
  122. smallest_rover = rover;
  123. }
  124. if (!inet_csk(sk)->icsk_af_ops->bind_conflict(sk, tb, false)) {
  125. snum = rover;
  126. goto tb_found;
  127. }
  128. goto next;
  129. }
  130. break;
  131. next:
  132. spin_unlock(&head->lock);
  133. next_nolock:
  134. if (++rover > high)
  135. rover = low;
  136. } while (--remaining > 0);
  137. /* Exhausted local port range during search? It is not
  138. * possible for us to be holding one of the bind hash
  139. * locks if this test triggers, because if 'remaining'
  140. * drops to zero, we broke out of the do/while loop at
  141. * the top level, not from the 'break;' statement.
  142. */
  143. ret = 1;
  144. if (remaining <= 0) {
  145. if (smallest_size != -1) {
  146. snum = smallest_rover;
  147. goto have_snum;
  148. }
  149. if (attempt_half == 1) {
  150. /* OK we now try the upper half of the range */
  151. attempt_half = 2;
  152. goto again;
  153. }
  154. goto fail;
  155. }
  156. /* OK, here is the one we will use. HEAD is
  157. * non-NULL and we hold it's mutex.
  158. */
  159. snum = rover;
  160. } else {
  161. have_snum:
  162. head = &hashinfo->bhash[inet_bhashfn(net, snum,
  163. hashinfo->bhash_size)];
  164. spin_lock(&head->lock);
  165. inet_bind_bucket_for_each(tb, &head->chain)
  166. if (net_eq(ib_net(tb), net) && tb->port == snum)
  167. goto tb_found;
  168. }
  169. tb = NULL;
  170. goto tb_not_found;
  171. tb_found:
  172. if (!hlist_empty(&tb->owners)) {
  173. if (sk->sk_reuse == SK_FORCE_REUSE)
  174. goto success;
  175. if (((tb->fastreuse > 0 &&
  176. sk->sk_reuse && sk->sk_state != TCP_LISTEN) ||
  177. (tb->fastreuseport > 0 &&
  178. sk->sk_reuseport && uid_eq(tb->fastuid, uid))) &&
  179. smallest_size == -1) {
  180. goto success;
  181. } else {
  182. ret = 1;
  183. if (inet_csk(sk)->icsk_af_ops->bind_conflict(sk, tb, true)) {
  184. if (((sk->sk_reuse && sk->sk_state != TCP_LISTEN) ||
  185. (tb->fastreuseport > 0 &&
  186. sk->sk_reuseport && uid_eq(tb->fastuid, uid))) &&
  187. smallest_size != -1 && --attempts >= 0) {
  188. spin_unlock(&head->lock);
  189. goto again;
  190. }
  191. goto fail_unlock;
  192. }
  193. }
  194. }
  195. tb_not_found:
  196. ret = 1;
  197. if (!tb && (tb = inet_bind_bucket_create(hashinfo->bind_bucket_cachep,
  198. net, head, snum)) == NULL)
  199. goto fail_unlock;
  200. if (hlist_empty(&tb->owners)) {
  201. if (sk->sk_reuse && sk->sk_state != TCP_LISTEN)
  202. tb->fastreuse = 1;
  203. else
  204. tb->fastreuse = 0;
  205. if (sk->sk_reuseport) {
  206. tb->fastreuseport = 1;
  207. tb->fastuid = uid;
  208. } else
  209. tb->fastreuseport = 0;
  210. } else {
  211. if (tb->fastreuse &&
  212. (!sk->sk_reuse || sk->sk_state == TCP_LISTEN))
  213. tb->fastreuse = 0;
  214. if (tb->fastreuseport &&
  215. (!sk->sk_reuseport || !uid_eq(tb->fastuid, uid)))
  216. tb->fastreuseport = 0;
  217. }
  218. success:
  219. if (!inet_csk(sk)->icsk_bind_hash)
  220. inet_bind_hash(sk, tb, snum);
  221. WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
  222. ret = 0;
  223. fail_unlock:
  224. spin_unlock(&head->lock);
  225. fail:
  226. local_bh_enable();
  227. return ret;
  228. }
  229. EXPORT_SYMBOL_GPL(inet_csk_get_port);
  230. /*
  231. * Wait for an incoming connection, avoid race conditions. This must be called
  232. * with the socket locked.
  233. */
  234. static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
  235. {
  236. struct inet_connection_sock *icsk = inet_csk(sk);
  237. DEFINE_WAIT(wait);
  238. int err;
  239. /*
  240. * True wake-one mechanism for incoming connections: only
  241. * one process gets woken up, not the 'whole herd'.
  242. * Since we do not 'race & poll' for established sockets
  243. * anymore, the common case will execute the loop only once.
  244. *
  245. * Subtle issue: "add_wait_queue_exclusive()" will be added
  246. * after any current non-exclusive waiters, and we know that
  247. * it will always _stay_ after any new non-exclusive waiters
  248. * because all non-exclusive waiters are added at the
  249. * beginning of the wait-queue. As such, it's ok to "drop"
  250. * our exclusiveness temporarily when we get woken up without
  251. * having to remove and re-insert us on the wait queue.
  252. */
  253. for (;;) {
  254. prepare_to_wait_exclusive(sk_sleep(sk), &wait,
  255. TASK_INTERRUPTIBLE);
  256. release_sock(sk);
  257. if (reqsk_queue_empty(&icsk->icsk_accept_queue))
  258. timeo = schedule_timeout(timeo);
  259. sched_annotate_sleep();
  260. lock_sock(sk);
  261. err = 0;
  262. if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
  263. break;
  264. err = -EINVAL;
  265. if (sk->sk_state != TCP_LISTEN)
  266. break;
  267. err = sock_intr_errno(timeo);
  268. if (signal_pending(current))
  269. break;
  270. err = -EAGAIN;
  271. if (!timeo)
  272. break;
  273. }
  274. finish_wait(sk_sleep(sk), &wait);
  275. return err;
  276. }
  277. /*
  278. * This will accept the next outstanding connection.
  279. */
  280. struct sock *inet_csk_accept(struct sock *sk, int flags, int *err)
  281. {
  282. struct inet_connection_sock *icsk = inet_csk(sk);
  283. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  284. struct request_sock *req;
  285. struct sock *newsk;
  286. int error;
  287. lock_sock(sk);
  288. /* We need to make sure that this socket is listening,
  289. * and that it has something pending.
  290. */
  291. error = -EINVAL;
  292. if (sk->sk_state != TCP_LISTEN)
  293. goto out_err;
  294. /* Find already established connection */
  295. if (reqsk_queue_empty(queue)) {
  296. long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
  297. /* If this is a non blocking socket don't sleep */
  298. error = -EAGAIN;
  299. if (!timeo)
  300. goto out_err;
  301. error = inet_csk_wait_for_connect(sk, timeo);
  302. if (error)
  303. goto out_err;
  304. }
  305. req = reqsk_queue_remove(queue);
  306. newsk = req->sk;
  307. sk_acceptq_removed(sk);
  308. if (sk->sk_protocol == IPPROTO_TCP &&
  309. tcp_rsk(req)->tfo_listener &&
  310. queue->fastopenq) {
  311. spin_lock_bh(&queue->fastopenq->lock);
  312. if (tcp_rsk(req)->tfo_listener) {
  313. /* We are still waiting for the final ACK from 3WHS
  314. * so can't free req now. Instead, we set req->sk to
  315. * NULL to signify that the child socket is taken
  316. * so reqsk_fastopen_remove() will free the req
  317. * when 3WHS finishes (or is aborted).
  318. */
  319. req->sk = NULL;
  320. req = NULL;
  321. }
  322. spin_unlock_bh(&queue->fastopenq->lock);
  323. }
  324. out:
  325. release_sock(sk);
  326. if (req)
  327. reqsk_put(req);
  328. return newsk;
  329. out_err:
  330. newsk = NULL;
  331. req = NULL;
  332. *err = error;
  333. goto out;
  334. }
  335. EXPORT_SYMBOL(inet_csk_accept);
  336. /*
  337. * Using different timers for retransmit, delayed acks and probes
  338. * We may wish use just one timer maintaining a list of expire jiffies
  339. * to optimize.
  340. */
  341. void inet_csk_init_xmit_timers(struct sock *sk,
  342. void (*retransmit_handler)(unsigned long),
  343. void (*delack_handler)(unsigned long),
  344. void (*keepalive_handler)(unsigned long))
  345. {
  346. struct inet_connection_sock *icsk = inet_csk(sk);
  347. setup_timer(&icsk->icsk_retransmit_timer, retransmit_handler,
  348. (unsigned long)sk);
  349. setup_timer(&icsk->icsk_delack_timer, delack_handler,
  350. (unsigned long)sk);
  351. setup_timer(&sk->sk_timer, keepalive_handler, (unsigned long)sk);
  352. icsk->icsk_pending = icsk->icsk_ack.pending = 0;
  353. }
  354. EXPORT_SYMBOL(inet_csk_init_xmit_timers);
  355. void inet_csk_clear_xmit_timers(struct sock *sk)
  356. {
  357. struct inet_connection_sock *icsk = inet_csk(sk);
  358. icsk->icsk_pending = icsk->icsk_ack.pending = icsk->icsk_ack.blocked = 0;
  359. sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
  360. sk_stop_timer(sk, &icsk->icsk_delack_timer);
  361. sk_stop_timer(sk, &sk->sk_timer);
  362. }
  363. EXPORT_SYMBOL(inet_csk_clear_xmit_timers);
  364. void inet_csk_delete_keepalive_timer(struct sock *sk)
  365. {
  366. sk_stop_timer(sk, &sk->sk_timer);
  367. }
  368. EXPORT_SYMBOL(inet_csk_delete_keepalive_timer);
  369. void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len)
  370. {
  371. sk_reset_timer(sk, &sk->sk_timer, jiffies + len);
  372. }
  373. EXPORT_SYMBOL(inet_csk_reset_keepalive_timer);
  374. struct dst_entry *inet_csk_route_req(struct sock *sk,
  375. struct flowi4 *fl4,
  376. const struct request_sock *req)
  377. {
  378. const struct inet_request_sock *ireq = inet_rsk(req);
  379. struct net *net = read_pnet(&ireq->ireq_net);
  380. struct ip_options_rcu *opt = ireq->opt;
  381. struct rtable *rt;
  382. flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
  383. RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
  384. sk->sk_protocol, inet_sk_flowi_flags(sk),
  385. (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
  386. ireq->ir_loc_addr, ireq->ir_rmt_port,
  387. htons(ireq->ir_num));
  388. security_req_classify_flow(req, flowi4_to_flowi(fl4));
  389. rt = ip_route_output_flow(net, fl4, sk);
  390. if (IS_ERR(rt))
  391. goto no_route;
  392. if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
  393. goto route_err;
  394. return &rt->dst;
  395. route_err:
  396. ip_rt_put(rt);
  397. no_route:
  398. IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
  399. return NULL;
  400. }
  401. EXPORT_SYMBOL_GPL(inet_csk_route_req);
  402. struct dst_entry *inet_csk_route_child_sock(struct sock *sk,
  403. struct sock *newsk,
  404. const struct request_sock *req)
  405. {
  406. const struct inet_request_sock *ireq = inet_rsk(req);
  407. struct net *net = read_pnet(&ireq->ireq_net);
  408. struct inet_sock *newinet = inet_sk(newsk);
  409. struct ip_options_rcu *opt;
  410. struct flowi4 *fl4;
  411. struct rtable *rt;
  412. fl4 = &newinet->cork.fl.u.ip4;
  413. rcu_read_lock();
  414. opt = rcu_dereference(newinet->inet_opt);
  415. flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
  416. RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
  417. sk->sk_protocol, inet_sk_flowi_flags(sk),
  418. (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
  419. ireq->ir_loc_addr, ireq->ir_rmt_port,
  420. htons(ireq->ir_num));
  421. security_req_classify_flow(req, flowi4_to_flowi(fl4));
  422. rt = ip_route_output_flow(net, fl4, sk);
  423. if (IS_ERR(rt))
  424. goto no_route;
  425. if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
  426. goto route_err;
  427. rcu_read_unlock();
  428. return &rt->dst;
  429. route_err:
  430. ip_rt_put(rt);
  431. no_route:
  432. rcu_read_unlock();
  433. IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
  434. return NULL;
  435. }
  436. EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);
  437. static inline u32 inet_synq_hash(const __be32 raddr, const __be16 rport,
  438. const u32 rnd, const u32 synq_hsize)
  439. {
  440. return jhash_2words((__force u32)raddr, (__force u32)rport, rnd) & (synq_hsize - 1);
  441. }
  442. #if IS_ENABLED(CONFIG_IPV6)
  443. #define AF_INET_FAMILY(fam) ((fam) == AF_INET)
  444. #else
  445. #define AF_INET_FAMILY(fam) true
  446. #endif
  447. /* Note: this is temporary :
  448. * req sock will no longer be in listener hash table
  449. */
  450. struct request_sock *inet_csk_search_req(struct sock *sk,
  451. const __be16 rport,
  452. const __be32 raddr,
  453. const __be32 laddr)
  454. {
  455. struct inet_connection_sock *icsk = inet_csk(sk);
  456. struct listen_sock *lopt = icsk->icsk_accept_queue.listen_opt;
  457. struct request_sock *req;
  458. u32 hash = inet_synq_hash(raddr, rport, lopt->hash_rnd,
  459. lopt->nr_table_entries);
  460. spin_lock(&icsk->icsk_accept_queue.syn_wait_lock);
  461. for (req = lopt->syn_table[hash]; req != NULL; req = req->dl_next) {
  462. const struct inet_request_sock *ireq = inet_rsk(req);
  463. if (ireq->ir_rmt_port == rport &&
  464. ireq->ir_rmt_addr == raddr &&
  465. ireq->ir_loc_addr == laddr &&
  466. AF_INET_FAMILY(req->rsk_ops->family)) {
  467. atomic_inc(&req->rsk_refcnt);
  468. WARN_ON(req->sk);
  469. break;
  470. }
  471. }
  472. spin_unlock(&icsk->icsk_accept_queue.syn_wait_lock);
  473. return req;
  474. }
  475. EXPORT_SYMBOL_GPL(inet_csk_search_req);
  476. void inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
  477. unsigned long timeout)
  478. {
  479. struct inet_connection_sock *icsk = inet_csk(sk);
  480. struct listen_sock *lopt = icsk->icsk_accept_queue.listen_opt;
  481. const u32 h = inet_synq_hash(inet_rsk(req)->ir_rmt_addr,
  482. inet_rsk(req)->ir_rmt_port,
  483. lopt->hash_rnd, lopt->nr_table_entries);
  484. reqsk_queue_hash_req(&icsk->icsk_accept_queue, h, req, timeout);
  485. inet_csk_reqsk_queue_added(sk, timeout);
  486. }
  487. EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
  488. /* Only thing we need from tcp.h */
  489. extern int sysctl_tcp_synack_retries;
  490. /* Decide when to expire the request and when to resend SYN-ACK */
  491. static inline void syn_ack_recalc(struct request_sock *req, const int thresh,
  492. const int max_retries,
  493. const u8 rskq_defer_accept,
  494. int *expire, int *resend)
  495. {
  496. if (!rskq_defer_accept) {
  497. *expire = req->num_timeout >= thresh;
  498. *resend = 1;
  499. return;
  500. }
  501. *expire = req->num_timeout >= thresh &&
  502. (!inet_rsk(req)->acked || req->num_timeout >= max_retries);
  503. /*
  504. * Do not resend while waiting for data after ACK,
  505. * start to resend on end of deferring period to give
  506. * last chance for data or ACK to create established socket.
  507. */
  508. *resend = !inet_rsk(req)->acked ||
  509. req->num_timeout >= rskq_defer_accept - 1;
  510. }
  511. int inet_rtx_syn_ack(struct sock *parent, struct request_sock *req)
  512. {
  513. int err = req->rsk_ops->rtx_syn_ack(parent, req);
  514. if (!err)
  515. req->num_retrans++;
  516. return err;
  517. }
  518. EXPORT_SYMBOL(inet_rtx_syn_ack);
  519. /* return true if req was found in the syn_table[] */
  520. static bool reqsk_queue_unlink(struct request_sock_queue *queue,
  521. struct request_sock *req)
  522. {
  523. struct listen_sock *lopt = queue->listen_opt;
  524. struct request_sock **prev;
  525. bool found = false;
  526. spin_lock(&queue->syn_wait_lock);
  527. for (prev = &lopt->syn_table[req->rsk_hash]; *prev != NULL;
  528. prev = &(*prev)->dl_next) {
  529. if (*prev == req) {
  530. *prev = req->dl_next;
  531. found = true;
  532. break;
  533. }
  534. }
  535. spin_unlock(&queue->syn_wait_lock);
  536. if (del_timer(&req->rsk_timer))
  537. reqsk_put(req);
  538. return found;
  539. }
  540. void inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req)
  541. {
  542. if (reqsk_queue_unlink(&inet_csk(sk)->icsk_accept_queue, req)) {
  543. reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
  544. reqsk_put(req);
  545. }
  546. }
  547. EXPORT_SYMBOL(inet_csk_reqsk_queue_drop);
  548. static void reqsk_timer_handler(unsigned long data)
  549. {
  550. struct request_sock *req = (struct request_sock *)data;
  551. struct sock *sk_listener = req->rsk_listener;
  552. struct inet_connection_sock *icsk = inet_csk(sk_listener);
  553. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  554. struct listen_sock *lopt = queue->listen_opt;
  555. int qlen, expire = 0, resend = 0;
  556. int max_retries, thresh;
  557. u8 defer_accept;
  558. if (sk_listener->sk_state != TCP_LISTEN || !lopt) {
  559. reqsk_put(req);
  560. return;
  561. }
  562. max_retries = icsk->icsk_syn_retries ? : sysctl_tcp_synack_retries;
  563. thresh = max_retries;
  564. /* Normally all the openreqs are young and become mature
  565. * (i.e. converted to established socket) for first timeout.
  566. * If synack was not acknowledged for 1 second, it means
  567. * one of the following things: synack was lost, ack was lost,
  568. * rtt is high or nobody planned to ack (i.e. synflood).
  569. * When server is a bit loaded, queue is populated with old
  570. * open requests, reducing effective size of queue.
  571. * When server is well loaded, queue size reduces to zero
  572. * after several minutes of work. It is not synflood,
  573. * it is normal operation. The solution is pruning
  574. * too old entries overriding normal timeout, when
  575. * situation becomes dangerous.
  576. *
  577. * Essentially, we reserve half of room for young
  578. * embrions; and abort old ones without pity, if old
  579. * ones are about to clog our table.
  580. */
  581. qlen = listen_sock_qlen(lopt);
  582. if (qlen >> (lopt->max_qlen_log - 1)) {
  583. int young = listen_sock_young(lopt) << 1;
  584. while (thresh > 2) {
  585. if (qlen < young)
  586. break;
  587. thresh--;
  588. young <<= 1;
  589. }
  590. }
  591. defer_accept = READ_ONCE(queue->rskq_defer_accept);
  592. if (defer_accept)
  593. max_retries = defer_accept;
  594. syn_ack_recalc(req, thresh, max_retries, defer_accept,
  595. &expire, &resend);
  596. req->rsk_ops->syn_ack_timeout(req);
  597. if (!expire &&
  598. (!resend ||
  599. !inet_rtx_syn_ack(sk_listener, req) ||
  600. inet_rsk(req)->acked)) {
  601. unsigned long timeo;
  602. if (req->num_timeout++ == 0)
  603. atomic_inc(&lopt->young_dec);
  604. timeo = min(TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX);
  605. mod_timer_pinned(&req->rsk_timer, jiffies + timeo);
  606. return;
  607. }
  608. inet_csk_reqsk_queue_drop(sk_listener, req);
  609. reqsk_put(req);
  610. }
  611. void reqsk_queue_hash_req(struct request_sock_queue *queue,
  612. u32 hash, struct request_sock *req,
  613. unsigned long timeout)
  614. {
  615. struct listen_sock *lopt = queue->listen_opt;
  616. req->num_retrans = 0;
  617. req->num_timeout = 0;
  618. req->sk = NULL;
  619. /* before letting lookups find us, make sure all req fields
  620. * are committed to memory and refcnt initialized.
  621. */
  622. smp_wmb();
  623. atomic_set(&req->rsk_refcnt, 2);
  624. setup_timer(&req->rsk_timer, reqsk_timer_handler, (unsigned long)req);
  625. req->rsk_hash = hash;
  626. spin_lock(&queue->syn_wait_lock);
  627. req->dl_next = lopt->syn_table[hash];
  628. lopt->syn_table[hash] = req;
  629. spin_unlock(&queue->syn_wait_lock);
  630. mod_timer_pinned(&req->rsk_timer, jiffies + timeout);
  631. }
  632. EXPORT_SYMBOL(reqsk_queue_hash_req);
  633. /**
  634. * inet_csk_clone_lock - clone an inet socket, and lock its clone
  635. * @sk: the socket to clone
  636. * @req: request_sock
  637. * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
  638. *
  639. * Caller must unlock socket even in error path (bh_unlock_sock(newsk))
  640. */
  641. struct sock *inet_csk_clone_lock(const struct sock *sk,
  642. const struct request_sock *req,
  643. const gfp_t priority)
  644. {
  645. struct sock *newsk = sk_clone_lock(sk, priority);
  646. if (newsk) {
  647. struct inet_connection_sock *newicsk = inet_csk(newsk);
  648. newsk->sk_state = TCP_SYN_RECV;
  649. newicsk->icsk_bind_hash = NULL;
  650. inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
  651. inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
  652. inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
  653. newsk->sk_write_space = sk_stream_write_space;
  654. newsk->sk_mark = inet_rsk(req)->ir_mark;
  655. atomic64_set(&newsk->sk_cookie,
  656. atomic64_read(&inet_rsk(req)->ir_cookie));
  657. newicsk->icsk_retransmits = 0;
  658. newicsk->icsk_backoff = 0;
  659. newicsk->icsk_probes_out = 0;
  660. /* Deinitialize accept_queue to trap illegal accesses. */
  661. memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
  662. security_inet_csk_clone(newsk, req);
  663. }
  664. return newsk;
  665. }
  666. EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
  667. /*
  668. * At this point, there should be no process reference to this
  669. * socket, and thus no user references at all. Therefore we
  670. * can assume the socket waitqueue is inactive and nobody will
  671. * try to jump onto it.
  672. */
  673. void inet_csk_destroy_sock(struct sock *sk)
  674. {
  675. WARN_ON(sk->sk_state != TCP_CLOSE);
  676. WARN_ON(!sock_flag(sk, SOCK_DEAD));
  677. /* It cannot be in hash table! */
  678. WARN_ON(!sk_unhashed(sk));
  679. /* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
  680. WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
  681. sk->sk_prot->destroy(sk);
  682. sk_stream_kill_queues(sk);
  683. xfrm_sk_free_policy(sk);
  684. sk_refcnt_debug_release(sk);
  685. percpu_counter_dec(sk->sk_prot->orphan_count);
  686. sock_put(sk);
  687. }
  688. EXPORT_SYMBOL(inet_csk_destroy_sock);
  689. /* This function allows to force a closure of a socket after the call to
  690. * tcp/dccp_create_openreq_child().
  691. */
  692. void inet_csk_prepare_forced_close(struct sock *sk)
  693. __releases(&sk->sk_lock.slock)
  694. {
  695. /* sk_clone_lock locked the socket and set refcnt to 2 */
  696. bh_unlock_sock(sk);
  697. sock_put(sk);
  698. /* The below has to be done to allow calling inet_csk_destroy_sock */
  699. sock_set_flag(sk, SOCK_DEAD);
  700. percpu_counter_inc(sk->sk_prot->orphan_count);
  701. inet_sk(sk)->inet_num = 0;
  702. }
  703. EXPORT_SYMBOL(inet_csk_prepare_forced_close);
  704. int inet_csk_listen_start(struct sock *sk, const int nr_table_entries)
  705. {
  706. struct inet_sock *inet = inet_sk(sk);
  707. struct inet_connection_sock *icsk = inet_csk(sk);
  708. int rc = reqsk_queue_alloc(&icsk->icsk_accept_queue, nr_table_entries);
  709. if (rc != 0)
  710. return rc;
  711. sk->sk_max_ack_backlog = 0;
  712. sk->sk_ack_backlog = 0;
  713. inet_csk_delack_init(sk);
  714. /* There is race window here: we announce ourselves listening,
  715. * but this transition is still not validated by get_port().
  716. * It is OK, because this socket enters to hash table only
  717. * after validation is complete.
  718. */
  719. sk->sk_state = TCP_LISTEN;
  720. if (!sk->sk_prot->get_port(sk, inet->inet_num)) {
  721. inet->inet_sport = htons(inet->inet_num);
  722. sk_dst_reset(sk);
  723. sk->sk_prot->hash(sk);
  724. return 0;
  725. }
  726. sk->sk_state = TCP_CLOSE;
  727. __reqsk_queue_destroy(&icsk->icsk_accept_queue);
  728. return -EADDRINUSE;
  729. }
  730. EXPORT_SYMBOL_GPL(inet_csk_listen_start);
  731. /*
  732. * This routine closes sockets which have been at least partially
  733. * opened, but not yet accepted.
  734. */
  735. void inet_csk_listen_stop(struct sock *sk)
  736. {
  737. struct inet_connection_sock *icsk = inet_csk(sk);
  738. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  739. struct request_sock *acc_req;
  740. struct request_sock *req;
  741. /* make all the listen_opt local to us */
  742. acc_req = reqsk_queue_yank_acceptq(queue);
  743. /* Following specs, it would be better either to send FIN
  744. * (and enter FIN-WAIT-1, it is normal close)
  745. * or to send active reset (abort).
  746. * Certainly, it is pretty dangerous while synflood, but it is
  747. * bad justification for our negligence 8)
  748. * To be honest, we are not able to make either
  749. * of the variants now. --ANK
  750. */
  751. reqsk_queue_destroy(queue);
  752. while ((req = acc_req) != NULL) {
  753. struct sock *child = req->sk;
  754. acc_req = req->dl_next;
  755. local_bh_disable();
  756. bh_lock_sock(child);
  757. WARN_ON(sock_owned_by_user(child));
  758. sock_hold(child);
  759. sk->sk_prot->disconnect(child, O_NONBLOCK);
  760. sock_orphan(child);
  761. percpu_counter_inc(sk->sk_prot->orphan_count);
  762. if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
  763. BUG_ON(tcp_sk(child)->fastopen_rsk != req);
  764. BUG_ON(sk != req->rsk_listener);
  765. /* Paranoid, to prevent race condition if
  766. * an inbound pkt destined for child is
  767. * blocked by sock lock in tcp_v4_rcv().
  768. * Also to satisfy an assertion in
  769. * tcp_v4_destroy_sock().
  770. */
  771. tcp_sk(child)->fastopen_rsk = NULL;
  772. }
  773. inet_csk_destroy_sock(child);
  774. bh_unlock_sock(child);
  775. local_bh_enable();
  776. sock_put(child);
  777. sk_acceptq_removed(sk);
  778. reqsk_put(req);
  779. }
  780. if (queue->fastopenq) {
  781. /* Free all the reqs queued in rskq_rst_head. */
  782. spin_lock_bh(&queue->fastopenq->lock);
  783. acc_req = queue->fastopenq->rskq_rst_head;
  784. queue->fastopenq->rskq_rst_head = NULL;
  785. spin_unlock_bh(&queue->fastopenq->lock);
  786. while ((req = acc_req) != NULL) {
  787. acc_req = req->dl_next;
  788. reqsk_put(req);
  789. }
  790. }
  791. WARN_ON(sk->sk_ack_backlog);
  792. }
  793. EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
  794. void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
  795. {
  796. struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
  797. const struct inet_sock *inet = inet_sk(sk);
  798. sin->sin_family = AF_INET;
  799. sin->sin_addr.s_addr = inet->inet_daddr;
  800. sin->sin_port = inet->inet_dport;
  801. }
  802. EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
  803. #ifdef CONFIG_COMPAT
  804. int inet_csk_compat_getsockopt(struct sock *sk, int level, int optname,
  805. char __user *optval, int __user *optlen)
  806. {
  807. const struct inet_connection_sock *icsk = inet_csk(sk);
  808. if (icsk->icsk_af_ops->compat_getsockopt)
  809. return icsk->icsk_af_ops->compat_getsockopt(sk, level, optname,
  810. optval, optlen);
  811. return icsk->icsk_af_ops->getsockopt(sk, level, optname,
  812. optval, optlen);
  813. }
  814. EXPORT_SYMBOL_GPL(inet_csk_compat_getsockopt);
  815. int inet_csk_compat_setsockopt(struct sock *sk, int level, int optname,
  816. char __user *optval, unsigned int optlen)
  817. {
  818. const struct inet_connection_sock *icsk = inet_csk(sk);
  819. if (icsk->icsk_af_ops->compat_setsockopt)
  820. return icsk->icsk_af_ops->compat_setsockopt(sk, level, optname,
  821. optval, optlen);
  822. return icsk->icsk_af_ops->setsockopt(sk, level, optname,
  823. optval, optlen);
  824. }
  825. EXPORT_SYMBOL_GPL(inet_csk_compat_setsockopt);
  826. #endif
  827. static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
  828. {
  829. const struct inet_sock *inet = inet_sk(sk);
  830. const struct ip_options_rcu *inet_opt;
  831. __be32 daddr = inet->inet_daddr;
  832. struct flowi4 *fl4;
  833. struct rtable *rt;
  834. rcu_read_lock();
  835. inet_opt = rcu_dereference(inet->inet_opt);
  836. if (inet_opt && inet_opt->opt.srr)
  837. daddr = inet_opt->opt.faddr;
  838. fl4 = &fl->u.ip4;
  839. rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
  840. inet->inet_saddr, inet->inet_dport,
  841. inet->inet_sport, sk->sk_protocol,
  842. RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
  843. if (IS_ERR(rt))
  844. rt = NULL;
  845. if (rt)
  846. sk_setup_caps(sk, &rt->dst);
  847. rcu_read_unlock();
  848. return &rt->dst;
  849. }
  850. struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
  851. {
  852. struct dst_entry *dst = __sk_dst_check(sk, 0);
  853. struct inet_sock *inet = inet_sk(sk);
  854. if (!dst) {
  855. dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
  856. if (!dst)
  857. goto out;
  858. }
  859. dst->ops->update_pmtu(dst, sk, NULL, mtu);
  860. dst = __sk_dst_check(sk, 0);
  861. if (!dst)
  862. dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
  863. out:
  864. return dst;
  865. }
  866. EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);