inet_connection_sock.c 27 KB

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