inet_connection_sock.c 41 KB

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