inet_connection_sock.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * INET An implementation of the TCP/IP protocol suite for the LINUX
  4. * operating system. INET is implemented using the BSD Socket
  5. * interface as the means of communication with the user level.
  6. *
  7. * Support for INET connection oriented protocols.
  8. *
  9. * Authors: See the TCP sources
  10. */
  11. #include <linux/module.h>
  12. #include <linux/jhash.h>
  13. #include <net/inet_connection_sock.h>
  14. #include <net/inet_hashtables.h>
  15. #include <net/inet_timewait_sock.h>
  16. #include <net/ip.h>
  17. #include <net/route.h>
  18. #include <net/tcp_states.h>
  19. #include <net/xfrm.h>
  20. #include <net/tcp.h>
  21. #include <net/sock_reuseport.h>
  22. #include <net/addrconf.h>
  23. #if IS_ENABLED(CONFIG_IPV6)
  24. /* match_sk*_wildcard == true: IPV6_ADDR_ANY equals to any IPv6 addresses
  25. * if IPv6 only, and any IPv4 addresses
  26. * if not IPv6 only
  27. * match_sk*_wildcard == false: addresses must be exactly the same, i.e.
  28. * IPV6_ADDR_ANY only equals to IPV6_ADDR_ANY,
  29. * and 0.0.0.0 equals to 0.0.0.0 only
  30. */
  31. static bool ipv6_rcv_saddr_equal(const struct in6_addr *sk1_rcv_saddr6,
  32. const struct in6_addr *sk2_rcv_saddr6,
  33. __be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
  34. bool sk1_ipv6only, bool sk2_ipv6only,
  35. bool match_sk1_wildcard,
  36. bool match_sk2_wildcard)
  37. {
  38. int addr_type = ipv6_addr_type(sk1_rcv_saddr6);
  39. int addr_type2 = sk2_rcv_saddr6 ? ipv6_addr_type(sk2_rcv_saddr6) : IPV6_ADDR_MAPPED;
  40. /* if both are mapped, treat as IPv4 */
  41. if (addr_type == IPV6_ADDR_MAPPED && addr_type2 == IPV6_ADDR_MAPPED) {
  42. if (!sk2_ipv6only) {
  43. if (sk1_rcv_saddr == sk2_rcv_saddr)
  44. return true;
  45. return (match_sk1_wildcard && !sk1_rcv_saddr) ||
  46. (match_sk2_wildcard && !sk2_rcv_saddr);
  47. }
  48. return false;
  49. }
  50. if (addr_type == IPV6_ADDR_ANY && addr_type2 == IPV6_ADDR_ANY)
  51. return true;
  52. if (addr_type2 == IPV6_ADDR_ANY && match_sk2_wildcard &&
  53. !(sk2_ipv6only && addr_type == IPV6_ADDR_MAPPED))
  54. return true;
  55. if (addr_type == IPV6_ADDR_ANY && match_sk1_wildcard &&
  56. !(sk1_ipv6only && addr_type2 == IPV6_ADDR_MAPPED))
  57. return true;
  58. if (sk2_rcv_saddr6 &&
  59. ipv6_addr_equal(sk1_rcv_saddr6, sk2_rcv_saddr6))
  60. return true;
  61. return false;
  62. }
  63. #endif
  64. /* match_sk*_wildcard == true: 0.0.0.0 equals to any IPv4 addresses
  65. * match_sk*_wildcard == false: addresses must be exactly the same, i.e.
  66. * 0.0.0.0 only equals to 0.0.0.0
  67. */
  68. static bool ipv4_rcv_saddr_equal(__be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
  69. bool sk2_ipv6only, bool match_sk1_wildcard,
  70. bool match_sk2_wildcard)
  71. {
  72. if (!sk2_ipv6only) {
  73. if (sk1_rcv_saddr == sk2_rcv_saddr)
  74. return true;
  75. return (match_sk1_wildcard && !sk1_rcv_saddr) ||
  76. (match_sk2_wildcard && !sk2_rcv_saddr);
  77. }
  78. return false;
  79. }
  80. bool inet_rcv_saddr_equal(const struct sock *sk, const struct sock *sk2,
  81. bool match_wildcard)
  82. {
  83. #if IS_ENABLED(CONFIG_IPV6)
  84. if (sk->sk_family == AF_INET6)
  85. return ipv6_rcv_saddr_equal(&sk->sk_v6_rcv_saddr,
  86. inet6_rcv_saddr(sk2),
  87. sk->sk_rcv_saddr,
  88. sk2->sk_rcv_saddr,
  89. ipv6_only_sock(sk),
  90. ipv6_only_sock(sk2),
  91. match_wildcard,
  92. match_wildcard);
  93. #endif
  94. return ipv4_rcv_saddr_equal(sk->sk_rcv_saddr, sk2->sk_rcv_saddr,
  95. ipv6_only_sock(sk2), match_wildcard,
  96. match_wildcard);
  97. }
  98. EXPORT_SYMBOL(inet_rcv_saddr_equal);
  99. bool inet_rcv_saddr_any(const struct sock *sk)
  100. {
  101. #if IS_ENABLED(CONFIG_IPV6)
  102. if (sk->sk_family == AF_INET6)
  103. return ipv6_addr_any(&sk->sk_v6_rcv_saddr);
  104. #endif
  105. return !sk->sk_rcv_saddr;
  106. }
  107. /**
  108. * inet_sk_get_local_port_range - fetch ephemeral ports range
  109. * @sk: socket
  110. * @low: pointer to low port
  111. * @high: pointer to high port
  112. *
  113. * Fetch netns port range (/proc/sys/net/ipv4/ip_local_port_range)
  114. * Range can be overridden if socket got IP_LOCAL_PORT_RANGE option.
  115. * Returns true if IP_LOCAL_PORT_RANGE was set on this socket.
  116. */
  117. bool inet_sk_get_local_port_range(const struct sock *sk, int *low, int *high)
  118. {
  119. int lo, hi, sk_lo, sk_hi;
  120. bool local_range = false;
  121. u32 sk_range;
  122. inet_get_local_port_range(sock_net(sk), &lo, &hi);
  123. sk_range = READ_ONCE(inet_sk(sk)->local_port_range);
  124. if (unlikely(sk_range)) {
  125. sk_lo = sk_range & 0xffff;
  126. sk_hi = sk_range >> 16;
  127. if (lo <= sk_lo && sk_lo <= hi)
  128. lo = sk_lo;
  129. if (lo <= sk_hi && sk_hi <= hi)
  130. hi = sk_hi;
  131. local_range = true;
  132. }
  133. *low = lo;
  134. *high = hi;
  135. return local_range;
  136. }
  137. EXPORT_SYMBOL(inet_sk_get_local_port_range);
  138. static bool inet_use_bhash2_on_bind(const struct sock *sk)
  139. {
  140. #if IS_ENABLED(CONFIG_IPV6)
  141. if (sk->sk_family == AF_INET6) {
  142. int addr_type = ipv6_addr_type(&sk->sk_v6_rcv_saddr);
  143. if (addr_type == IPV6_ADDR_ANY)
  144. return false;
  145. if (addr_type != IPV6_ADDR_MAPPED)
  146. return true;
  147. }
  148. #endif
  149. return sk->sk_rcv_saddr != htonl(INADDR_ANY);
  150. }
  151. static bool inet_bind_conflict(const struct sock *sk, struct sock *sk2,
  152. kuid_t sk_uid, bool relax,
  153. bool reuseport_cb_ok, bool reuseport_ok)
  154. {
  155. int bound_dev_if2;
  156. if (sk == sk2)
  157. return false;
  158. bound_dev_if2 = READ_ONCE(sk2->sk_bound_dev_if);
  159. if (!sk->sk_bound_dev_if || !bound_dev_if2 ||
  160. sk->sk_bound_dev_if == bound_dev_if2) {
  161. if (sk->sk_reuse && sk2->sk_reuse &&
  162. sk2->sk_state != TCP_LISTEN) {
  163. if (!relax || (!reuseport_ok && sk->sk_reuseport &&
  164. sk2->sk_reuseport && reuseport_cb_ok &&
  165. (sk2->sk_state == TCP_TIME_WAIT ||
  166. uid_eq(sk_uid, sock_i_uid(sk2)))))
  167. return true;
  168. } else if (!reuseport_ok || !sk->sk_reuseport ||
  169. !sk2->sk_reuseport || !reuseport_cb_ok ||
  170. (sk2->sk_state != TCP_TIME_WAIT &&
  171. !uid_eq(sk_uid, sock_i_uid(sk2)))) {
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. static bool __inet_bhash2_conflict(const struct sock *sk, struct sock *sk2,
  178. kuid_t sk_uid, bool relax,
  179. bool reuseport_cb_ok, bool reuseport_ok)
  180. {
  181. if (ipv6_only_sock(sk2)) {
  182. if (sk->sk_family == AF_INET)
  183. return false;
  184. #if IS_ENABLED(CONFIG_IPV6)
  185. if (ipv6_addr_v4mapped(&sk->sk_v6_rcv_saddr))
  186. return false;
  187. #endif
  188. }
  189. return inet_bind_conflict(sk, sk2, sk_uid, relax,
  190. reuseport_cb_ok, reuseport_ok);
  191. }
  192. static bool inet_bhash2_conflict(const struct sock *sk,
  193. const struct inet_bind2_bucket *tb2,
  194. kuid_t sk_uid,
  195. bool relax, bool reuseport_cb_ok,
  196. bool reuseport_ok)
  197. {
  198. struct sock *sk2;
  199. sk_for_each_bound(sk2, &tb2->owners) {
  200. if (__inet_bhash2_conflict(sk, sk2, sk_uid, relax,
  201. reuseport_cb_ok, reuseport_ok))
  202. return true;
  203. }
  204. return false;
  205. }
  206. #define sk_for_each_bound_bhash(__sk, __tb2, __tb) \
  207. hlist_for_each_entry(__tb2, &(__tb)->bhash2, bhash_node) \
  208. sk_for_each_bound((__sk), &(__tb2)->owners)
  209. /* This should be called only when the tb and tb2 hashbuckets' locks are held */
  210. static int inet_csk_bind_conflict(const struct sock *sk,
  211. const struct inet_bind_bucket *tb,
  212. const struct inet_bind2_bucket *tb2, /* may be null */
  213. bool relax, bool reuseport_ok)
  214. {
  215. kuid_t uid = sock_i_uid((struct sock *)sk);
  216. struct sock_reuseport *reuseport_cb;
  217. bool reuseport_cb_ok;
  218. struct sock *sk2;
  219. rcu_read_lock();
  220. reuseport_cb = rcu_dereference(sk->sk_reuseport_cb);
  221. /* paired with WRITE_ONCE() in __reuseport_(add|detach)_closed_sock */
  222. reuseport_cb_ok = !reuseport_cb || READ_ONCE(reuseport_cb->num_closed_socks);
  223. rcu_read_unlock();
  224. /* Conflicts with an existing IPV6_ADDR_ANY (if ipv6) or INADDR_ANY (if
  225. * ipv4) should have been checked already. We need to do these two
  226. * checks separately because their spinlocks have to be acquired/released
  227. * independently of each other, to prevent possible deadlocks
  228. */
  229. if (inet_use_bhash2_on_bind(sk))
  230. return tb2 && inet_bhash2_conflict(sk, tb2, uid, relax,
  231. reuseport_cb_ok, reuseport_ok);
  232. /* Unlike other sk lookup places we do not check
  233. * for sk_net here, since _all_ the socks listed
  234. * in tb->owners and tb2->owners list belong
  235. * to the same net - the one this bucket belongs to.
  236. */
  237. sk_for_each_bound_bhash(sk2, tb2, tb) {
  238. if (!inet_bind_conflict(sk, sk2, uid, relax, reuseport_cb_ok, reuseport_ok))
  239. continue;
  240. if (inet_rcv_saddr_equal(sk, sk2, true))
  241. return true;
  242. }
  243. return false;
  244. }
  245. /* Determine if there is a bind conflict with an existing IPV6_ADDR_ANY (if ipv6) or
  246. * INADDR_ANY (if ipv4) socket.
  247. *
  248. * Caller must hold bhash hashbucket lock with local bh disabled, to protect
  249. * against concurrent binds on the port for addr any
  250. */
  251. static bool inet_bhash2_addr_any_conflict(const struct sock *sk, int port, int l3mdev,
  252. bool relax, bool reuseport_ok)
  253. {
  254. kuid_t uid = sock_i_uid((struct sock *)sk);
  255. const struct net *net = sock_net(sk);
  256. struct sock_reuseport *reuseport_cb;
  257. struct inet_bind_hashbucket *head2;
  258. struct inet_bind2_bucket *tb2;
  259. bool conflict = false;
  260. bool reuseport_cb_ok;
  261. rcu_read_lock();
  262. reuseport_cb = rcu_dereference(sk->sk_reuseport_cb);
  263. /* paired with WRITE_ONCE() in __reuseport_(add|detach)_closed_sock */
  264. reuseport_cb_ok = !reuseport_cb || READ_ONCE(reuseport_cb->num_closed_socks);
  265. rcu_read_unlock();
  266. head2 = inet_bhash2_addr_any_hashbucket(sk, net, port);
  267. spin_lock(&head2->lock);
  268. inet_bind_bucket_for_each(tb2, &head2->chain) {
  269. if (!inet_bind2_bucket_match_addr_any(tb2, net, port, l3mdev, sk))
  270. continue;
  271. if (!inet_bhash2_conflict(sk, tb2, uid, relax, reuseport_cb_ok, reuseport_ok))
  272. continue;
  273. conflict = true;
  274. break;
  275. }
  276. spin_unlock(&head2->lock);
  277. return conflict;
  278. }
  279. /*
  280. * Find an open port number for the socket. Returns with the
  281. * inet_bind_hashbucket locks held if successful.
  282. */
  283. static struct inet_bind_hashbucket *
  284. inet_csk_find_open_port(const struct sock *sk, struct inet_bind_bucket **tb_ret,
  285. struct inet_bind2_bucket **tb2_ret,
  286. struct inet_bind_hashbucket **head2_ret, int *port_ret)
  287. {
  288. struct inet_hashinfo *hinfo = tcp_or_dccp_get_hashinfo(sk);
  289. int i, low, high, attempt_half, port, l3mdev;
  290. struct inet_bind_hashbucket *head, *head2;
  291. struct net *net = sock_net(sk);
  292. struct inet_bind2_bucket *tb2;
  293. struct inet_bind_bucket *tb;
  294. u32 remaining, offset;
  295. bool relax = false;
  296. l3mdev = inet_sk_bound_l3mdev(sk);
  297. ports_exhausted:
  298. attempt_half = (sk->sk_reuse == SK_CAN_REUSE) ? 1 : 0;
  299. other_half_scan:
  300. inet_sk_get_local_port_range(sk, &low, &high);
  301. high++; /* [32768, 60999] -> [32768, 61000[ */
  302. if (high - low < 4)
  303. attempt_half = 0;
  304. if (attempt_half) {
  305. int half = low + (((high - low) >> 2) << 1);
  306. if (attempt_half == 1)
  307. high = half;
  308. else
  309. low = half;
  310. }
  311. remaining = high - low;
  312. if (likely(remaining > 1))
  313. remaining &= ~1U;
  314. offset = get_random_u32_below(remaining);
  315. /* __inet_hash_connect() favors ports having @low parity
  316. * We do the opposite to not pollute connect() users.
  317. */
  318. offset |= 1U;
  319. other_parity_scan:
  320. port = low + offset;
  321. for (i = 0; i < remaining; i += 2, port += 2) {
  322. if (unlikely(port >= high))
  323. port -= remaining;
  324. if (inet_is_local_reserved_port(net, port))
  325. continue;
  326. head = &hinfo->bhash[inet_bhashfn(net, port,
  327. hinfo->bhash_size)];
  328. spin_lock_bh(&head->lock);
  329. if (inet_use_bhash2_on_bind(sk)) {
  330. if (inet_bhash2_addr_any_conflict(sk, port, l3mdev, relax, false))
  331. goto next_port;
  332. }
  333. head2 = inet_bhashfn_portaddr(hinfo, sk, net, port);
  334. spin_lock(&head2->lock);
  335. tb2 = inet_bind2_bucket_find(head2, net, port, l3mdev, sk);
  336. inet_bind_bucket_for_each(tb, &head->chain)
  337. if (inet_bind_bucket_match(tb, net, port, l3mdev)) {
  338. if (!inet_csk_bind_conflict(sk, tb, tb2,
  339. relax, false))
  340. goto success;
  341. spin_unlock(&head2->lock);
  342. goto next_port;
  343. }
  344. tb = NULL;
  345. goto success;
  346. next_port:
  347. spin_unlock_bh(&head->lock);
  348. cond_resched();
  349. }
  350. offset--;
  351. if (!(offset & 1))
  352. goto other_parity_scan;
  353. if (attempt_half == 1) {
  354. /* OK we now try the upper half of the range */
  355. attempt_half = 2;
  356. goto other_half_scan;
  357. }
  358. if (READ_ONCE(net->ipv4.sysctl_ip_autobind_reuse) && !relax) {
  359. /* We still have a chance to connect to different destinations */
  360. relax = true;
  361. goto ports_exhausted;
  362. }
  363. return NULL;
  364. success:
  365. *port_ret = port;
  366. *tb_ret = tb;
  367. *tb2_ret = tb2;
  368. *head2_ret = head2;
  369. return head;
  370. }
  371. static inline int sk_reuseport_match(struct inet_bind_bucket *tb,
  372. struct sock *sk)
  373. {
  374. kuid_t uid = sock_i_uid(sk);
  375. if (tb->fastreuseport <= 0)
  376. return 0;
  377. if (!sk->sk_reuseport)
  378. return 0;
  379. if (rcu_access_pointer(sk->sk_reuseport_cb))
  380. return 0;
  381. if (!uid_eq(tb->fastuid, uid))
  382. return 0;
  383. /* We only need to check the rcv_saddr if this tb was once marked
  384. * without fastreuseport and then was reset, as we can only know that
  385. * the fast_*rcv_saddr doesn't have any conflicts with the socks on the
  386. * owners list.
  387. */
  388. if (tb->fastreuseport == FASTREUSEPORT_ANY)
  389. return 1;
  390. #if IS_ENABLED(CONFIG_IPV6)
  391. if (tb->fast_sk_family == AF_INET6)
  392. return ipv6_rcv_saddr_equal(&tb->fast_v6_rcv_saddr,
  393. inet6_rcv_saddr(sk),
  394. tb->fast_rcv_saddr,
  395. sk->sk_rcv_saddr,
  396. tb->fast_ipv6_only,
  397. ipv6_only_sock(sk), true, false);
  398. #endif
  399. return ipv4_rcv_saddr_equal(tb->fast_rcv_saddr, sk->sk_rcv_saddr,
  400. ipv6_only_sock(sk), true, false);
  401. }
  402. void inet_csk_update_fastreuse(struct inet_bind_bucket *tb,
  403. struct sock *sk)
  404. {
  405. kuid_t uid = sock_i_uid(sk);
  406. bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
  407. if (hlist_empty(&tb->bhash2)) {
  408. tb->fastreuse = reuse;
  409. if (sk->sk_reuseport) {
  410. tb->fastreuseport = FASTREUSEPORT_ANY;
  411. tb->fastuid = uid;
  412. tb->fast_rcv_saddr = sk->sk_rcv_saddr;
  413. tb->fast_ipv6_only = ipv6_only_sock(sk);
  414. tb->fast_sk_family = sk->sk_family;
  415. #if IS_ENABLED(CONFIG_IPV6)
  416. tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
  417. #endif
  418. } else {
  419. tb->fastreuseport = 0;
  420. }
  421. } else {
  422. if (!reuse)
  423. tb->fastreuse = 0;
  424. if (sk->sk_reuseport) {
  425. /* We didn't match or we don't have fastreuseport set on
  426. * the tb, but we have sk_reuseport set on this socket
  427. * and we know that there are no bind conflicts with
  428. * this socket in this tb, so reset our tb's reuseport
  429. * settings so that any subsequent sockets that match
  430. * our current socket will be put on the fast path.
  431. *
  432. * If we reset we need to set FASTREUSEPORT_STRICT so we
  433. * do extra checking for all subsequent sk_reuseport
  434. * socks.
  435. */
  436. if (!sk_reuseport_match(tb, sk)) {
  437. tb->fastreuseport = FASTREUSEPORT_STRICT;
  438. tb->fastuid = uid;
  439. tb->fast_rcv_saddr = sk->sk_rcv_saddr;
  440. tb->fast_ipv6_only = ipv6_only_sock(sk);
  441. tb->fast_sk_family = sk->sk_family;
  442. #if IS_ENABLED(CONFIG_IPV6)
  443. tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
  444. #endif
  445. }
  446. } else {
  447. tb->fastreuseport = 0;
  448. }
  449. }
  450. }
  451. /* Obtain a reference to a local port for the given sock,
  452. * if snum is zero it means select any available local port.
  453. * We try to allocate an odd port (and leave even ports for connect())
  454. */
  455. int inet_csk_get_port(struct sock *sk, unsigned short snum)
  456. {
  457. struct inet_hashinfo *hinfo = tcp_or_dccp_get_hashinfo(sk);
  458. bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
  459. bool found_port = false, check_bind_conflict = true;
  460. bool bhash_created = false, bhash2_created = false;
  461. int ret = -EADDRINUSE, port = snum, l3mdev;
  462. struct inet_bind_hashbucket *head, *head2;
  463. struct inet_bind2_bucket *tb2 = NULL;
  464. struct inet_bind_bucket *tb = NULL;
  465. bool head2_lock_acquired = false;
  466. struct net *net = sock_net(sk);
  467. l3mdev = inet_sk_bound_l3mdev(sk);
  468. if (!port) {
  469. head = inet_csk_find_open_port(sk, &tb, &tb2, &head2, &port);
  470. if (!head)
  471. return ret;
  472. head2_lock_acquired = true;
  473. if (tb && tb2)
  474. goto success;
  475. found_port = true;
  476. } else {
  477. head = &hinfo->bhash[inet_bhashfn(net, port,
  478. hinfo->bhash_size)];
  479. spin_lock_bh(&head->lock);
  480. inet_bind_bucket_for_each(tb, &head->chain)
  481. if (inet_bind_bucket_match(tb, net, port, l3mdev))
  482. break;
  483. }
  484. if (!tb) {
  485. tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep, net,
  486. head, port, l3mdev);
  487. if (!tb)
  488. goto fail_unlock;
  489. bhash_created = true;
  490. }
  491. if (!found_port) {
  492. if (!hlist_empty(&tb->bhash2)) {
  493. if (sk->sk_reuse == SK_FORCE_REUSE ||
  494. (tb->fastreuse > 0 && reuse) ||
  495. sk_reuseport_match(tb, sk))
  496. check_bind_conflict = false;
  497. }
  498. if (check_bind_conflict && inet_use_bhash2_on_bind(sk)) {
  499. if (inet_bhash2_addr_any_conflict(sk, port, l3mdev, true, true))
  500. goto fail_unlock;
  501. }
  502. head2 = inet_bhashfn_portaddr(hinfo, sk, net, port);
  503. spin_lock(&head2->lock);
  504. head2_lock_acquired = true;
  505. tb2 = inet_bind2_bucket_find(head2, net, port, l3mdev, sk);
  506. }
  507. if (!tb2) {
  508. tb2 = inet_bind2_bucket_create(hinfo->bind2_bucket_cachep,
  509. net, head2, tb, sk);
  510. if (!tb2)
  511. goto fail_unlock;
  512. bhash2_created = true;
  513. }
  514. if (!found_port && check_bind_conflict) {
  515. if (inet_csk_bind_conflict(sk, tb, tb2, true, true))
  516. goto fail_unlock;
  517. }
  518. success:
  519. inet_csk_update_fastreuse(tb, sk);
  520. if (!inet_csk(sk)->icsk_bind_hash)
  521. inet_bind_hash(sk, tb, tb2, port);
  522. WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
  523. WARN_ON(inet_csk(sk)->icsk_bind2_hash != tb2);
  524. ret = 0;
  525. fail_unlock:
  526. if (ret) {
  527. if (bhash2_created)
  528. inet_bind2_bucket_destroy(hinfo->bind2_bucket_cachep, tb2);
  529. if (bhash_created)
  530. inet_bind_bucket_destroy(hinfo->bind_bucket_cachep, tb);
  531. }
  532. if (head2_lock_acquired)
  533. spin_unlock(&head2->lock);
  534. spin_unlock_bh(&head->lock);
  535. return ret;
  536. }
  537. EXPORT_SYMBOL_GPL(inet_csk_get_port);
  538. /*
  539. * Wait for an incoming connection, avoid race conditions. This must be called
  540. * with the socket locked.
  541. */
  542. static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
  543. {
  544. struct inet_connection_sock *icsk = inet_csk(sk);
  545. DEFINE_WAIT(wait);
  546. int err;
  547. /*
  548. * True wake-one mechanism for incoming connections: only
  549. * one process gets woken up, not the 'whole herd'.
  550. * Since we do not 'race & poll' for established sockets
  551. * anymore, the common case will execute the loop only once.
  552. *
  553. * Subtle issue: "add_wait_queue_exclusive()" will be added
  554. * after any current non-exclusive waiters, and we know that
  555. * it will always _stay_ after any new non-exclusive waiters
  556. * because all non-exclusive waiters are added at the
  557. * beginning of the wait-queue. As such, it's ok to "drop"
  558. * our exclusiveness temporarily when we get woken up without
  559. * having to remove and re-insert us on the wait queue.
  560. */
  561. for (;;) {
  562. prepare_to_wait_exclusive(sk_sleep(sk), &wait,
  563. TASK_INTERRUPTIBLE);
  564. release_sock(sk);
  565. if (reqsk_queue_empty(&icsk->icsk_accept_queue))
  566. timeo = schedule_timeout(timeo);
  567. sched_annotate_sleep();
  568. lock_sock(sk);
  569. err = 0;
  570. if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
  571. break;
  572. err = -EINVAL;
  573. if (sk->sk_state != TCP_LISTEN)
  574. break;
  575. err = sock_intr_errno(timeo);
  576. if (signal_pending(current))
  577. break;
  578. err = -EAGAIN;
  579. if (!timeo)
  580. break;
  581. }
  582. finish_wait(sk_sleep(sk), &wait);
  583. return err;
  584. }
  585. /*
  586. * This will accept the next outstanding connection.
  587. */
  588. struct sock *inet_csk_accept(struct sock *sk, struct proto_accept_arg *arg)
  589. {
  590. struct inet_connection_sock *icsk = inet_csk(sk);
  591. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  592. struct request_sock *req;
  593. struct sock *newsk;
  594. int error;
  595. lock_sock(sk);
  596. /* We need to make sure that this socket is listening,
  597. * and that it has something pending.
  598. */
  599. error = -EINVAL;
  600. if (sk->sk_state != TCP_LISTEN)
  601. goto out_err;
  602. /* Find already established connection */
  603. if (reqsk_queue_empty(queue)) {
  604. long timeo = sock_rcvtimeo(sk, arg->flags & O_NONBLOCK);
  605. /* If this is a non blocking socket don't sleep */
  606. error = -EAGAIN;
  607. if (!timeo)
  608. goto out_err;
  609. error = inet_csk_wait_for_connect(sk, timeo);
  610. if (error)
  611. goto out_err;
  612. }
  613. req = reqsk_queue_remove(queue, sk);
  614. arg->is_empty = reqsk_queue_empty(queue);
  615. newsk = req->sk;
  616. if (sk->sk_protocol == IPPROTO_TCP &&
  617. tcp_rsk(req)->tfo_listener) {
  618. spin_lock_bh(&queue->fastopenq.lock);
  619. if (tcp_rsk(req)->tfo_listener) {
  620. /* We are still waiting for the final ACK from 3WHS
  621. * so can't free req now. Instead, we set req->sk to
  622. * NULL to signify that the child socket is taken
  623. * so reqsk_fastopen_remove() will free the req
  624. * when 3WHS finishes (or is aborted).
  625. */
  626. req->sk = NULL;
  627. req = NULL;
  628. }
  629. spin_unlock_bh(&queue->fastopenq.lock);
  630. }
  631. out:
  632. release_sock(sk);
  633. if (newsk && mem_cgroup_sockets_enabled) {
  634. gfp_t gfp = GFP_KERNEL | __GFP_NOFAIL;
  635. int amt = 0;
  636. /* atomically get the memory usage, set and charge the
  637. * newsk->sk_memcg.
  638. */
  639. lock_sock(newsk);
  640. mem_cgroup_sk_alloc(newsk);
  641. if (newsk->sk_memcg) {
  642. /* The socket has not been accepted yet, no need
  643. * to look at newsk->sk_wmem_queued.
  644. */
  645. amt = sk_mem_pages(newsk->sk_forward_alloc +
  646. atomic_read(&newsk->sk_rmem_alloc));
  647. }
  648. if (amt)
  649. mem_cgroup_charge_skmem(newsk->sk_memcg, amt, gfp);
  650. kmem_cache_charge(newsk, gfp);
  651. release_sock(newsk);
  652. }
  653. if (req)
  654. reqsk_put(req);
  655. if (newsk)
  656. inet_init_csk_locks(newsk);
  657. return newsk;
  658. out_err:
  659. newsk = NULL;
  660. req = NULL;
  661. arg->err = error;
  662. goto out;
  663. }
  664. EXPORT_SYMBOL(inet_csk_accept);
  665. /*
  666. * Using different timers for retransmit, delayed acks and probes
  667. * We may wish use just one timer maintaining a list of expire jiffies
  668. * to optimize.
  669. */
  670. void inet_csk_init_xmit_timers(struct sock *sk,
  671. void (*retransmit_handler)(struct timer_list *t),
  672. void (*delack_handler)(struct timer_list *t),
  673. void (*keepalive_handler)(struct timer_list *t))
  674. {
  675. struct inet_connection_sock *icsk = inet_csk(sk);
  676. timer_setup(&icsk->icsk_retransmit_timer, retransmit_handler, 0);
  677. timer_setup(&icsk->icsk_delack_timer, delack_handler, 0);
  678. timer_setup(&sk->sk_timer, keepalive_handler, 0);
  679. icsk->icsk_pending = icsk->icsk_ack.pending = 0;
  680. }
  681. EXPORT_SYMBOL(inet_csk_init_xmit_timers);
  682. void inet_csk_clear_xmit_timers(struct sock *sk)
  683. {
  684. struct inet_connection_sock *icsk = inet_csk(sk);
  685. icsk->icsk_pending = icsk->icsk_ack.pending = 0;
  686. sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
  687. sk_stop_timer(sk, &icsk->icsk_delack_timer);
  688. sk_stop_timer(sk, &sk->sk_timer);
  689. }
  690. EXPORT_SYMBOL(inet_csk_clear_xmit_timers);
  691. void inet_csk_clear_xmit_timers_sync(struct sock *sk)
  692. {
  693. struct inet_connection_sock *icsk = inet_csk(sk);
  694. /* ongoing timer handlers need to acquire socket lock. */
  695. sock_not_owned_by_me(sk);
  696. icsk->icsk_pending = icsk->icsk_ack.pending = 0;
  697. sk_stop_timer_sync(sk, &icsk->icsk_retransmit_timer);
  698. sk_stop_timer_sync(sk, &icsk->icsk_delack_timer);
  699. sk_stop_timer_sync(sk, &sk->sk_timer);
  700. }
  701. void inet_csk_delete_keepalive_timer(struct sock *sk)
  702. {
  703. sk_stop_timer(sk, &sk->sk_timer);
  704. }
  705. EXPORT_SYMBOL(inet_csk_delete_keepalive_timer);
  706. void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len)
  707. {
  708. sk_reset_timer(sk, &sk->sk_timer, jiffies + len);
  709. }
  710. EXPORT_SYMBOL(inet_csk_reset_keepalive_timer);
  711. struct dst_entry *inet_csk_route_req(const struct sock *sk,
  712. struct flowi4 *fl4,
  713. const struct request_sock *req)
  714. {
  715. const struct inet_request_sock *ireq = inet_rsk(req);
  716. struct net *net = read_pnet(&ireq->ireq_net);
  717. struct ip_options_rcu *opt;
  718. struct rtable *rt;
  719. rcu_read_lock();
  720. opt = rcu_dereference(ireq->ireq_opt);
  721. flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
  722. ip_sock_rt_tos(sk), ip_sock_rt_scope(sk),
  723. sk->sk_protocol, inet_sk_flowi_flags(sk),
  724. (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
  725. ireq->ir_loc_addr, ireq->ir_rmt_port,
  726. htons(ireq->ir_num), sk->sk_uid);
  727. security_req_classify_flow(req, flowi4_to_flowi_common(fl4));
  728. rt = ip_route_output_flow(net, fl4, sk);
  729. if (IS_ERR(rt))
  730. goto no_route;
  731. if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
  732. goto route_err;
  733. rcu_read_unlock();
  734. return &rt->dst;
  735. route_err:
  736. ip_rt_put(rt);
  737. no_route:
  738. rcu_read_unlock();
  739. __IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
  740. return NULL;
  741. }
  742. EXPORT_SYMBOL_GPL(inet_csk_route_req);
  743. struct dst_entry *inet_csk_route_child_sock(const struct sock *sk,
  744. struct sock *newsk,
  745. const struct request_sock *req)
  746. {
  747. const struct inet_request_sock *ireq = inet_rsk(req);
  748. struct net *net = read_pnet(&ireq->ireq_net);
  749. struct inet_sock *newinet = inet_sk(newsk);
  750. struct ip_options_rcu *opt;
  751. struct flowi4 *fl4;
  752. struct rtable *rt;
  753. opt = rcu_dereference(ireq->ireq_opt);
  754. fl4 = &newinet->cork.fl.u.ip4;
  755. flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
  756. ip_sock_rt_tos(sk), ip_sock_rt_scope(sk),
  757. sk->sk_protocol, inet_sk_flowi_flags(sk),
  758. (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
  759. ireq->ir_loc_addr, ireq->ir_rmt_port,
  760. htons(ireq->ir_num), sk->sk_uid);
  761. security_req_classify_flow(req, flowi4_to_flowi_common(fl4));
  762. rt = ip_route_output_flow(net, fl4, sk);
  763. if (IS_ERR(rt))
  764. goto no_route;
  765. if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
  766. goto route_err;
  767. return &rt->dst;
  768. route_err:
  769. ip_rt_put(rt);
  770. no_route:
  771. __IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
  772. return NULL;
  773. }
  774. EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);
  775. /* Decide when to expire the request and when to resend SYN-ACK */
  776. static void syn_ack_recalc(struct request_sock *req,
  777. const int max_syn_ack_retries,
  778. const u8 rskq_defer_accept,
  779. int *expire, int *resend)
  780. {
  781. if (!rskq_defer_accept) {
  782. *expire = req->num_timeout >= max_syn_ack_retries;
  783. *resend = 1;
  784. return;
  785. }
  786. *expire = req->num_timeout >= max_syn_ack_retries &&
  787. (!inet_rsk(req)->acked || req->num_timeout >= rskq_defer_accept);
  788. /* Do not resend while waiting for data after ACK,
  789. * start to resend on end of deferring period to give
  790. * last chance for data or ACK to create established socket.
  791. */
  792. *resend = !inet_rsk(req)->acked ||
  793. req->num_timeout >= rskq_defer_accept - 1;
  794. }
  795. int inet_rtx_syn_ack(const struct sock *parent, struct request_sock *req)
  796. {
  797. int err = req->rsk_ops->rtx_syn_ack(parent, req);
  798. if (!err)
  799. req->num_retrans++;
  800. return err;
  801. }
  802. EXPORT_SYMBOL(inet_rtx_syn_ack);
  803. static struct request_sock *
  804. reqsk_alloc_noprof(const struct request_sock_ops *ops, struct sock *sk_listener,
  805. bool attach_listener)
  806. {
  807. struct request_sock *req;
  808. req = kmem_cache_alloc_noprof(ops->slab, GFP_ATOMIC | __GFP_NOWARN);
  809. if (!req)
  810. return NULL;
  811. req->rsk_listener = NULL;
  812. if (attach_listener) {
  813. if (unlikely(!refcount_inc_not_zero(&sk_listener->sk_refcnt))) {
  814. kmem_cache_free(ops->slab, req);
  815. return NULL;
  816. }
  817. req->rsk_listener = sk_listener;
  818. }
  819. req->rsk_ops = ops;
  820. req_to_sk(req)->sk_prot = sk_listener->sk_prot;
  821. sk_node_init(&req_to_sk(req)->sk_node);
  822. sk_tx_queue_clear(req_to_sk(req));
  823. req->saved_syn = NULL;
  824. req->syncookie = 0;
  825. req->timeout = 0;
  826. req->num_timeout = 0;
  827. req->num_retrans = 0;
  828. req->sk = NULL;
  829. refcount_set(&req->rsk_refcnt, 0);
  830. return req;
  831. }
  832. #define reqsk_alloc(...) alloc_hooks(reqsk_alloc_noprof(__VA_ARGS__))
  833. struct request_sock *inet_reqsk_alloc(const struct request_sock_ops *ops,
  834. struct sock *sk_listener,
  835. bool attach_listener)
  836. {
  837. struct request_sock *req = reqsk_alloc(ops, sk_listener,
  838. attach_listener);
  839. if (req) {
  840. struct inet_request_sock *ireq = inet_rsk(req);
  841. ireq->ireq_opt = NULL;
  842. #if IS_ENABLED(CONFIG_IPV6)
  843. ireq->pktopts = NULL;
  844. #endif
  845. atomic64_set(&ireq->ir_cookie, 0);
  846. ireq->ireq_state = TCP_NEW_SYN_RECV;
  847. write_pnet(&ireq->ireq_net, sock_net(sk_listener));
  848. ireq->ireq_family = sk_listener->sk_family;
  849. req->timeout = TCP_TIMEOUT_INIT;
  850. }
  851. return req;
  852. }
  853. EXPORT_SYMBOL(inet_reqsk_alloc);
  854. static struct request_sock *inet_reqsk_clone(struct request_sock *req,
  855. struct sock *sk)
  856. {
  857. struct sock *req_sk, *nreq_sk;
  858. struct request_sock *nreq;
  859. nreq = kmem_cache_alloc(req->rsk_ops->slab, GFP_ATOMIC | __GFP_NOWARN);
  860. if (!nreq) {
  861. __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMIGRATEREQFAILURE);
  862. /* paired with refcount_inc_not_zero() in reuseport_migrate_sock() */
  863. sock_put(sk);
  864. return NULL;
  865. }
  866. req_sk = req_to_sk(req);
  867. nreq_sk = req_to_sk(nreq);
  868. memcpy(nreq_sk, req_sk,
  869. offsetof(struct sock, sk_dontcopy_begin));
  870. unsafe_memcpy(&nreq_sk->sk_dontcopy_end, &req_sk->sk_dontcopy_end,
  871. req->rsk_ops->obj_size - offsetof(struct sock, sk_dontcopy_end),
  872. /* alloc is larger than struct, see above */);
  873. sk_node_init(&nreq_sk->sk_node);
  874. nreq_sk->sk_tx_queue_mapping = req_sk->sk_tx_queue_mapping;
  875. #ifdef CONFIG_SOCK_RX_QUEUE_MAPPING
  876. nreq_sk->sk_rx_queue_mapping = req_sk->sk_rx_queue_mapping;
  877. #endif
  878. nreq_sk->sk_incoming_cpu = req_sk->sk_incoming_cpu;
  879. nreq->rsk_listener = sk;
  880. /* We need not acquire fastopenq->lock
  881. * because the child socket is locked in inet_csk_listen_stop().
  882. */
  883. if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(nreq)->tfo_listener)
  884. rcu_assign_pointer(tcp_sk(nreq->sk)->fastopen_rsk, nreq);
  885. return nreq;
  886. }
  887. static void reqsk_queue_migrated(struct request_sock_queue *queue,
  888. const struct request_sock *req)
  889. {
  890. if (req->num_timeout == 0)
  891. atomic_inc(&queue->young);
  892. atomic_inc(&queue->qlen);
  893. }
  894. static void reqsk_migrate_reset(struct request_sock *req)
  895. {
  896. req->saved_syn = NULL;
  897. #if IS_ENABLED(CONFIG_IPV6)
  898. inet_rsk(req)->ipv6_opt = NULL;
  899. inet_rsk(req)->pktopts = NULL;
  900. #else
  901. inet_rsk(req)->ireq_opt = NULL;
  902. #endif
  903. }
  904. /* return true if req was found in the ehash table */
  905. static bool reqsk_queue_unlink(struct request_sock *req)
  906. {
  907. struct sock *sk = req_to_sk(req);
  908. bool found = false;
  909. if (sk_hashed(sk)) {
  910. struct inet_hashinfo *hashinfo = tcp_or_dccp_get_hashinfo(sk);
  911. spinlock_t *lock = inet_ehash_lockp(hashinfo, req->rsk_hash);
  912. spin_lock(lock);
  913. found = __sk_nulls_del_node_init_rcu(sk);
  914. spin_unlock(lock);
  915. }
  916. return found;
  917. }
  918. static bool __inet_csk_reqsk_queue_drop(struct sock *sk,
  919. struct request_sock *req,
  920. bool from_timer)
  921. {
  922. bool unlinked = reqsk_queue_unlink(req);
  923. if (!from_timer && timer_delete_sync(&req->rsk_timer))
  924. reqsk_put(req);
  925. if (unlinked) {
  926. reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
  927. reqsk_put(req);
  928. }
  929. return unlinked;
  930. }
  931. bool inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req)
  932. {
  933. return __inet_csk_reqsk_queue_drop(sk, req, false);
  934. }
  935. EXPORT_SYMBOL(inet_csk_reqsk_queue_drop);
  936. void inet_csk_reqsk_queue_drop_and_put(struct sock *sk, struct request_sock *req)
  937. {
  938. inet_csk_reqsk_queue_drop(sk, req);
  939. reqsk_put(req);
  940. }
  941. EXPORT_SYMBOL(inet_csk_reqsk_queue_drop_and_put);
  942. static void reqsk_timer_handler(struct timer_list *t)
  943. {
  944. struct request_sock *req = from_timer(req, t, rsk_timer);
  945. struct request_sock *nreq = NULL, *oreq = req;
  946. struct sock *sk_listener = req->rsk_listener;
  947. struct inet_connection_sock *icsk;
  948. struct request_sock_queue *queue;
  949. struct net *net;
  950. int max_syn_ack_retries, qlen, expire = 0, resend = 0;
  951. if (inet_sk_state_load(sk_listener) != TCP_LISTEN) {
  952. struct sock *nsk;
  953. nsk = reuseport_migrate_sock(sk_listener, req_to_sk(req), NULL);
  954. if (!nsk)
  955. goto drop;
  956. nreq = inet_reqsk_clone(req, nsk);
  957. if (!nreq)
  958. goto drop;
  959. /* The new timer for the cloned req can decrease the 2
  960. * by calling inet_csk_reqsk_queue_drop_and_put(), so
  961. * hold another count to prevent use-after-free and
  962. * call reqsk_put() just before return.
  963. */
  964. refcount_set(&nreq->rsk_refcnt, 2 + 1);
  965. timer_setup(&nreq->rsk_timer, reqsk_timer_handler, TIMER_PINNED);
  966. reqsk_queue_migrated(&inet_csk(nsk)->icsk_accept_queue, req);
  967. req = nreq;
  968. sk_listener = nsk;
  969. }
  970. icsk = inet_csk(sk_listener);
  971. net = sock_net(sk_listener);
  972. max_syn_ack_retries = READ_ONCE(icsk->icsk_syn_retries) ? :
  973. READ_ONCE(net->ipv4.sysctl_tcp_synack_retries);
  974. /* Normally all the openreqs are young and become mature
  975. * (i.e. converted to established socket) for first timeout.
  976. * If synack was not acknowledged for 1 second, it means
  977. * one of the following things: synack was lost, ack was lost,
  978. * rtt is high or nobody planned to ack (i.e. synflood).
  979. * When server is a bit loaded, queue is populated with old
  980. * open requests, reducing effective size of queue.
  981. * When server is well loaded, queue size reduces to zero
  982. * after several minutes of work. It is not synflood,
  983. * it is normal operation. The solution is pruning
  984. * too old entries overriding normal timeout, when
  985. * situation becomes dangerous.
  986. *
  987. * Essentially, we reserve half of room for young
  988. * embrions; and abort old ones without pity, if old
  989. * ones are about to clog our table.
  990. */
  991. queue = &icsk->icsk_accept_queue;
  992. qlen = reqsk_queue_len(queue);
  993. if ((qlen << 1) > max(8U, READ_ONCE(sk_listener->sk_max_ack_backlog))) {
  994. int young = reqsk_queue_len_young(queue) << 1;
  995. while (max_syn_ack_retries > 2) {
  996. if (qlen < young)
  997. break;
  998. max_syn_ack_retries--;
  999. young <<= 1;
  1000. }
  1001. }
  1002. syn_ack_recalc(req, max_syn_ack_retries, READ_ONCE(queue->rskq_defer_accept),
  1003. &expire, &resend);
  1004. req->rsk_ops->syn_ack_timeout(req);
  1005. if (!expire &&
  1006. (!resend ||
  1007. !inet_rtx_syn_ack(sk_listener, req) ||
  1008. inet_rsk(req)->acked)) {
  1009. if (req->num_timeout++ == 0)
  1010. atomic_dec(&queue->young);
  1011. mod_timer(&req->rsk_timer, jiffies + reqsk_timeout(req, TCP_RTO_MAX));
  1012. if (!nreq)
  1013. return;
  1014. if (!inet_ehash_insert(req_to_sk(nreq), req_to_sk(oreq), NULL)) {
  1015. /* delete timer */
  1016. __inet_csk_reqsk_queue_drop(sk_listener, nreq, true);
  1017. goto no_ownership;
  1018. }
  1019. __NET_INC_STATS(net, LINUX_MIB_TCPMIGRATEREQSUCCESS);
  1020. reqsk_migrate_reset(oreq);
  1021. reqsk_queue_removed(&inet_csk(oreq->rsk_listener)->icsk_accept_queue, oreq);
  1022. reqsk_put(oreq);
  1023. reqsk_put(nreq);
  1024. return;
  1025. }
  1026. /* Even if we can clone the req, we may need not retransmit any more
  1027. * SYN+ACKs (nreq->num_timeout > max_syn_ack_retries, etc), or another
  1028. * CPU may win the "own_req" race so that inet_ehash_insert() fails.
  1029. */
  1030. if (nreq) {
  1031. __NET_INC_STATS(net, LINUX_MIB_TCPMIGRATEREQFAILURE);
  1032. no_ownership:
  1033. reqsk_migrate_reset(nreq);
  1034. reqsk_queue_removed(queue, nreq);
  1035. __reqsk_free(nreq);
  1036. }
  1037. drop:
  1038. __inet_csk_reqsk_queue_drop(sk_listener, oreq, true);
  1039. reqsk_put(oreq);
  1040. }
  1041. static bool reqsk_queue_hash_req(struct request_sock *req,
  1042. unsigned long timeout)
  1043. {
  1044. bool found_dup_sk = false;
  1045. if (!inet_ehash_insert(req_to_sk(req), NULL, &found_dup_sk))
  1046. return false;
  1047. /* The timer needs to be setup after a successful insertion. */
  1048. timer_setup(&req->rsk_timer, reqsk_timer_handler, TIMER_PINNED);
  1049. mod_timer(&req->rsk_timer, jiffies + timeout);
  1050. /* before letting lookups find us, make sure all req fields
  1051. * are committed to memory and refcnt initialized.
  1052. */
  1053. smp_wmb();
  1054. refcount_set(&req->rsk_refcnt, 2 + 1);
  1055. return true;
  1056. }
  1057. bool inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
  1058. unsigned long timeout)
  1059. {
  1060. if (!reqsk_queue_hash_req(req, timeout))
  1061. return false;
  1062. inet_csk_reqsk_queue_added(sk);
  1063. return true;
  1064. }
  1065. EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
  1066. static void inet_clone_ulp(const struct request_sock *req, struct sock *newsk,
  1067. const gfp_t priority)
  1068. {
  1069. struct inet_connection_sock *icsk = inet_csk(newsk);
  1070. if (!icsk->icsk_ulp_ops)
  1071. return;
  1072. icsk->icsk_ulp_ops->clone(req, newsk, priority);
  1073. }
  1074. /**
  1075. * inet_csk_clone_lock - clone an inet socket, and lock its clone
  1076. * @sk: the socket to clone
  1077. * @req: request_sock
  1078. * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
  1079. *
  1080. * Caller must unlock socket even in error path (bh_unlock_sock(newsk))
  1081. */
  1082. struct sock *inet_csk_clone_lock(const struct sock *sk,
  1083. const struct request_sock *req,
  1084. const gfp_t priority)
  1085. {
  1086. struct sock *newsk = sk_clone_lock(sk, priority);
  1087. if (newsk) {
  1088. struct inet_connection_sock *newicsk = inet_csk(newsk);
  1089. inet_sk_set_state(newsk, TCP_SYN_RECV);
  1090. newicsk->icsk_bind_hash = NULL;
  1091. newicsk->icsk_bind2_hash = NULL;
  1092. inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
  1093. inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
  1094. inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
  1095. /* listeners have SOCK_RCU_FREE, not the children */
  1096. sock_reset_flag(newsk, SOCK_RCU_FREE);
  1097. inet_sk(newsk)->mc_list = NULL;
  1098. newsk->sk_mark = inet_rsk(req)->ir_mark;
  1099. atomic64_set(&newsk->sk_cookie,
  1100. atomic64_read(&inet_rsk(req)->ir_cookie));
  1101. newicsk->icsk_retransmits = 0;
  1102. newicsk->icsk_backoff = 0;
  1103. newicsk->icsk_probes_out = 0;
  1104. newicsk->icsk_probes_tstamp = 0;
  1105. /* Deinitialize accept_queue to trap illegal accesses. */
  1106. memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
  1107. inet_clone_ulp(req, newsk, priority);
  1108. security_inet_csk_clone(newsk, req);
  1109. }
  1110. return newsk;
  1111. }
  1112. EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
  1113. /*
  1114. * At this point, there should be no process reference to this
  1115. * socket, and thus no user references at all. Therefore we
  1116. * can assume the socket waitqueue is inactive and nobody will
  1117. * try to jump onto it.
  1118. */
  1119. void inet_csk_destroy_sock(struct sock *sk)
  1120. {
  1121. WARN_ON(sk->sk_state != TCP_CLOSE);
  1122. WARN_ON(!sock_flag(sk, SOCK_DEAD));
  1123. /* It cannot be in hash table! */
  1124. WARN_ON(!sk_unhashed(sk));
  1125. /* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
  1126. WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
  1127. sk->sk_prot->destroy(sk);
  1128. sk_stream_kill_queues(sk);
  1129. xfrm_sk_free_policy(sk);
  1130. this_cpu_dec(*sk->sk_prot->orphan_count);
  1131. sock_put(sk);
  1132. }
  1133. EXPORT_SYMBOL(inet_csk_destroy_sock);
  1134. /* This function allows to force a closure of a socket after the call to
  1135. * tcp/dccp_create_openreq_child().
  1136. */
  1137. void inet_csk_prepare_forced_close(struct sock *sk)
  1138. __releases(&sk->sk_lock.slock)
  1139. {
  1140. /* sk_clone_lock locked the socket and set refcnt to 2 */
  1141. bh_unlock_sock(sk);
  1142. sock_put(sk);
  1143. inet_csk_prepare_for_destroy_sock(sk);
  1144. inet_sk(sk)->inet_num = 0;
  1145. }
  1146. EXPORT_SYMBOL(inet_csk_prepare_forced_close);
  1147. static int inet_ulp_can_listen(const struct sock *sk)
  1148. {
  1149. const struct inet_connection_sock *icsk = inet_csk(sk);
  1150. if (icsk->icsk_ulp_ops && !icsk->icsk_ulp_ops->clone)
  1151. return -EINVAL;
  1152. return 0;
  1153. }
  1154. int inet_csk_listen_start(struct sock *sk)
  1155. {
  1156. struct inet_connection_sock *icsk = inet_csk(sk);
  1157. struct inet_sock *inet = inet_sk(sk);
  1158. int err;
  1159. err = inet_ulp_can_listen(sk);
  1160. if (unlikely(err))
  1161. return err;
  1162. reqsk_queue_alloc(&icsk->icsk_accept_queue);
  1163. sk->sk_ack_backlog = 0;
  1164. inet_csk_delack_init(sk);
  1165. /* There is race window here: we announce ourselves listening,
  1166. * but this transition is still not validated by get_port().
  1167. * It is OK, because this socket enters to hash table only
  1168. * after validation is complete.
  1169. */
  1170. inet_sk_state_store(sk, TCP_LISTEN);
  1171. err = sk->sk_prot->get_port(sk, inet->inet_num);
  1172. if (!err) {
  1173. inet->inet_sport = htons(inet->inet_num);
  1174. sk_dst_reset(sk);
  1175. err = sk->sk_prot->hash(sk);
  1176. if (likely(!err))
  1177. return 0;
  1178. }
  1179. inet_sk_set_state(sk, TCP_CLOSE);
  1180. return err;
  1181. }
  1182. EXPORT_SYMBOL_GPL(inet_csk_listen_start);
  1183. static void inet_child_forget(struct sock *sk, struct request_sock *req,
  1184. struct sock *child)
  1185. {
  1186. sk->sk_prot->disconnect(child, O_NONBLOCK);
  1187. sock_orphan(child);
  1188. this_cpu_inc(*sk->sk_prot->orphan_count);
  1189. if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
  1190. BUG_ON(rcu_access_pointer(tcp_sk(child)->fastopen_rsk) != req);
  1191. BUG_ON(sk != req->rsk_listener);
  1192. /* Paranoid, to prevent race condition if
  1193. * an inbound pkt destined for child is
  1194. * blocked by sock lock in tcp_v4_rcv().
  1195. * Also to satisfy an assertion in
  1196. * tcp_v4_destroy_sock().
  1197. */
  1198. RCU_INIT_POINTER(tcp_sk(child)->fastopen_rsk, NULL);
  1199. }
  1200. inet_csk_destroy_sock(child);
  1201. }
  1202. struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
  1203. struct request_sock *req,
  1204. struct sock *child)
  1205. {
  1206. struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
  1207. spin_lock(&queue->rskq_lock);
  1208. if (unlikely(sk->sk_state != TCP_LISTEN)) {
  1209. inet_child_forget(sk, req, child);
  1210. child = NULL;
  1211. } else {
  1212. req->sk = child;
  1213. req->dl_next = NULL;
  1214. if (queue->rskq_accept_head == NULL)
  1215. WRITE_ONCE(queue->rskq_accept_head, req);
  1216. else
  1217. queue->rskq_accept_tail->dl_next = req;
  1218. queue->rskq_accept_tail = req;
  1219. sk_acceptq_added(sk);
  1220. }
  1221. spin_unlock(&queue->rskq_lock);
  1222. return child;
  1223. }
  1224. EXPORT_SYMBOL(inet_csk_reqsk_queue_add);
  1225. struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child,
  1226. struct request_sock *req, bool own_req)
  1227. {
  1228. if (own_req) {
  1229. inet_csk_reqsk_queue_drop(req->rsk_listener, req);
  1230. reqsk_queue_removed(&inet_csk(req->rsk_listener)->icsk_accept_queue, req);
  1231. if (sk != req->rsk_listener) {
  1232. /* another listening sk has been selected,
  1233. * migrate the req to it.
  1234. */
  1235. struct request_sock *nreq;
  1236. /* hold a refcnt for the nreq->rsk_listener
  1237. * which is assigned in inet_reqsk_clone()
  1238. */
  1239. sock_hold(sk);
  1240. nreq = inet_reqsk_clone(req, sk);
  1241. if (!nreq) {
  1242. inet_child_forget(sk, req, child);
  1243. goto child_put;
  1244. }
  1245. refcount_set(&nreq->rsk_refcnt, 1);
  1246. if (inet_csk_reqsk_queue_add(sk, nreq, child)) {
  1247. __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMIGRATEREQSUCCESS);
  1248. reqsk_migrate_reset(req);
  1249. reqsk_put(req);
  1250. return child;
  1251. }
  1252. __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMIGRATEREQFAILURE);
  1253. reqsk_migrate_reset(nreq);
  1254. __reqsk_free(nreq);
  1255. } else if (inet_csk_reqsk_queue_add(sk, req, child)) {
  1256. return child;
  1257. }
  1258. }
  1259. /* Too bad, another child took ownership of the request, undo. */
  1260. child_put:
  1261. bh_unlock_sock(child);
  1262. sock_put(child);
  1263. return NULL;
  1264. }
  1265. EXPORT_SYMBOL(inet_csk_complete_hashdance);
  1266. /*
  1267. * This routine closes sockets which have been at least partially
  1268. * opened, but not yet accepted.
  1269. */
  1270. void inet_csk_listen_stop(struct sock *sk)
  1271. {
  1272. struct inet_connection_sock *icsk = inet_csk(sk);
  1273. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  1274. struct request_sock *next, *req;
  1275. /* Following specs, it would be better either to send FIN
  1276. * (and enter FIN-WAIT-1, it is normal close)
  1277. * or to send active reset (abort).
  1278. * Certainly, it is pretty dangerous while synflood, but it is
  1279. * bad justification for our negligence 8)
  1280. * To be honest, we are not able to make either
  1281. * of the variants now. --ANK
  1282. */
  1283. while ((req = reqsk_queue_remove(queue, sk)) != NULL) {
  1284. struct sock *child = req->sk, *nsk;
  1285. struct request_sock *nreq;
  1286. local_bh_disable();
  1287. bh_lock_sock(child);
  1288. WARN_ON(sock_owned_by_user(child));
  1289. sock_hold(child);
  1290. nsk = reuseport_migrate_sock(sk, child, NULL);
  1291. if (nsk) {
  1292. nreq = inet_reqsk_clone(req, nsk);
  1293. if (nreq) {
  1294. refcount_set(&nreq->rsk_refcnt, 1);
  1295. if (inet_csk_reqsk_queue_add(nsk, nreq, child)) {
  1296. __NET_INC_STATS(sock_net(nsk),
  1297. LINUX_MIB_TCPMIGRATEREQSUCCESS);
  1298. reqsk_migrate_reset(req);
  1299. } else {
  1300. __NET_INC_STATS(sock_net(nsk),
  1301. LINUX_MIB_TCPMIGRATEREQFAILURE);
  1302. reqsk_migrate_reset(nreq);
  1303. __reqsk_free(nreq);
  1304. }
  1305. /* inet_csk_reqsk_queue_add() has already
  1306. * called inet_child_forget() on failure case.
  1307. */
  1308. goto skip_child_forget;
  1309. }
  1310. }
  1311. inet_child_forget(sk, req, child);
  1312. skip_child_forget:
  1313. reqsk_put(req);
  1314. bh_unlock_sock(child);
  1315. local_bh_enable();
  1316. sock_put(child);
  1317. cond_resched();
  1318. }
  1319. if (queue->fastopenq.rskq_rst_head) {
  1320. /* Free all the reqs queued in rskq_rst_head. */
  1321. spin_lock_bh(&queue->fastopenq.lock);
  1322. req = queue->fastopenq.rskq_rst_head;
  1323. queue->fastopenq.rskq_rst_head = NULL;
  1324. spin_unlock_bh(&queue->fastopenq.lock);
  1325. while (req != NULL) {
  1326. next = req->dl_next;
  1327. reqsk_put(req);
  1328. req = next;
  1329. }
  1330. }
  1331. WARN_ON_ONCE(sk->sk_ack_backlog);
  1332. }
  1333. EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
  1334. void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
  1335. {
  1336. struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
  1337. const struct inet_sock *inet = inet_sk(sk);
  1338. sin->sin_family = AF_INET;
  1339. sin->sin_addr.s_addr = inet->inet_daddr;
  1340. sin->sin_port = inet->inet_dport;
  1341. }
  1342. EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
  1343. static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
  1344. {
  1345. const struct inet_sock *inet = inet_sk(sk);
  1346. const struct ip_options_rcu *inet_opt;
  1347. __be32 daddr = inet->inet_daddr;
  1348. struct flowi4 *fl4;
  1349. struct rtable *rt;
  1350. rcu_read_lock();
  1351. inet_opt = rcu_dereference(inet->inet_opt);
  1352. if (inet_opt && inet_opt->opt.srr)
  1353. daddr = inet_opt->opt.faddr;
  1354. fl4 = &fl->u.ip4;
  1355. rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
  1356. inet->inet_saddr, inet->inet_dport,
  1357. inet->inet_sport, sk->sk_protocol,
  1358. ip_sock_rt_tos(sk), sk->sk_bound_dev_if);
  1359. if (IS_ERR(rt))
  1360. rt = NULL;
  1361. if (rt)
  1362. sk_setup_caps(sk, &rt->dst);
  1363. rcu_read_unlock();
  1364. return &rt->dst;
  1365. }
  1366. struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
  1367. {
  1368. struct dst_entry *dst = __sk_dst_check(sk, 0);
  1369. struct inet_sock *inet = inet_sk(sk);
  1370. if (!dst) {
  1371. dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
  1372. if (!dst)
  1373. goto out;
  1374. }
  1375. dst->ops->update_pmtu(dst, sk, NULL, mtu, true);
  1376. dst = __sk_dst_check(sk, 0);
  1377. if (!dst)
  1378. dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
  1379. out:
  1380. return dst;
  1381. }
  1382. EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);