inet_connection_sock.c 27 KB

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