inet_connection_sock.c 29 KB

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