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