inet_connection_sock.c 31 KB

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