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 = ireq->opt;
  372. struct rtable *rt;
  373. flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
  374. RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
  375. sk->sk_protocol, inet_sk_flowi_flags(sk),
  376. (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
  377. ireq->ir_loc_addr, ireq->ir_rmt_port,
  378. htons(ireq->ir_num));
  379. security_req_classify_flow(req, flowi4_to_flowi(fl4));
  380. rt = ip_route_output_flow(net, fl4, sk);
  381. if (IS_ERR(rt))
  382. goto no_route;
  383. if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
  384. goto route_err;
  385. return &rt->dst;
  386. route_err:
  387. ip_rt_put(rt);
  388. no_route:
  389. __IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
  390. return NULL;
  391. }
  392. EXPORT_SYMBOL_GPL(inet_csk_route_req);
  393. struct dst_entry *inet_csk_route_child_sock(const struct sock *sk,
  394. struct sock *newsk,
  395. const struct request_sock *req)
  396. {
  397. const struct inet_request_sock *ireq = inet_rsk(req);
  398. struct net *net = read_pnet(&ireq->ireq_net);
  399. struct inet_sock *newinet = inet_sk(newsk);
  400. struct ip_options_rcu *opt;
  401. struct flowi4 *fl4;
  402. struct rtable *rt;
  403. fl4 = &newinet->cork.fl.u.ip4;
  404. rcu_read_lock();
  405. opt = rcu_dereference(newinet->inet_opt);
  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. rcu_read_unlock();
  419. return &rt->dst;
  420. route_err:
  421. ip_rt_put(rt);
  422. no_route:
  423. rcu_read_unlock();
  424. __IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
  425. return NULL;
  426. }
  427. EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);
  428. #if IS_ENABLED(CONFIG_IPV6)
  429. #define AF_INET_FAMILY(fam) ((fam) == AF_INET)
  430. #else
  431. #define AF_INET_FAMILY(fam) true
  432. #endif
  433. /* Decide when to expire the request and when to resend SYN-ACK */
  434. static inline void syn_ack_recalc(struct request_sock *req, const int thresh,
  435. const int max_retries,
  436. const u8 rskq_defer_accept,
  437. int *expire, int *resend)
  438. {
  439. if (!rskq_defer_accept) {
  440. *expire = req->num_timeout >= thresh;
  441. *resend = 1;
  442. return;
  443. }
  444. *expire = req->num_timeout >= thresh &&
  445. (!inet_rsk(req)->acked || req->num_timeout >= max_retries);
  446. /*
  447. * Do not resend while waiting for data after ACK,
  448. * start to resend on end of deferring period to give
  449. * last chance for data or ACK to create established socket.
  450. */
  451. *resend = !inet_rsk(req)->acked ||
  452. req->num_timeout >= rskq_defer_accept - 1;
  453. }
  454. int inet_rtx_syn_ack(const struct sock *parent, struct request_sock *req)
  455. {
  456. int err = req->rsk_ops->rtx_syn_ack(parent, req);
  457. if (!err)
  458. req->num_retrans++;
  459. return err;
  460. }
  461. EXPORT_SYMBOL(inet_rtx_syn_ack);
  462. /* return true if req was found in the ehash table */
  463. static bool reqsk_queue_unlink(struct request_sock_queue *queue,
  464. struct request_sock *req)
  465. {
  466. struct inet_hashinfo *hashinfo = req_to_sk(req)->sk_prot->h.hashinfo;
  467. bool found = false;
  468. if (sk_hashed(req_to_sk(req))) {
  469. spinlock_t *lock = inet_ehash_lockp(hashinfo, req->rsk_hash);
  470. spin_lock(lock);
  471. found = __sk_nulls_del_node_init_rcu(req_to_sk(req));
  472. spin_unlock(lock);
  473. }
  474. if (timer_pending(&req->rsk_timer) && del_timer_sync(&req->rsk_timer))
  475. reqsk_put(req);
  476. return found;
  477. }
  478. void inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req)
  479. {
  480. if (reqsk_queue_unlink(&inet_csk(sk)->icsk_accept_queue, req)) {
  481. reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
  482. reqsk_put(req);
  483. }
  484. }
  485. EXPORT_SYMBOL(inet_csk_reqsk_queue_drop);
  486. void inet_csk_reqsk_queue_drop_and_put(struct sock *sk, struct request_sock *req)
  487. {
  488. inet_csk_reqsk_queue_drop(sk, req);
  489. reqsk_put(req);
  490. }
  491. EXPORT_SYMBOL(inet_csk_reqsk_queue_drop_and_put);
  492. static void reqsk_timer_handler(unsigned long data)
  493. {
  494. struct request_sock *req = (struct request_sock *)data;
  495. struct sock *sk_listener = req->rsk_listener;
  496. struct net *net = sock_net(sk_listener);
  497. struct inet_connection_sock *icsk = inet_csk(sk_listener);
  498. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  499. int qlen, expire = 0, resend = 0;
  500. int max_retries, thresh;
  501. u8 defer_accept;
  502. if (sk_state_load(sk_listener) != TCP_LISTEN)
  503. goto drop;
  504. max_retries = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_synack_retries;
  505. thresh = max_retries;
  506. /* Normally all the openreqs are young and become mature
  507. * (i.e. converted to established socket) for first timeout.
  508. * If synack was not acknowledged for 1 second, it means
  509. * one of the following things: synack was lost, ack was lost,
  510. * rtt is high or nobody planned to ack (i.e. synflood).
  511. * When server is a bit loaded, queue is populated with old
  512. * open requests, reducing effective size of queue.
  513. * When server is well loaded, queue size reduces to zero
  514. * after several minutes of work. It is not synflood,
  515. * it is normal operation. The solution is pruning
  516. * too old entries overriding normal timeout, when
  517. * situation becomes dangerous.
  518. *
  519. * Essentially, we reserve half of room for young
  520. * embrions; and abort old ones without pity, if old
  521. * ones are about to clog our table.
  522. */
  523. qlen = reqsk_queue_len(queue);
  524. if ((qlen << 1) > max(8U, sk_listener->sk_max_ack_backlog)) {
  525. int young = reqsk_queue_len_young(queue) << 1;
  526. while (thresh > 2) {
  527. if (qlen < young)
  528. break;
  529. thresh--;
  530. young <<= 1;
  531. }
  532. }
  533. defer_accept = READ_ONCE(queue->rskq_defer_accept);
  534. if (defer_accept)
  535. max_retries = defer_accept;
  536. syn_ack_recalc(req, thresh, max_retries, defer_accept,
  537. &expire, &resend);
  538. req->rsk_ops->syn_ack_timeout(req);
  539. if (!expire &&
  540. (!resend ||
  541. !inet_rtx_syn_ack(sk_listener, req) ||
  542. inet_rsk(req)->acked)) {
  543. unsigned long timeo;
  544. if (req->num_timeout++ == 0)
  545. atomic_dec(&queue->young);
  546. timeo = min(TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX);
  547. mod_timer(&req->rsk_timer, jiffies + timeo);
  548. return;
  549. }
  550. drop:
  551. inet_csk_reqsk_queue_drop_and_put(sk_listener, req);
  552. }
  553. static void reqsk_queue_hash_req(struct request_sock *req,
  554. unsigned long timeout)
  555. {
  556. req->num_retrans = 0;
  557. req->num_timeout = 0;
  558. req->sk = NULL;
  559. setup_pinned_timer(&req->rsk_timer, reqsk_timer_handler,
  560. (unsigned long)req);
  561. mod_timer(&req->rsk_timer, jiffies + timeout);
  562. inet_ehash_insert(req_to_sk(req), NULL);
  563. /* before letting lookups find us, make sure all req fields
  564. * are committed to memory and refcnt initialized.
  565. */
  566. smp_wmb();
  567. atomic_set(&req->rsk_refcnt, 2 + 1);
  568. }
  569. void inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
  570. unsigned long timeout)
  571. {
  572. reqsk_queue_hash_req(req, timeout);
  573. inet_csk_reqsk_queue_added(sk);
  574. }
  575. EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
  576. /**
  577. * inet_csk_clone_lock - clone an inet socket, and lock its clone
  578. * @sk: the socket to clone
  579. * @req: request_sock
  580. * @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
  581. *
  582. * Caller must unlock socket even in error path (bh_unlock_sock(newsk))
  583. */
  584. struct sock *inet_csk_clone_lock(const struct sock *sk,
  585. const struct request_sock *req,
  586. const gfp_t priority)
  587. {
  588. struct sock *newsk = sk_clone_lock(sk, priority);
  589. if (newsk) {
  590. struct inet_connection_sock *newicsk = inet_csk(newsk);
  591. newsk->sk_state = TCP_SYN_RECV;
  592. newicsk->icsk_bind_hash = NULL;
  593. inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
  594. inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
  595. inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
  596. newsk->sk_write_space = sk_stream_write_space;
  597. /* listeners have SOCK_RCU_FREE, not the children */
  598. sock_reset_flag(newsk, SOCK_RCU_FREE);
  599. inet_sk(newsk)->mc_list = NULL;
  600. newsk->sk_mark = inet_rsk(req)->ir_mark;
  601. atomic64_set(&newsk->sk_cookie,
  602. atomic64_read(&inet_rsk(req)->ir_cookie));
  603. newicsk->icsk_retransmits = 0;
  604. newicsk->icsk_backoff = 0;
  605. newicsk->icsk_probes_out = 0;
  606. /* Deinitialize accept_queue to trap illegal accesses. */
  607. memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
  608. security_inet_csk_clone(newsk, req);
  609. }
  610. return newsk;
  611. }
  612. EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
  613. /*
  614. * At this point, there should be no process reference to this
  615. * socket, and thus no user references at all. Therefore we
  616. * can assume the socket waitqueue is inactive and nobody will
  617. * try to jump onto it.
  618. */
  619. void inet_csk_destroy_sock(struct sock *sk)
  620. {
  621. WARN_ON(sk->sk_state != TCP_CLOSE);
  622. WARN_ON(!sock_flag(sk, SOCK_DEAD));
  623. /* It cannot be in hash table! */
  624. WARN_ON(!sk_unhashed(sk));
  625. /* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
  626. WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
  627. sk->sk_prot->destroy(sk);
  628. sk_stream_kill_queues(sk);
  629. xfrm_sk_free_policy(sk);
  630. sk_refcnt_debug_release(sk);
  631. local_bh_disable();
  632. percpu_counter_dec(sk->sk_prot->orphan_count);
  633. local_bh_enable();
  634. sock_put(sk);
  635. }
  636. EXPORT_SYMBOL(inet_csk_destroy_sock);
  637. /* This function allows to force a closure of a socket after the call to
  638. * tcp/dccp_create_openreq_child().
  639. */
  640. void inet_csk_prepare_forced_close(struct sock *sk)
  641. __releases(&sk->sk_lock.slock)
  642. {
  643. /* sk_clone_lock locked the socket and set refcnt to 2 */
  644. bh_unlock_sock(sk);
  645. sock_put(sk);
  646. /* The below has to be done to allow calling inet_csk_destroy_sock */
  647. sock_set_flag(sk, SOCK_DEAD);
  648. percpu_counter_inc(sk->sk_prot->orphan_count);
  649. inet_sk(sk)->inet_num = 0;
  650. }
  651. EXPORT_SYMBOL(inet_csk_prepare_forced_close);
  652. int inet_csk_listen_start(struct sock *sk, int backlog)
  653. {
  654. struct inet_connection_sock *icsk = inet_csk(sk);
  655. struct inet_sock *inet = inet_sk(sk);
  656. int err = -EADDRINUSE;
  657. reqsk_queue_alloc(&icsk->icsk_accept_queue);
  658. sk->sk_max_ack_backlog = backlog;
  659. sk->sk_ack_backlog = 0;
  660. inet_csk_delack_init(sk);
  661. /* There is race window here: we announce ourselves listening,
  662. * but this transition is still not validated by get_port().
  663. * It is OK, because this socket enters to hash table only
  664. * after validation is complete.
  665. */
  666. sk_state_store(sk, TCP_LISTEN);
  667. if (!sk->sk_prot->get_port(sk, inet->inet_num)) {
  668. inet->inet_sport = htons(inet->inet_num);
  669. sk_dst_reset(sk);
  670. err = sk->sk_prot->hash(sk);
  671. if (likely(!err))
  672. return 0;
  673. }
  674. sk->sk_state = TCP_CLOSE;
  675. return err;
  676. }
  677. EXPORT_SYMBOL_GPL(inet_csk_listen_start);
  678. static void inet_child_forget(struct sock *sk, struct request_sock *req,
  679. struct sock *child)
  680. {
  681. sk->sk_prot->disconnect(child, O_NONBLOCK);
  682. sock_orphan(child);
  683. percpu_counter_inc(sk->sk_prot->orphan_count);
  684. if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
  685. BUG_ON(tcp_sk(child)->fastopen_rsk != req);
  686. BUG_ON(sk != req->rsk_listener);
  687. /* Paranoid, to prevent race condition if
  688. * an inbound pkt destined for child is
  689. * blocked by sock lock in tcp_v4_rcv().
  690. * Also to satisfy an assertion in
  691. * tcp_v4_destroy_sock().
  692. */
  693. tcp_sk(child)->fastopen_rsk = NULL;
  694. }
  695. inet_csk_destroy_sock(child);
  696. reqsk_put(req);
  697. }
  698. struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
  699. struct request_sock *req,
  700. struct sock *child)
  701. {
  702. struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
  703. spin_lock(&queue->rskq_lock);
  704. if (unlikely(sk->sk_state != TCP_LISTEN)) {
  705. inet_child_forget(sk, req, child);
  706. child = NULL;
  707. } else {
  708. req->sk = child;
  709. req->dl_next = NULL;
  710. if (queue->rskq_accept_head == NULL)
  711. queue->rskq_accept_head = req;
  712. else
  713. queue->rskq_accept_tail->dl_next = req;
  714. queue->rskq_accept_tail = req;
  715. sk_acceptq_added(sk);
  716. }
  717. spin_unlock(&queue->rskq_lock);
  718. return child;
  719. }
  720. EXPORT_SYMBOL(inet_csk_reqsk_queue_add);
  721. struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child,
  722. struct request_sock *req, bool own_req)
  723. {
  724. if (own_req) {
  725. inet_csk_reqsk_queue_drop(sk, req);
  726. reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
  727. if (inet_csk_reqsk_queue_add(sk, req, child))
  728. return child;
  729. }
  730. /* Too bad, another child took ownership of the request, undo. */
  731. bh_unlock_sock(child);
  732. sock_put(child);
  733. return NULL;
  734. }
  735. EXPORT_SYMBOL(inet_csk_complete_hashdance);
  736. /*
  737. * This routine closes sockets which have been at least partially
  738. * opened, but not yet accepted.
  739. */
  740. void inet_csk_listen_stop(struct sock *sk)
  741. {
  742. struct inet_connection_sock *icsk = inet_csk(sk);
  743. struct request_sock_queue *queue = &icsk->icsk_accept_queue;
  744. struct request_sock *next, *req;
  745. /* Following specs, it would be better either to send FIN
  746. * (and enter FIN-WAIT-1, it is normal close)
  747. * or to send active reset (abort).
  748. * Certainly, it is pretty dangerous while synflood, but it is
  749. * bad justification for our negligence 8)
  750. * To be honest, we are not able to make either
  751. * of the variants now. --ANK
  752. */
  753. while ((req = reqsk_queue_remove(queue, sk)) != NULL) {
  754. struct sock *child = req->sk;
  755. local_bh_disable();
  756. bh_lock_sock(child);
  757. WARN_ON(sock_owned_by_user(child));
  758. sock_hold(child);
  759. inet_child_forget(sk, req, child);
  760. bh_unlock_sock(child);
  761. local_bh_enable();
  762. sock_put(child);
  763. cond_resched();
  764. }
  765. if (queue->fastopenq.rskq_rst_head) {
  766. /* Free all the reqs queued in rskq_rst_head. */
  767. spin_lock_bh(&queue->fastopenq.lock);
  768. req = queue->fastopenq.rskq_rst_head;
  769. queue->fastopenq.rskq_rst_head = NULL;
  770. spin_unlock_bh(&queue->fastopenq.lock);
  771. while (req != NULL) {
  772. next = req->dl_next;
  773. reqsk_put(req);
  774. req = next;
  775. }
  776. }
  777. WARN_ON_ONCE(sk->sk_ack_backlog);
  778. }
  779. EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
  780. void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
  781. {
  782. struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
  783. const struct inet_sock *inet = inet_sk(sk);
  784. sin->sin_family = AF_INET;
  785. sin->sin_addr.s_addr = inet->inet_daddr;
  786. sin->sin_port = inet->inet_dport;
  787. }
  788. EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
  789. #ifdef CONFIG_COMPAT
  790. int inet_csk_compat_getsockopt(struct sock *sk, int level, int optname,
  791. char __user *optval, int __user *optlen)
  792. {
  793. const struct inet_connection_sock *icsk = inet_csk(sk);
  794. if (icsk->icsk_af_ops->compat_getsockopt)
  795. return icsk->icsk_af_ops->compat_getsockopt(sk, level, optname,
  796. optval, optlen);
  797. return icsk->icsk_af_ops->getsockopt(sk, level, optname,
  798. optval, optlen);
  799. }
  800. EXPORT_SYMBOL_GPL(inet_csk_compat_getsockopt);
  801. int inet_csk_compat_setsockopt(struct sock *sk, int level, int optname,
  802. char __user *optval, unsigned int optlen)
  803. {
  804. const struct inet_connection_sock *icsk = inet_csk(sk);
  805. if (icsk->icsk_af_ops->compat_setsockopt)
  806. return icsk->icsk_af_ops->compat_setsockopt(sk, level, optname,
  807. optval, optlen);
  808. return icsk->icsk_af_ops->setsockopt(sk, level, optname,
  809. optval, optlen);
  810. }
  811. EXPORT_SYMBOL_GPL(inet_csk_compat_setsockopt);
  812. #endif
  813. static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
  814. {
  815. const struct inet_sock *inet = inet_sk(sk);
  816. const struct ip_options_rcu *inet_opt;
  817. __be32 daddr = inet->inet_daddr;
  818. struct flowi4 *fl4;
  819. struct rtable *rt;
  820. rcu_read_lock();
  821. inet_opt = rcu_dereference(inet->inet_opt);
  822. if (inet_opt && inet_opt->opt.srr)
  823. daddr = inet_opt->opt.faddr;
  824. fl4 = &fl->u.ip4;
  825. rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
  826. inet->inet_saddr, inet->inet_dport,
  827. inet->inet_sport, sk->sk_protocol,
  828. RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
  829. if (IS_ERR(rt))
  830. rt = NULL;
  831. if (rt)
  832. sk_setup_caps(sk, &rt->dst);
  833. rcu_read_unlock();
  834. return &rt->dst;
  835. }
  836. struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
  837. {
  838. struct dst_entry *dst = __sk_dst_check(sk, 0);
  839. struct inet_sock *inet = inet_sk(sk);
  840. if (!dst) {
  841. dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
  842. if (!dst)
  843. goto out;
  844. }
  845. dst->ops->update_pmtu(dst, sk, NULL, mtu);
  846. dst = __sk_dst_check(sk, 0);
  847. if (!dst)
  848. dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
  849. out:
  850. return dst;
  851. }
  852. EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);