inet_connection_sock.c 31 KB

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