inet_connection_sock.c 32 KB

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