inet_connection_sock.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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 bool 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 true;
  51. if (!sk1_rcv_saddr || !sk2_rcv_saddr)
  52. return match_wildcard;
  53. }
  54. return false;
  55. }
  56. if (addr_type == IPV6_ADDR_ANY && addr_type2 == IPV6_ADDR_ANY)
  57. return true;
  58. if (addr_type2 == IPV6_ADDR_ANY && match_wildcard &&
  59. !(sk2_ipv6only && addr_type == IPV6_ADDR_MAPPED))
  60. return true;
  61. if (addr_type == IPV6_ADDR_ANY && match_wildcard &&
  62. !(sk1_ipv6only && addr_type2 == IPV6_ADDR_MAPPED))
  63. return true;
  64. if (sk2_rcv_saddr6 &&
  65. ipv6_addr_equal(sk1_rcv_saddr6, sk2_rcv_saddr6))
  66. return true;
  67. return false;
  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 bool 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 true;
  80. if (!sk1_rcv_saddr || !sk2_rcv_saddr)
  81. return match_wildcard;
  82. }
  83. return false;
  84. }
  85. bool 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. inet6_rcv_saddr(sk),
  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. tb->fast_sk_family = sk->sk_family;
  302. #if IS_ENABLED(CONFIG_IPV6)
  303. tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
  304. #endif
  305. } else {
  306. tb->fastreuseport = 0;
  307. }
  308. } else {
  309. if (!reuse)
  310. tb->fastreuse = 0;
  311. if (sk->sk_reuseport) {
  312. /* We didn't match or we don't have fastreuseport set on
  313. * the tb, but we have sk_reuseport set on this socket
  314. * and we know that there are no bind conflicts with
  315. * this socket in this tb, so reset our tb's reuseport
  316. * settings so that any subsequent sockets that match
  317. * our current socket will be put on the fast path.
  318. *
  319. * If we reset we need to set FASTREUSEPORT_STRICT so we
  320. * do extra checking for all subsequent sk_reuseport
  321. * socks.
  322. */
  323. if (!sk_reuseport_match(tb, sk)) {
  324. tb->fastreuseport = FASTREUSEPORT_STRICT;
  325. tb->fastuid = uid;
  326. tb->fast_rcv_saddr = sk->sk_rcv_saddr;
  327. tb->fast_ipv6_only = ipv6_only_sock(sk);
  328. tb->fast_sk_family = sk->sk_family;
  329. #if IS_ENABLED(CONFIG_IPV6)
  330. tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
  331. #endif
  332. }
  333. } else {
  334. tb->fastreuseport = 0;
  335. }
  336. }
  337. if (!inet_csk(sk)->icsk_bind_hash)
  338. inet_bind_hash(sk, tb, port);
  339. WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
  340. ret = 0;
  341. fail_unlock:
  342. spin_unlock_bh(&head->lock);
  343. return ret;
  344. }
  345. EXPORT_SYMBOL_GPL(inet_csk_get_port);
  346. /*
  347. * Wait for an incoming connection, avoid race conditions. This must be called
  348. * with the socket locked.
  349. */
  350. static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
  351. {
  352. struct inet_connection_sock *icsk = inet_csk(sk);
  353. DEFINE_WAIT(wait);
  354. int err;
  355. /*
  356. * True wake-one mechanism for incoming connections: only
  357. * one process gets woken up, not the 'whole herd'.
  358. * Since we do not 'race & poll' for established sockets
  359. * anymore, the common case will execute the loop only once.
  360. *
  361. * Subtle issue: "add_wait_queue_exclusive()" will be added
  362. * after any current non-exclusive waiters, and we know that
  363. * it will always _stay_ after any new non-exclusive waiters
  364. * because all non-exclusive waiters are added at the
  365. * beginning of the wait-queue. As such, it's ok to "drop"
  366. * our exclusiveness temporarily when we get woken up without
  367. * having to remove and re-insert us on the wait queue.
  368. */
  369. for (;;) {
  370. prepare_to_wait_exclusive(sk_sleep(sk), &wait,
  371. TASK_INTERRUPTIBLE);
  372. release_sock(sk);
  373. if (reqsk_queue_empty(&icsk->icsk_accept_queue))
  374. timeo = schedule_timeout(timeo);
  375. sched_annotate_sleep();
  376. lock_sock(sk);
  377. err = 0;
  378. if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
  379. break;
  380. err = -EINVAL;
  381. if (sk->sk_state != TCP_LISTEN)
  382. break;
  383. err = sock_intr_errno(timeo);
  384. if (signal_pending(current))
  385. break;
  386. err = -EAGAIN;
  387. if (!timeo)
  388. break;
  389. }
  390. finish_wait(sk_sleep(sk), &wait);
  391. return err;
  392. }
  393. /*
  394. * This will accept the next outstanding connection.
  395. */
  396. struct sock *inet_csk_accept(struct sock *sk, int flags, int *err, bool kern)
  397. {
  398. struct inet_connection_sock *icsk = inet_csk(sk);
  399. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  400. struct request_sock *req;
  401. struct sock *newsk;
  402. int error;
  403. lock_sock(sk);
  404. /* We need to make sure that this socket is listening,
  405. * and that it has something pending.
  406. */
  407. error = -EINVAL;
  408. if (sk->sk_state != TCP_LISTEN)
  409. goto out_err;
  410. /* Find already established connection */
  411. if (reqsk_queue_empty(queue)) {
  412. long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
  413. /* If this is a non blocking socket don't sleep */
  414. error = -EAGAIN;
  415. if (!timeo)
  416. goto out_err;
  417. error = inet_csk_wait_for_connect(sk, timeo);
  418. if (error)
  419. goto out_err;
  420. }
  421. req = reqsk_queue_remove(queue, sk);
  422. newsk = req->sk;
  423. if (sk->sk_protocol == IPPROTO_TCP &&
  424. tcp_rsk(req)->tfo_listener) {
  425. spin_lock_bh(&queue->fastopenq.lock);
  426. if (tcp_rsk(req)->tfo_listener) {
  427. /* We are still waiting for the final ACK from 3WHS
  428. * so can't free req now. Instead, we set req->sk to
  429. * NULL to signify that the child socket is taken
  430. * so reqsk_fastopen_remove() will free the req
  431. * when 3WHS finishes (or is aborted).
  432. */
  433. req->sk = NULL;
  434. req = NULL;
  435. }
  436. spin_unlock_bh(&queue->fastopenq.lock);
  437. }
  438. out:
  439. release_sock(sk);
  440. if (req)
  441. reqsk_put(req);
  442. return newsk;
  443. out_err:
  444. newsk = NULL;
  445. req = NULL;
  446. *err = error;
  447. goto out;
  448. }
  449. EXPORT_SYMBOL(inet_csk_accept);
  450. /*
  451. * Using different timers for retransmit, delayed acks and probes
  452. * We may wish use just one timer maintaining a list of expire jiffies
  453. * to optimize.
  454. */
  455. void inet_csk_init_xmit_timers(struct sock *sk,
  456. void (*retransmit_handler)(struct timer_list *t),
  457. void (*delack_handler)(struct timer_list *t),
  458. void (*keepalive_handler)(struct timer_list *t))
  459. {
  460. struct inet_connection_sock *icsk = inet_csk(sk);
  461. timer_setup(&icsk->icsk_retransmit_timer, retransmit_handler, 0);
  462. timer_setup(&icsk->icsk_delack_timer, delack_handler, 0);
  463. timer_setup(&sk->sk_timer, keepalive_handler, 0);
  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(struct timer_list *t)
  614. {
  615. struct request_sock *req = from_timer(req, t, rsk_timer);
  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. timer_setup(&req->rsk_timer, reqsk_timer_handler, TIMER_PINNED);
  681. mod_timer(&req->rsk_timer, jiffies + timeout);
  682. inet_ehash_insert(req_to_sk(req), NULL);
  683. /* before letting lookups find us, make sure all req fields
  684. * are committed to memory and refcnt initialized.
  685. */
  686. smp_wmb();
  687. refcount_set(&req->rsk_refcnt, 2 + 1);
  688. }
  689. void inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
  690. unsigned long timeout)
  691. {
  692. reqsk_queue_hash_req(req, timeout);
  693. inet_csk_reqsk_queue_added(sk);
  694. }
  695. EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
  696. /**
  697. * inet_csk_clone_lock - clone an inet socket, and lock its clone
  698. * @sk: the socket to clone
  699. * @req: request_sock
  700. * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
  701. *
  702. * Caller must unlock socket even in error path (bh_unlock_sock(newsk))
  703. */
  704. struct sock *inet_csk_clone_lock(const struct sock *sk,
  705. const struct request_sock *req,
  706. const gfp_t priority)
  707. {
  708. struct sock *newsk = sk_clone_lock(sk, priority);
  709. if (newsk) {
  710. struct inet_connection_sock *newicsk = inet_csk(newsk);
  711. newsk->sk_state = TCP_SYN_RECV;
  712. newicsk->icsk_bind_hash = NULL;
  713. inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
  714. inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
  715. inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
  716. /* listeners have SOCK_RCU_FREE, not the children */
  717. sock_reset_flag(newsk, SOCK_RCU_FREE);
  718. inet_sk(newsk)->mc_list = NULL;
  719. newsk->sk_mark = inet_rsk(req)->ir_mark;
  720. atomic64_set(&newsk->sk_cookie,
  721. atomic64_read(&inet_rsk(req)->ir_cookie));
  722. newicsk->icsk_retransmits = 0;
  723. newicsk->icsk_backoff = 0;
  724. newicsk->icsk_probes_out = 0;
  725. /* Deinitialize accept_queue to trap illegal accesses. */
  726. memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
  727. security_inet_csk_clone(newsk, req);
  728. }
  729. return newsk;
  730. }
  731. EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
  732. /*
  733. * At this point, there should be no process reference to this
  734. * socket, and thus no user references at all. Therefore we
  735. * can assume the socket waitqueue is inactive and nobody will
  736. * try to jump onto it.
  737. */
  738. void inet_csk_destroy_sock(struct sock *sk)
  739. {
  740. WARN_ON(sk->sk_state != TCP_CLOSE);
  741. WARN_ON(!sock_flag(sk, SOCK_DEAD));
  742. /* It cannot be in hash table! */
  743. WARN_ON(!sk_unhashed(sk));
  744. /* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
  745. WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
  746. sk->sk_prot->destroy(sk);
  747. sk_stream_kill_queues(sk);
  748. xfrm_sk_free_policy(sk);
  749. sk_refcnt_debug_release(sk);
  750. percpu_counter_dec(sk->sk_prot->orphan_count);
  751. sock_put(sk);
  752. }
  753. EXPORT_SYMBOL(inet_csk_destroy_sock);
  754. /* This function allows to force a closure of a socket after the call to
  755. * tcp/dccp_create_openreq_child().
  756. */
  757. void inet_csk_prepare_forced_close(struct sock *sk)
  758. __releases(&sk->sk_lock.slock)
  759. {
  760. /* sk_clone_lock locked the socket and set refcnt to 2 */
  761. bh_unlock_sock(sk);
  762. sock_put(sk);
  763. /* The below has to be done to allow calling inet_csk_destroy_sock */
  764. sock_set_flag(sk, SOCK_DEAD);
  765. percpu_counter_inc(sk->sk_prot->orphan_count);
  766. inet_sk(sk)->inet_num = 0;
  767. }
  768. EXPORT_SYMBOL(inet_csk_prepare_forced_close);
  769. int inet_csk_listen_start(struct sock *sk, int backlog)
  770. {
  771. struct inet_connection_sock *icsk = inet_csk(sk);
  772. struct inet_sock *inet = inet_sk(sk);
  773. int err = -EADDRINUSE;
  774. reqsk_queue_alloc(&icsk->icsk_accept_queue);
  775. sk->sk_max_ack_backlog = backlog;
  776. sk->sk_ack_backlog = 0;
  777. inet_csk_delack_init(sk);
  778. /* There is race window here: we announce ourselves listening,
  779. * but this transition is still not validated by get_port().
  780. * It is OK, because this socket enters to hash table only
  781. * after validation is complete.
  782. */
  783. sk_state_store(sk, TCP_LISTEN);
  784. if (!sk->sk_prot->get_port(sk, inet->inet_num)) {
  785. inet->inet_sport = htons(inet->inet_num);
  786. sk_dst_reset(sk);
  787. err = sk->sk_prot->hash(sk);
  788. if (likely(!err))
  789. return 0;
  790. }
  791. sk->sk_state = TCP_CLOSE;
  792. return err;
  793. }
  794. EXPORT_SYMBOL_GPL(inet_csk_listen_start);
  795. static void inet_child_forget(struct sock *sk, struct request_sock *req,
  796. struct sock *child)
  797. {
  798. sk->sk_prot->disconnect(child, O_NONBLOCK);
  799. sock_orphan(child);
  800. percpu_counter_inc(sk->sk_prot->orphan_count);
  801. if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
  802. BUG_ON(tcp_sk(child)->fastopen_rsk != req);
  803. BUG_ON(sk != req->rsk_listener);
  804. /* Paranoid, to prevent race condition if
  805. * an inbound pkt destined for child is
  806. * blocked by sock lock in tcp_v4_rcv().
  807. * Also to satisfy an assertion in
  808. * tcp_v4_destroy_sock().
  809. */
  810. tcp_sk(child)->fastopen_rsk = NULL;
  811. }
  812. inet_csk_destroy_sock(child);
  813. }
  814. struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
  815. struct request_sock *req,
  816. struct sock *child)
  817. {
  818. struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
  819. spin_lock(&queue->rskq_lock);
  820. if (unlikely(sk->sk_state != TCP_LISTEN)) {
  821. inet_child_forget(sk, req, child);
  822. child = NULL;
  823. } else {
  824. req->sk = child;
  825. req->dl_next = NULL;
  826. if (queue->rskq_accept_head == NULL)
  827. queue->rskq_accept_head = req;
  828. else
  829. queue->rskq_accept_tail->dl_next = req;
  830. queue->rskq_accept_tail = req;
  831. sk_acceptq_added(sk);
  832. }
  833. spin_unlock(&queue->rskq_lock);
  834. return child;
  835. }
  836. EXPORT_SYMBOL(inet_csk_reqsk_queue_add);
  837. struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child,
  838. struct request_sock *req, bool own_req)
  839. {
  840. if (own_req) {
  841. inet_csk_reqsk_queue_drop(sk, req);
  842. reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
  843. if (inet_csk_reqsk_queue_add(sk, req, child))
  844. return child;
  845. }
  846. /* Too bad, another child took ownership of the request, undo. */
  847. bh_unlock_sock(child);
  848. sock_put(child);
  849. return NULL;
  850. }
  851. EXPORT_SYMBOL(inet_csk_complete_hashdance);
  852. /*
  853. * This routine closes sockets which have been at least partially
  854. * opened, but not yet accepted.
  855. */
  856. void inet_csk_listen_stop(struct sock *sk)
  857. {
  858. struct inet_connection_sock *icsk = inet_csk(sk);
  859. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  860. struct request_sock *next, *req;
  861. /* Following specs, it would be better either to send FIN
  862. * (and enter FIN-WAIT-1, it is normal close)
  863. * or to send active reset (abort).
  864. * Certainly, it is pretty dangerous while synflood, but it is
  865. * bad justification for our negligence 8)
  866. * To be honest, we are not able to make either
  867. * of the variants now. --ANK
  868. */
  869. while ((req = reqsk_queue_remove(queue, sk)) != NULL) {
  870. struct sock *child = req->sk;
  871. local_bh_disable();
  872. bh_lock_sock(child);
  873. WARN_ON(sock_owned_by_user(child));
  874. sock_hold(child);
  875. inet_child_forget(sk, req, child);
  876. reqsk_put(req);
  877. bh_unlock_sock(child);
  878. local_bh_enable();
  879. sock_put(child);
  880. cond_resched();
  881. }
  882. if (queue->fastopenq.rskq_rst_head) {
  883. /* Free all the reqs queued in rskq_rst_head. */
  884. spin_lock_bh(&queue->fastopenq.lock);
  885. req = queue->fastopenq.rskq_rst_head;
  886. queue->fastopenq.rskq_rst_head = NULL;
  887. spin_unlock_bh(&queue->fastopenq.lock);
  888. while (req != NULL) {
  889. next = req->dl_next;
  890. reqsk_put(req);
  891. req = next;
  892. }
  893. }
  894. WARN_ON_ONCE(sk->sk_ack_backlog);
  895. }
  896. EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
  897. void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
  898. {
  899. struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
  900. const struct inet_sock *inet = inet_sk(sk);
  901. sin->sin_family = AF_INET;
  902. sin->sin_addr.s_addr = inet->inet_daddr;
  903. sin->sin_port = inet->inet_dport;
  904. }
  905. EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
  906. #ifdef CONFIG_COMPAT
  907. int inet_csk_compat_getsockopt(struct sock *sk, int level, int optname,
  908. char __user *optval, int __user *optlen)
  909. {
  910. const struct inet_connection_sock *icsk = inet_csk(sk);
  911. if (icsk->icsk_af_ops->compat_getsockopt)
  912. return icsk->icsk_af_ops->compat_getsockopt(sk, level, optname,
  913. optval, optlen);
  914. return icsk->icsk_af_ops->getsockopt(sk, level, optname,
  915. optval, optlen);
  916. }
  917. EXPORT_SYMBOL_GPL(inet_csk_compat_getsockopt);
  918. int inet_csk_compat_setsockopt(struct sock *sk, int level, int optname,
  919. char __user *optval, unsigned int optlen)
  920. {
  921. const struct inet_connection_sock *icsk = inet_csk(sk);
  922. if (icsk->icsk_af_ops->compat_setsockopt)
  923. return icsk->icsk_af_ops->compat_setsockopt(sk, level, optname,
  924. optval, optlen);
  925. return icsk->icsk_af_ops->setsockopt(sk, level, optname,
  926. optval, optlen);
  927. }
  928. EXPORT_SYMBOL_GPL(inet_csk_compat_setsockopt);
  929. #endif
  930. static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
  931. {
  932. const struct inet_sock *inet = inet_sk(sk);
  933. const struct ip_options_rcu *inet_opt;
  934. __be32 daddr = inet->inet_daddr;
  935. struct flowi4 *fl4;
  936. struct rtable *rt;
  937. rcu_read_lock();
  938. inet_opt = rcu_dereference(inet->inet_opt);
  939. if (inet_opt && inet_opt->opt.srr)
  940. daddr = inet_opt->opt.faddr;
  941. fl4 = &fl->u.ip4;
  942. rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
  943. inet->inet_saddr, inet->inet_dport,
  944. inet->inet_sport, sk->sk_protocol,
  945. RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
  946. if (IS_ERR(rt))
  947. rt = NULL;
  948. if (rt)
  949. sk_setup_caps(sk, &rt->dst);
  950. rcu_read_unlock();
  951. return &rt->dst;
  952. }
  953. struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
  954. {
  955. struct dst_entry *dst = __sk_dst_check(sk, 0);
  956. struct inet_sock *inet = inet_sk(sk);
  957. if (!dst) {
  958. dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
  959. if (!dst)
  960. goto out;
  961. }
  962. dst->ops->update_pmtu(dst, sk, NULL, mtu);
  963. dst = __sk_dst_check(sk, 0);
  964. if (!dst)
  965. dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
  966. out:
  967. return dst;
  968. }
  969. EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);