inet_connection_sock.c 27 KB

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