inet_connection_sock.c 30 KB

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