inet_connection_sock.c 31 KB

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