inet_connection_sock.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  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. !rcu_access_pointer(sk->sk_reuseport_cb) &&
  185. sk->sk_reuseport && uid_eq(tb->fastuid, uid))) &&
  186. smallest_size == -1)
  187. goto success;
  188. if (inet_csk(sk)->icsk_af_ops->bind_conflict(sk, tb, true)) {
  189. if ((reuse ||
  190. (tb->fastreuseport > 0 &&
  191. sk->sk_reuseport &&
  192. !rcu_access_pointer(sk->sk_reuseport_cb) &&
  193. uid_eq(tb->fastuid, uid))) &&
  194. smallest_size != -1 && --attempts >= 0) {
  195. spin_unlock_bh(&head->lock);
  196. goto again;
  197. }
  198. goto fail_unlock;
  199. }
  200. if (!reuse)
  201. tb->fastreuse = 0;
  202. if (!sk->sk_reuseport || !uid_eq(tb->fastuid, uid))
  203. tb->fastreuseport = 0;
  204. } else {
  205. tb->fastreuse = reuse;
  206. if (sk->sk_reuseport) {
  207. tb->fastreuseport = 1;
  208. tb->fastuid = uid;
  209. } else {
  210. tb->fastreuseport = 0;
  211. }
  212. }
  213. success:
  214. if (!inet_csk(sk)->icsk_bind_hash)
  215. inet_bind_hash(sk, tb, port);
  216. WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
  217. ret = 0;
  218. fail_unlock:
  219. spin_unlock_bh(&head->lock);
  220. return ret;
  221. }
  222. EXPORT_SYMBOL_GPL(inet_csk_get_port);
  223. /*
  224. * Wait for an incoming connection, avoid race conditions. This must be called
  225. * with the socket locked.
  226. */
  227. static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
  228. {
  229. struct inet_connection_sock *icsk = inet_csk(sk);
  230. DEFINE_WAIT(wait);
  231. int err;
  232. /*
  233. * True wake-one mechanism for incoming connections: only
  234. * one process gets woken up, not the 'whole herd'.
  235. * Since we do not 'race & poll' for established sockets
  236. * anymore, the common case will execute the loop only once.
  237. *
  238. * Subtle issue: "add_wait_queue_exclusive()" will be added
  239. * after any current non-exclusive waiters, and we know that
  240. * it will always _stay_ after any new non-exclusive waiters
  241. * because all non-exclusive waiters are added at the
  242. * beginning of the wait-queue. As such, it's ok to "drop"
  243. * our exclusiveness temporarily when we get woken up without
  244. * having to remove and re-insert us on the wait queue.
  245. */
  246. for (;;) {
  247. prepare_to_wait_exclusive(sk_sleep(sk), &wait,
  248. TASK_INTERRUPTIBLE);
  249. release_sock(sk);
  250. if (reqsk_queue_empty(&icsk->icsk_accept_queue))
  251. timeo = schedule_timeout(timeo);
  252. sched_annotate_sleep();
  253. lock_sock(sk);
  254. err = 0;
  255. if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
  256. break;
  257. err = -EINVAL;
  258. if (sk->sk_state != TCP_LISTEN)
  259. break;
  260. err = sock_intr_errno(timeo);
  261. if (signal_pending(current))
  262. break;
  263. err = -EAGAIN;
  264. if (!timeo)
  265. break;
  266. }
  267. finish_wait(sk_sleep(sk), &wait);
  268. return err;
  269. }
  270. /*
  271. * This will accept the next outstanding connection.
  272. */
  273. struct sock *inet_csk_accept(struct sock *sk, int flags, int *err)
  274. {
  275. struct inet_connection_sock *icsk = inet_csk(sk);
  276. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  277. struct request_sock *req;
  278. struct sock *newsk;
  279. int error;
  280. lock_sock(sk);
  281. /* We need to make sure that this socket is listening,
  282. * and that it has something pending.
  283. */
  284. error = -EINVAL;
  285. if (sk->sk_state != TCP_LISTEN)
  286. goto out_err;
  287. /* Find already established connection */
  288. if (reqsk_queue_empty(queue)) {
  289. long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
  290. /* If this is a non blocking socket don't sleep */
  291. error = -EAGAIN;
  292. if (!timeo)
  293. goto out_err;
  294. error = inet_csk_wait_for_connect(sk, timeo);
  295. if (error)
  296. goto out_err;
  297. }
  298. req = reqsk_queue_remove(queue, sk);
  299. newsk = req->sk;
  300. if (sk->sk_protocol == IPPROTO_TCP &&
  301. tcp_rsk(req)->tfo_listener) {
  302. spin_lock_bh(&queue->fastopenq.lock);
  303. if (tcp_rsk(req)->tfo_listener) {
  304. /* We are still waiting for the final ACK from 3WHS
  305. * so can't free req now. Instead, we set req->sk to
  306. * NULL to signify that the child socket is taken
  307. * so reqsk_fastopen_remove() will free the req
  308. * when 3WHS finishes (or is aborted).
  309. */
  310. req->sk = NULL;
  311. req = NULL;
  312. }
  313. spin_unlock_bh(&queue->fastopenq.lock);
  314. }
  315. out:
  316. release_sock(sk);
  317. if (req)
  318. reqsk_put(req);
  319. return newsk;
  320. out_err:
  321. newsk = NULL;
  322. req = NULL;
  323. *err = error;
  324. goto out;
  325. }
  326. EXPORT_SYMBOL(inet_csk_accept);
  327. /*
  328. * Using different timers for retransmit, delayed acks and probes
  329. * We may wish use just one timer maintaining a list of expire jiffies
  330. * to optimize.
  331. */
  332. void inet_csk_init_xmit_timers(struct sock *sk,
  333. void (*retransmit_handler)(unsigned long),
  334. void (*delack_handler)(unsigned long),
  335. void (*keepalive_handler)(unsigned long))
  336. {
  337. struct inet_connection_sock *icsk = inet_csk(sk);
  338. setup_timer(&icsk->icsk_retransmit_timer, retransmit_handler,
  339. (unsigned long)sk);
  340. setup_timer(&icsk->icsk_delack_timer, delack_handler,
  341. (unsigned long)sk);
  342. setup_timer(&sk->sk_timer, keepalive_handler, (unsigned long)sk);
  343. icsk->icsk_pending = icsk->icsk_ack.pending = 0;
  344. }
  345. EXPORT_SYMBOL(inet_csk_init_xmit_timers);
  346. void inet_csk_clear_xmit_timers(struct sock *sk)
  347. {
  348. struct inet_connection_sock *icsk = inet_csk(sk);
  349. icsk->icsk_pending = icsk->icsk_ack.pending = icsk->icsk_ack.blocked = 0;
  350. sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
  351. sk_stop_timer(sk, &icsk->icsk_delack_timer);
  352. sk_stop_timer(sk, &sk->sk_timer);
  353. }
  354. EXPORT_SYMBOL(inet_csk_clear_xmit_timers);
  355. void inet_csk_delete_keepalive_timer(struct sock *sk)
  356. {
  357. sk_stop_timer(sk, &sk->sk_timer);
  358. }
  359. EXPORT_SYMBOL(inet_csk_delete_keepalive_timer);
  360. void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len)
  361. {
  362. sk_reset_timer(sk, &sk->sk_timer, jiffies + len);
  363. }
  364. EXPORT_SYMBOL(inet_csk_reset_keepalive_timer);
  365. struct dst_entry *inet_csk_route_req(const struct sock *sk,
  366. struct flowi4 *fl4,
  367. const struct request_sock *req)
  368. {
  369. const struct inet_request_sock *ireq = inet_rsk(req);
  370. struct net *net = read_pnet(&ireq->ireq_net);
  371. struct ip_options_rcu *opt;
  372. struct rtable *rt;
  373. opt = ireq_opt_deref(ireq);
  374. flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
  375. RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
  376. sk->sk_protocol, inet_sk_flowi_flags(sk),
  377. (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
  378. ireq->ir_loc_addr, ireq->ir_rmt_port,
  379. htons(ireq->ir_num));
  380. security_req_classify_flow(req, flowi4_to_flowi(fl4));
  381. rt = ip_route_output_flow(net, fl4, sk);
  382. if (IS_ERR(rt))
  383. goto no_route;
  384. if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
  385. goto route_err;
  386. return &rt->dst;
  387. route_err:
  388. ip_rt_put(rt);
  389. no_route:
  390. __IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
  391. return NULL;
  392. }
  393. EXPORT_SYMBOL_GPL(inet_csk_route_req);
  394. struct dst_entry *inet_csk_route_child_sock(const struct sock *sk,
  395. struct sock *newsk,
  396. const struct request_sock *req)
  397. {
  398. const struct inet_request_sock *ireq = inet_rsk(req);
  399. struct net *net = read_pnet(&ireq->ireq_net);
  400. struct inet_sock *newinet = inet_sk(newsk);
  401. struct ip_options_rcu *opt;
  402. struct flowi4 *fl4;
  403. struct rtable *rt;
  404. opt = rcu_dereference(ireq->ireq_opt);
  405. fl4 = &newinet->cork.fl.u.ip4;
  406. flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
  407. RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
  408. sk->sk_protocol, inet_sk_flowi_flags(sk),
  409. (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
  410. ireq->ir_loc_addr, ireq->ir_rmt_port,
  411. htons(ireq->ir_num));
  412. security_req_classify_flow(req, flowi4_to_flowi(fl4));
  413. rt = ip_route_output_flow(net, fl4, sk);
  414. if (IS_ERR(rt))
  415. goto no_route;
  416. if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
  417. goto route_err;
  418. return &rt->dst;
  419. route_err:
  420. ip_rt_put(rt);
  421. no_route:
  422. __IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
  423. return NULL;
  424. }
  425. EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);
  426. #if IS_ENABLED(CONFIG_IPV6)
  427. #define AF_INET_FAMILY(fam) ((fam) == AF_INET)
  428. #else
  429. #define AF_INET_FAMILY(fam) true
  430. #endif
  431. /* Decide when to expire the request and when to resend SYN-ACK */
  432. static inline void syn_ack_recalc(struct request_sock *req, const int thresh,
  433. const int max_retries,
  434. const u8 rskq_defer_accept,
  435. int *expire, int *resend)
  436. {
  437. if (!rskq_defer_accept) {
  438. *expire = req->num_timeout >= thresh;
  439. *resend = 1;
  440. return;
  441. }
  442. *expire = req->num_timeout >= thresh &&
  443. (!inet_rsk(req)->acked || req->num_timeout >= max_retries);
  444. /*
  445. * Do not resend while waiting for data after ACK,
  446. * start to resend on end of deferring period to give
  447. * last chance for data or ACK to create established socket.
  448. */
  449. *resend = !inet_rsk(req)->acked ||
  450. req->num_timeout >= rskq_defer_accept - 1;
  451. }
  452. int inet_rtx_syn_ack(const struct sock *parent, struct request_sock *req)
  453. {
  454. int err = req->rsk_ops->rtx_syn_ack(parent, req);
  455. if (!err)
  456. req->num_retrans++;
  457. return err;
  458. }
  459. EXPORT_SYMBOL(inet_rtx_syn_ack);
  460. /* return true if req was found in the ehash table */
  461. static bool reqsk_queue_unlink(struct request_sock_queue *queue,
  462. struct request_sock *req)
  463. {
  464. struct inet_hashinfo *hashinfo = req_to_sk(req)->sk_prot->h.hashinfo;
  465. bool found = false;
  466. if (sk_hashed(req_to_sk(req))) {
  467. spinlock_t *lock = inet_ehash_lockp(hashinfo, req->rsk_hash);
  468. spin_lock(lock);
  469. found = __sk_nulls_del_node_init_rcu(req_to_sk(req));
  470. spin_unlock(lock);
  471. }
  472. if (timer_pending(&req->rsk_timer) && del_timer_sync(&req->rsk_timer))
  473. reqsk_put(req);
  474. return found;
  475. }
  476. void inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req)
  477. {
  478. if (reqsk_queue_unlink(&inet_csk(sk)->icsk_accept_queue, req)) {
  479. reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
  480. reqsk_put(req);
  481. }
  482. }
  483. EXPORT_SYMBOL(inet_csk_reqsk_queue_drop);
  484. void inet_csk_reqsk_queue_drop_and_put(struct sock *sk, struct request_sock *req)
  485. {
  486. inet_csk_reqsk_queue_drop(sk, req);
  487. reqsk_put(req);
  488. }
  489. EXPORT_SYMBOL(inet_csk_reqsk_queue_drop_and_put);
  490. static void reqsk_timer_handler(unsigned long data)
  491. {
  492. struct request_sock *req = (struct request_sock *)data;
  493. struct sock *sk_listener = req->rsk_listener;
  494. struct net *net = sock_net(sk_listener);
  495. struct inet_connection_sock *icsk = inet_csk(sk_listener);
  496. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  497. int qlen, expire = 0, resend = 0;
  498. int max_retries, thresh;
  499. u8 defer_accept;
  500. if (sk_state_load(sk_listener) != TCP_LISTEN)
  501. goto drop;
  502. max_retries = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_synack_retries;
  503. thresh = max_retries;
  504. /* Normally all the openreqs are young and become mature
  505. * (i.e. converted to established socket) for first timeout.
  506. * If synack was not acknowledged for 1 second, it means
  507. * one of the following things: synack was lost, ack was lost,
  508. * rtt is high or nobody planned to ack (i.e. synflood).
  509. * When server is a bit loaded, queue is populated with old
  510. * open requests, reducing effective size of queue.
  511. * When server is well loaded, queue size reduces to zero
  512. * after several minutes of work. It is not synflood,
  513. * it is normal operation. The solution is pruning
  514. * too old entries overriding normal timeout, when
  515. * situation becomes dangerous.
  516. *
  517. * Essentially, we reserve half of room for young
  518. * embrions; and abort old ones without pity, if old
  519. * ones are about to clog our table.
  520. */
  521. qlen = reqsk_queue_len(queue);
  522. if ((qlen << 1) > max(8U, sk_listener->sk_max_ack_backlog)) {
  523. int young = reqsk_queue_len_young(queue) << 1;
  524. while (thresh > 2) {
  525. if (qlen < young)
  526. break;
  527. thresh--;
  528. young <<= 1;
  529. }
  530. }
  531. defer_accept = READ_ONCE(queue->rskq_defer_accept);
  532. if (defer_accept)
  533. max_retries = defer_accept;
  534. syn_ack_recalc(req, thresh, max_retries, defer_accept,
  535. &expire, &resend);
  536. req->rsk_ops->syn_ack_timeout(req);
  537. if (!expire &&
  538. (!resend ||
  539. !inet_rtx_syn_ack(sk_listener, req) ||
  540. inet_rsk(req)->acked)) {
  541. unsigned long timeo;
  542. if (req->num_timeout++ == 0)
  543. atomic_dec(&queue->young);
  544. timeo = min(TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX);
  545. mod_timer(&req->rsk_timer, jiffies + timeo);
  546. return;
  547. }
  548. drop:
  549. inet_csk_reqsk_queue_drop_and_put(sk_listener, req);
  550. }
  551. static void reqsk_queue_hash_req(struct request_sock *req,
  552. unsigned long timeout)
  553. {
  554. req->num_retrans = 0;
  555. req->num_timeout = 0;
  556. req->sk = NULL;
  557. setup_pinned_timer(&req->rsk_timer, reqsk_timer_handler,
  558. (unsigned long)req);
  559. mod_timer(&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. /* listeners have SOCK_RCU_FREE, not the children */
  596. sock_reset_flag(newsk, SOCK_RCU_FREE);
  597. inet_sk(newsk)->mc_list = NULL;
  598. newsk->sk_mark = inet_rsk(req)->ir_mark;
  599. atomic64_set(&newsk->sk_cookie,
  600. atomic64_read(&inet_rsk(req)->ir_cookie));
  601. newicsk->icsk_retransmits = 0;
  602. newicsk->icsk_backoff = 0;
  603. newicsk->icsk_probes_out = 0;
  604. /* Deinitialize accept_queue to trap illegal accesses. */
  605. memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
  606. security_inet_csk_clone(newsk, req);
  607. }
  608. return newsk;
  609. }
  610. EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
  611. /*
  612. * At this point, there should be no process reference to this
  613. * socket, and thus no user references at all. Therefore we
  614. * can assume the socket waitqueue is inactive and nobody will
  615. * try to jump onto it.
  616. */
  617. void inet_csk_destroy_sock(struct sock *sk)
  618. {
  619. WARN_ON(sk->sk_state != TCP_CLOSE);
  620. WARN_ON(!sock_flag(sk, SOCK_DEAD));
  621. /* It cannot be in hash table! */
  622. WARN_ON(!sk_unhashed(sk));
  623. /* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
  624. WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
  625. sk->sk_prot->destroy(sk);
  626. sk_stream_kill_queues(sk);
  627. xfrm_sk_free_policy(sk);
  628. sk_refcnt_debug_release(sk);
  629. local_bh_disable();
  630. percpu_counter_dec(sk->sk_prot->orphan_count);
  631. local_bh_enable();
  632. sock_put(sk);
  633. }
  634. EXPORT_SYMBOL(inet_csk_destroy_sock);
  635. /* This function allows to force a closure of a socket after the call to
  636. * tcp/dccp_create_openreq_child().
  637. */
  638. void inet_csk_prepare_forced_close(struct sock *sk)
  639. __releases(&sk->sk_lock.slock)
  640. {
  641. /* sk_clone_lock locked the socket and set refcnt to 2 */
  642. bh_unlock_sock(sk);
  643. sock_put(sk);
  644. /* The below has to be done to allow calling inet_csk_destroy_sock */
  645. sock_set_flag(sk, SOCK_DEAD);
  646. percpu_counter_inc(sk->sk_prot->orphan_count);
  647. inet_sk(sk)->inet_num = 0;
  648. }
  649. EXPORT_SYMBOL(inet_csk_prepare_forced_close);
  650. int inet_csk_listen_start(struct sock *sk, int backlog)
  651. {
  652. struct inet_connection_sock *icsk = inet_csk(sk);
  653. struct inet_sock *inet = inet_sk(sk);
  654. int err = -EADDRINUSE;
  655. reqsk_queue_alloc(&icsk->icsk_accept_queue);
  656. sk->sk_max_ack_backlog = backlog;
  657. sk->sk_ack_backlog = 0;
  658. inet_csk_delack_init(sk);
  659. /* There is race window here: we announce ourselves listening,
  660. * but this transition is still not validated by get_port().
  661. * It is OK, because this socket enters to hash table only
  662. * after validation is complete.
  663. */
  664. sk_state_store(sk, TCP_LISTEN);
  665. if (!sk->sk_prot->get_port(sk, inet->inet_num)) {
  666. inet->inet_sport = htons(inet->inet_num);
  667. sk_dst_reset(sk);
  668. err = sk->sk_prot->hash(sk);
  669. if (likely(!err))
  670. return 0;
  671. }
  672. sk->sk_state = TCP_CLOSE;
  673. return err;
  674. }
  675. EXPORT_SYMBOL_GPL(inet_csk_listen_start);
  676. static void inet_child_forget(struct sock *sk, struct request_sock *req,
  677. struct sock *child)
  678. {
  679. sk->sk_prot->disconnect(child, O_NONBLOCK);
  680. sock_orphan(child);
  681. percpu_counter_inc(sk->sk_prot->orphan_count);
  682. if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
  683. BUG_ON(tcp_sk(child)->fastopen_rsk != req);
  684. BUG_ON(sk != req->rsk_listener);
  685. /* Paranoid, to prevent race condition if
  686. * an inbound pkt destined for child is
  687. * blocked by sock lock in tcp_v4_rcv().
  688. * Also to satisfy an assertion in
  689. * tcp_v4_destroy_sock().
  690. */
  691. tcp_sk(child)->fastopen_rsk = NULL;
  692. }
  693. inet_csk_destroy_sock(child);
  694. reqsk_put(req);
  695. }
  696. struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
  697. struct request_sock *req,
  698. struct sock *child)
  699. {
  700. struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
  701. spin_lock(&queue->rskq_lock);
  702. if (unlikely(sk->sk_state != TCP_LISTEN)) {
  703. inet_child_forget(sk, req, child);
  704. child = NULL;
  705. } else {
  706. req->sk = child;
  707. req->dl_next = NULL;
  708. if (queue->rskq_accept_head == NULL)
  709. queue->rskq_accept_head = req;
  710. else
  711. queue->rskq_accept_tail->dl_next = req;
  712. queue->rskq_accept_tail = req;
  713. sk_acceptq_added(sk);
  714. }
  715. spin_unlock(&queue->rskq_lock);
  716. return child;
  717. }
  718. EXPORT_SYMBOL(inet_csk_reqsk_queue_add);
  719. struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child,
  720. struct request_sock *req, bool own_req)
  721. {
  722. if (own_req) {
  723. inet_csk_reqsk_queue_drop(sk, req);
  724. reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
  725. if (inet_csk_reqsk_queue_add(sk, req, child))
  726. return child;
  727. }
  728. /* Too bad, another child took ownership of the request, undo. */
  729. bh_unlock_sock(child);
  730. sock_put(child);
  731. return NULL;
  732. }
  733. EXPORT_SYMBOL(inet_csk_complete_hashdance);
  734. /*
  735. * This routine closes sockets which have been at least partially
  736. * opened, but not yet accepted.
  737. */
  738. void inet_csk_listen_stop(struct sock *sk)
  739. {
  740. struct inet_connection_sock *icsk = inet_csk(sk);
  741. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  742. struct request_sock *next, *req;
  743. /* Following specs, it would be better either to send FIN
  744. * (and enter FIN-WAIT-1, it is normal close)
  745. * or to send active reset (abort).
  746. * Certainly, it is pretty dangerous while synflood, but it is
  747. * bad justification for our negligence 8)
  748. * To be honest, we are not able to make either
  749. * of the variants now. --ANK
  750. */
  751. while ((req = reqsk_queue_remove(queue, sk)) != NULL) {
  752. struct sock *child = req->sk;
  753. local_bh_disable();
  754. bh_lock_sock(child);
  755. WARN_ON(sock_owned_by_user(child));
  756. sock_hold(child);
  757. inet_child_forget(sk, req, child);
  758. bh_unlock_sock(child);
  759. local_bh_enable();
  760. sock_put(child);
  761. cond_resched();
  762. }
  763. if (queue->fastopenq.rskq_rst_head) {
  764. /* Free all the reqs queued in rskq_rst_head. */
  765. spin_lock_bh(&queue->fastopenq.lock);
  766. req = queue->fastopenq.rskq_rst_head;
  767. queue->fastopenq.rskq_rst_head = NULL;
  768. spin_unlock_bh(&queue->fastopenq.lock);
  769. while (req != NULL) {
  770. next = req->dl_next;
  771. reqsk_put(req);
  772. req = next;
  773. }
  774. }
  775. WARN_ON_ONCE(sk->sk_ack_backlog);
  776. }
  777. EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
  778. void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
  779. {
  780. struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
  781. const struct inet_sock *inet = inet_sk(sk);
  782. sin->sin_family = AF_INET;
  783. sin->sin_addr.s_addr = inet->inet_daddr;
  784. sin->sin_port = inet->inet_dport;
  785. }
  786. EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
  787. #ifdef CONFIG_COMPAT
  788. int inet_csk_compat_getsockopt(struct sock *sk, int level, int optname,
  789. char __user *optval, int __user *optlen)
  790. {
  791. const struct inet_connection_sock *icsk = inet_csk(sk);
  792. if (icsk->icsk_af_ops->compat_getsockopt)
  793. return icsk->icsk_af_ops->compat_getsockopt(sk, level, optname,
  794. optval, optlen);
  795. return icsk->icsk_af_ops->getsockopt(sk, level, optname,
  796. optval, optlen);
  797. }
  798. EXPORT_SYMBOL_GPL(inet_csk_compat_getsockopt);
  799. int inet_csk_compat_setsockopt(struct sock *sk, int level, int optname,
  800. char __user *optval, unsigned int optlen)
  801. {
  802. const struct inet_connection_sock *icsk = inet_csk(sk);
  803. if (icsk->icsk_af_ops->compat_setsockopt)
  804. return icsk->icsk_af_ops->compat_setsockopt(sk, level, optname,
  805. optval, optlen);
  806. return icsk->icsk_af_ops->setsockopt(sk, level, optname,
  807. optval, optlen);
  808. }
  809. EXPORT_SYMBOL_GPL(inet_csk_compat_setsockopt);
  810. #endif
  811. static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
  812. {
  813. const struct inet_sock *inet = inet_sk(sk);
  814. const struct ip_options_rcu *inet_opt;
  815. __be32 daddr = inet->inet_daddr;
  816. struct flowi4 *fl4;
  817. struct rtable *rt;
  818. rcu_read_lock();
  819. inet_opt = rcu_dereference(inet->inet_opt);
  820. if (inet_opt && inet_opt->opt.srr)
  821. daddr = inet_opt->opt.faddr;
  822. fl4 = &fl->u.ip4;
  823. rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
  824. inet->inet_saddr, inet->inet_dport,
  825. inet->inet_sport, sk->sk_protocol,
  826. RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
  827. if (IS_ERR(rt))
  828. rt = NULL;
  829. if (rt)
  830. sk_setup_caps(sk, &rt->dst);
  831. rcu_read_unlock();
  832. return &rt->dst;
  833. }
  834. struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
  835. {
  836. struct dst_entry *dst = __sk_dst_check(sk, 0);
  837. struct inet_sock *inet = inet_sk(sk);
  838. if (!dst) {
  839. dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
  840. if (!dst)
  841. goto out;
  842. }
  843. dst->ops->update_pmtu(dst, sk, NULL, mtu);
  844. dst = __sk_dst_check(sk, 0);
  845. if (!dst)
  846. dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
  847. out:
  848. return dst;
  849. }
  850. EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);