GNU Linux-libre 4.14.251-gnu1
[releases.git] / net / ipv4 / inet_connection_sock.c
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
16 #include <linux/module.h>
17 #include <linux/jhash.h>
18
19 #include <net/inet_connection_sock.h>
20 #include <net/inet_hashtables.h>
21 #include <net/inet_timewait_sock.h>
22 #include <net/ip.h>
23 #include <net/route.h>
24 #include <net/tcp_states.h>
25 #include <net/xfrm.h>
26 #include <net/tcp.h>
27 #include <net/sock_reuseport.h>
28 #include <net/addrconf.h>
29
30 #ifdef INET_CSK_DEBUG
31 const char inet_csk_timer_bug_msg[] = "inet_csk BUG: unknown timer value\n";
32 EXPORT_SYMBOL(inet_csk_timer_bug_msg);
33 #endif
34
35 #if IS_ENABLED(CONFIG_IPV6)
36 /* match_wildcard == true:  IPV6_ADDR_ANY equals to any IPv6 addresses if IPv6
37  *                          only, and any IPv4 addresses if not IPv6 only
38  * match_wildcard == false: addresses must be exactly the same, i.e.
39  *                          IPV6_ADDR_ANY only equals to IPV6_ADDR_ANY,
40  *                          and 0.0.0.0 equals to 0.0.0.0 only
41  */
42 static int ipv6_rcv_saddr_equal(const struct in6_addr *sk1_rcv_saddr6,
43                                 const struct in6_addr *sk2_rcv_saddr6,
44                                 __be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
45                                 bool sk1_ipv6only, bool sk2_ipv6only,
46                                 bool match_wildcard)
47 {
48         int addr_type = ipv6_addr_type(sk1_rcv_saddr6);
49         int addr_type2 = sk2_rcv_saddr6 ? ipv6_addr_type(sk2_rcv_saddr6) : IPV6_ADDR_MAPPED;
50
51         /* if both are mapped, treat as IPv4 */
52         if (addr_type == IPV6_ADDR_MAPPED && addr_type2 == IPV6_ADDR_MAPPED) {
53                 if (!sk2_ipv6only) {
54                         if (sk1_rcv_saddr == sk2_rcv_saddr)
55                                 return 1;
56                         if (!sk1_rcv_saddr || !sk2_rcv_saddr)
57                                 return match_wildcard;
58                 }
59                 return 0;
60         }
61
62         if (addr_type == IPV6_ADDR_ANY && addr_type2 == IPV6_ADDR_ANY)
63                 return 1;
64
65         if (addr_type2 == IPV6_ADDR_ANY && match_wildcard &&
66             !(sk2_ipv6only && addr_type == IPV6_ADDR_MAPPED))
67                 return 1;
68
69         if (addr_type == IPV6_ADDR_ANY && match_wildcard &&
70             !(sk1_ipv6only && addr_type2 == IPV6_ADDR_MAPPED))
71                 return 1;
72
73         if (sk2_rcv_saddr6 &&
74             ipv6_addr_equal(sk1_rcv_saddr6, sk2_rcv_saddr6))
75                 return 1;
76
77         return 0;
78 }
79 #endif
80
81 /* match_wildcard == true:  0.0.0.0 equals to any IPv4 addresses
82  * match_wildcard == false: addresses must be exactly the same, i.e.
83  *                          0.0.0.0 only equals to 0.0.0.0
84  */
85 static int ipv4_rcv_saddr_equal(__be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
86                                 bool sk2_ipv6only, bool match_wildcard)
87 {
88         if (!sk2_ipv6only) {
89                 if (sk1_rcv_saddr == sk2_rcv_saddr)
90                         return 1;
91                 if (!sk1_rcv_saddr || !sk2_rcv_saddr)
92                         return match_wildcard;
93         }
94         return 0;
95 }
96
97 int inet_rcv_saddr_equal(const struct sock *sk, const struct sock *sk2,
98                          bool match_wildcard)
99 {
100 #if IS_ENABLED(CONFIG_IPV6)
101         if (sk->sk_family == AF_INET6)
102                 return ipv6_rcv_saddr_equal(&sk->sk_v6_rcv_saddr,
103                                             inet6_rcv_saddr(sk2),
104                                             sk->sk_rcv_saddr,
105                                             sk2->sk_rcv_saddr,
106                                             ipv6_only_sock(sk),
107                                             ipv6_only_sock(sk2),
108                                             match_wildcard);
109 #endif
110         return ipv4_rcv_saddr_equal(sk->sk_rcv_saddr, sk2->sk_rcv_saddr,
111                                     ipv6_only_sock(sk2), match_wildcard);
112 }
113 EXPORT_SYMBOL(inet_rcv_saddr_equal);
114
115 void inet_get_local_port_range(struct net *net, int *low, int *high)
116 {
117         unsigned int seq;
118
119         do {
120                 seq = read_seqbegin(&net->ipv4.ip_local_ports.lock);
121
122                 *low = net->ipv4.ip_local_ports.range[0];
123                 *high = net->ipv4.ip_local_ports.range[1];
124         } while (read_seqretry(&net->ipv4.ip_local_ports.lock, seq));
125 }
126 EXPORT_SYMBOL(inet_get_local_port_range);
127
128 static int inet_csk_bind_conflict(const struct sock *sk,
129                                   const struct inet_bind_bucket *tb,
130                                   bool relax, bool reuseport_ok)
131 {
132         struct sock *sk2;
133         bool reuse = sk->sk_reuse;
134         bool reuseport = !!sk->sk_reuseport && reuseport_ok;
135         kuid_t uid = sock_i_uid((struct sock *)sk);
136
137         /*
138          * Unlike other sk lookup places we do not check
139          * for sk_net here, since _all_ the socks listed
140          * in tb->owners list belong to the same net - the
141          * one this bucket belongs to.
142          */
143
144         sk_for_each_bound(sk2, &tb->owners) {
145                 if (sk != sk2 &&
146                     (!sk->sk_bound_dev_if ||
147                      !sk2->sk_bound_dev_if ||
148                      sk->sk_bound_dev_if == sk2->sk_bound_dev_if)) {
149                         if ((!reuse || !sk2->sk_reuse ||
150                             sk2->sk_state == TCP_LISTEN) &&
151                             (!reuseport || !sk2->sk_reuseport ||
152                              rcu_access_pointer(sk->sk_reuseport_cb) ||
153                              (sk2->sk_state != TCP_TIME_WAIT &&
154                              !uid_eq(uid, sock_i_uid(sk2))))) {
155                                 if (inet_rcv_saddr_equal(sk, sk2, true))
156                                         break;
157                         }
158                         if (!relax && reuse && sk2->sk_reuse &&
159                             sk2->sk_state != TCP_LISTEN) {
160                                 if (inet_rcv_saddr_equal(sk, sk2, true))
161                                         break;
162                         }
163                 }
164         }
165         return sk2 != NULL;
166 }
167
168 /*
169  * Find an open port number for the socket.  Returns with the
170  * inet_bind_hashbucket lock held.
171  */
172 static struct inet_bind_hashbucket *
173 inet_csk_find_open_port(struct sock *sk, struct inet_bind_bucket **tb_ret, int *port_ret)
174 {
175         struct inet_hashinfo *hinfo = sk->sk_prot->h.hashinfo;
176         int port = 0;
177         struct inet_bind_hashbucket *head;
178         struct net *net = sock_net(sk);
179         int i, low, high, attempt_half;
180         struct inet_bind_bucket *tb;
181         u32 remaining, offset;
182
183         attempt_half = (sk->sk_reuse == SK_CAN_REUSE) ? 1 : 0;
184 other_half_scan:
185         inet_get_local_port_range(net, &low, &high);
186         high++; /* [32768, 60999] -> [32768, 61000[ */
187         if (high - low < 4)
188                 attempt_half = 0;
189         if (attempt_half) {
190                 int half = low + (((high - low) >> 2) << 1);
191
192                 if (attempt_half == 1)
193                         high = half;
194                 else
195                         low = half;
196         }
197         remaining = high - low;
198         if (likely(remaining > 1))
199                 remaining &= ~1U;
200
201         offset = prandom_u32() % remaining;
202         /* __inet_hash_connect() favors ports having @low parity
203          * We do the opposite to not pollute connect() users.
204          */
205         offset |= 1U;
206
207 other_parity_scan:
208         port = low + offset;
209         for (i = 0; i < remaining; i += 2, port += 2) {
210                 if (unlikely(port >= high))
211                         port -= remaining;
212                 if (inet_is_local_reserved_port(net, port))
213                         continue;
214                 head = &hinfo->bhash[inet_bhashfn(net, port,
215                                                   hinfo->bhash_size)];
216                 spin_lock_bh(&head->lock);
217                 inet_bind_bucket_for_each(tb, &head->chain)
218                         if (net_eq(ib_net(tb), net) && tb->port == port) {
219                                 if (!inet_csk_bind_conflict(sk, tb, false, false))
220                                         goto success;
221                                 goto next_port;
222                         }
223                 tb = NULL;
224                 goto success;
225 next_port:
226                 spin_unlock_bh(&head->lock);
227                 cond_resched();
228         }
229
230         offset--;
231         if (!(offset & 1))
232                 goto other_parity_scan;
233
234         if (attempt_half == 1) {
235                 /* OK we now try the upper half of the range */
236                 attempt_half = 2;
237                 goto other_half_scan;
238         }
239         return NULL;
240 success:
241         *port_ret = port;
242         *tb_ret = tb;
243         return head;
244 }
245
246 static inline int sk_reuseport_match(struct inet_bind_bucket *tb,
247                                      struct sock *sk)
248 {
249         kuid_t uid = sock_i_uid(sk);
250
251         if (tb->fastreuseport <= 0)
252                 return 0;
253         if (!sk->sk_reuseport)
254                 return 0;
255         if (rcu_access_pointer(sk->sk_reuseport_cb))
256                 return 0;
257         if (!uid_eq(tb->fastuid, uid))
258                 return 0;
259         /* We only need to check the rcv_saddr if this tb was once marked
260          * without fastreuseport and then was reset, as we can only know that
261          * the fast_*rcv_saddr doesn't have any conflicts with the socks on the
262          * owners list.
263          */
264         if (tb->fastreuseport == FASTREUSEPORT_ANY)
265                 return 1;
266 #if IS_ENABLED(CONFIG_IPV6)
267         if (tb->fast_sk_family == AF_INET6)
268                 return ipv6_rcv_saddr_equal(&tb->fast_v6_rcv_saddr,
269                                             inet6_rcv_saddr(sk),
270                                             tb->fast_rcv_saddr,
271                                             sk->sk_rcv_saddr,
272                                             tb->fast_ipv6_only,
273                                             ipv6_only_sock(sk), true);
274 #endif
275         return ipv4_rcv_saddr_equal(tb->fast_rcv_saddr, sk->sk_rcv_saddr,
276                                     ipv6_only_sock(sk), true);
277 }
278
279 void inet_csk_update_fastreuse(struct inet_bind_bucket *tb,
280                                struct sock *sk)
281 {
282         kuid_t uid = sock_i_uid(sk);
283         bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
284
285         if (hlist_empty(&tb->owners)) {
286                 tb->fastreuse = reuse;
287                 if (sk->sk_reuseport) {
288                         tb->fastreuseport = FASTREUSEPORT_ANY;
289                         tb->fastuid = uid;
290                         tb->fast_rcv_saddr = sk->sk_rcv_saddr;
291                         tb->fast_ipv6_only = ipv6_only_sock(sk);
292                         tb->fast_sk_family = sk->sk_family;
293 #if IS_ENABLED(CONFIG_IPV6)
294                         tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
295 #endif
296                 } else {
297                         tb->fastreuseport = 0;
298                 }
299         } else {
300                 if (!reuse)
301                         tb->fastreuse = 0;
302                 if (sk->sk_reuseport) {
303                         /* We didn't match or we don't have fastreuseport set on
304                          * the tb, but we have sk_reuseport set on this socket
305                          * and we know that there are no bind conflicts with
306                          * this socket in this tb, so reset our tb's reuseport
307                          * settings so that any subsequent sockets that match
308                          * our current socket will be put on the fast path.
309                          *
310                          * If we reset we need to set FASTREUSEPORT_STRICT so we
311                          * do extra checking for all subsequent sk_reuseport
312                          * socks.
313                          */
314                         if (!sk_reuseport_match(tb, sk)) {
315                                 tb->fastreuseport = FASTREUSEPORT_STRICT;
316                                 tb->fastuid = uid;
317                                 tb->fast_rcv_saddr = sk->sk_rcv_saddr;
318                                 tb->fast_ipv6_only = ipv6_only_sock(sk);
319                                 tb->fast_sk_family = sk->sk_family;
320 #if IS_ENABLED(CONFIG_IPV6)
321                                 tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
322 #endif
323                         }
324                 } else {
325                         tb->fastreuseport = 0;
326                 }
327         }
328 }
329
330 /* Obtain a reference to a local port for the given sock,
331  * if snum is zero it means select any available local port.
332  * We try to allocate an odd port (and leave even ports for connect())
333  */
334 int inet_csk_get_port(struct sock *sk, unsigned short snum)
335 {
336         bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
337         struct inet_hashinfo *hinfo = sk->sk_prot->h.hashinfo;
338         int ret = 1, port = snum;
339         struct inet_bind_hashbucket *head;
340         struct net *net = sock_net(sk);
341         struct inet_bind_bucket *tb = NULL;
342
343         if (!port) {
344                 head = inet_csk_find_open_port(sk, &tb, &port);
345                 if (!head)
346                         return ret;
347                 if (!tb)
348                         goto tb_not_found;
349                 goto success;
350         }
351         head = &hinfo->bhash[inet_bhashfn(net, port,
352                                           hinfo->bhash_size)];
353         spin_lock_bh(&head->lock);
354         inet_bind_bucket_for_each(tb, &head->chain)
355                 if (net_eq(ib_net(tb), net) && tb->port == port)
356                         goto tb_found;
357 tb_not_found:
358         tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep,
359                                      net, head, port);
360         if (!tb)
361                 goto fail_unlock;
362 tb_found:
363         if (!hlist_empty(&tb->owners)) {
364                 if (sk->sk_reuse == SK_FORCE_REUSE)
365                         goto success;
366
367                 if ((tb->fastreuse > 0 && reuse) ||
368                     sk_reuseport_match(tb, sk))
369                         goto success;
370                 if (inet_csk_bind_conflict(sk, tb, true, true))
371                         goto fail_unlock;
372         }
373 success:
374         inet_csk_update_fastreuse(tb, sk);
375
376         if (!inet_csk(sk)->icsk_bind_hash)
377                 inet_bind_hash(sk, tb, port);
378         WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
379         ret = 0;
380
381 fail_unlock:
382         spin_unlock_bh(&head->lock);
383         return ret;
384 }
385 EXPORT_SYMBOL_GPL(inet_csk_get_port);
386
387 /*
388  * Wait for an incoming connection, avoid race conditions. This must be called
389  * with the socket locked.
390  */
391 static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
392 {
393         struct inet_connection_sock *icsk = inet_csk(sk);
394         DEFINE_WAIT(wait);
395         int err;
396
397         /*
398          * True wake-one mechanism for incoming connections: only
399          * one process gets woken up, not the 'whole herd'.
400          * Since we do not 'race & poll' for established sockets
401          * anymore, the common case will execute the loop only once.
402          *
403          * Subtle issue: "add_wait_queue_exclusive()" will be added
404          * after any current non-exclusive waiters, and we know that
405          * it will always _stay_ after any new non-exclusive waiters
406          * because all non-exclusive waiters are added at the
407          * beginning of the wait-queue. As such, it's ok to "drop"
408          * our exclusiveness temporarily when we get woken up without
409          * having to remove and re-insert us on the wait queue.
410          */
411         for (;;) {
412                 prepare_to_wait_exclusive(sk_sleep(sk), &wait,
413                                           TASK_INTERRUPTIBLE);
414                 release_sock(sk);
415                 if (reqsk_queue_empty(&icsk->icsk_accept_queue))
416                         timeo = schedule_timeout(timeo);
417                 sched_annotate_sleep();
418                 lock_sock(sk);
419                 err = 0;
420                 if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
421                         break;
422                 err = -EINVAL;
423                 if (sk->sk_state != TCP_LISTEN)
424                         break;
425                 err = sock_intr_errno(timeo);
426                 if (signal_pending(current))
427                         break;
428                 err = -EAGAIN;
429                 if (!timeo)
430                         break;
431         }
432         finish_wait(sk_sleep(sk), &wait);
433         return err;
434 }
435
436 /*
437  * This will accept the next outstanding connection.
438  */
439 struct sock *inet_csk_accept(struct sock *sk, int flags, int *err, bool kern)
440 {
441         struct inet_connection_sock *icsk = inet_csk(sk);
442         struct request_sock_queue *queue = &icsk->icsk_accept_queue;
443         struct request_sock *req;
444         struct sock *newsk;
445         int error;
446
447         lock_sock(sk);
448
449         /* We need to make sure that this socket is listening,
450          * and that it has something pending.
451          */
452         error = -EINVAL;
453         if (sk->sk_state != TCP_LISTEN)
454                 goto out_err;
455
456         /* Find already established connection */
457         if (reqsk_queue_empty(queue)) {
458                 long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
459
460                 /* If this is a non blocking socket don't sleep */
461                 error = -EAGAIN;
462                 if (!timeo)
463                         goto out_err;
464
465                 error = inet_csk_wait_for_connect(sk, timeo);
466                 if (error)
467                         goto out_err;
468         }
469         req = reqsk_queue_remove(queue, sk);
470         newsk = req->sk;
471
472         if (sk->sk_protocol == IPPROTO_TCP &&
473             tcp_rsk(req)->tfo_listener) {
474                 spin_lock_bh(&queue->fastopenq.lock);
475                 if (tcp_rsk(req)->tfo_listener) {
476                         /* We are still waiting for the final ACK from 3WHS
477                          * so can't free req now. Instead, we set req->sk to
478                          * NULL to signify that the child socket is taken
479                          * so reqsk_fastopen_remove() will free the req
480                          * when 3WHS finishes (or is aborted).
481                          */
482                         req->sk = NULL;
483                         req = NULL;
484                 }
485                 spin_unlock_bh(&queue->fastopenq.lock);
486         }
487
488 out:
489         release_sock(sk);
490         if (newsk && mem_cgroup_sockets_enabled) {
491                 int amt;
492
493                 /* atomically get the memory usage, set and charge the
494                  * newsk->sk_memcg.
495                  */
496                 lock_sock(newsk);
497
498                 /* The socket has not been accepted yet, no need to look at
499                  * newsk->sk_wmem_queued.
500                  */
501                 amt = sk_mem_pages(newsk->sk_forward_alloc +
502                                    atomic_read(&newsk->sk_rmem_alloc));
503                 mem_cgroup_sk_alloc(newsk);
504                 if (newsk->sk_memcg && amt)
505                         mem_cgroup_charge_skmem(newsk->sk_memcg, amt);
506
507                 release_sock(newsk);
508         }
509         if (req)
510                 reqsk_put(req);
511         return newsk;
512 out_err:
513         newsk = NULL;
514         req = NULL;
515         *err = error;
516         goto out;
517 }
518 EXPORT_SYMBOL(inet_csk_accept);
519
520 /*
521  * Using different timers for retransmit, delayed acks and probes
522  * We may wish use just one timer maintaining a list of expire jiffies
523  * to optimize.
524  */
525 void inet_csk_init_xmit_timers(struct sock *sk,
526                                void (*retransmit_handler)(unsigned long),
527                                void (*delack_handler)(unsigned long),
528                                void (*keepalive_handler)(unsigned long))
529 {
530         struct inet_connection_sock *icsk = inet_csk(sk);
531
532         setup_timer(&icsk->icsk_retransmit_timer, retransmit_handler,
533                         (unsigned long)sk);
534         setup_timer(&icsk->icsk_delack_timer, delack_handler,
535                         (unsigned long)sk);
536         setup_timer(&sk->sk_timer, keepalive_handler, (unsigned long)sk);
537         icsk->icsk_pending = icsk->icsk_ack.pending = 0;
538 }
539 EXPORT_SYMBOL(inet_csk_init_xmit_timers);
540
541 void inet_csk_clear_xmit_timers(struct sock *sk)
542 {
543         struct inet_connection_sock *icsk = inet_csk(sk);
544
545         icsk->icsk_pending = icsk->icsk_ack.pending = icsk->icsk_ack.blocked = 0;
546
547         sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
548         sk_stop_timer(sk, &icsk->icsk_delack_timer);
549         sk_stop_timer(sk, &sk->sk_timer);
550 }
551 EXPORT_SYMBOL(inet_csk_clear_xmit_timers);
552
553 void inet_csk_delete_keepalive_timer(struct sock *sk)
554 {
555         sk_stop_timer(sk, &sk->sk_timer);
556 }
557 EXPORT_SYMBOL(inet_csk_delete_keepalive_timer);
558
559 void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len)
560 {
561         sk_reset_timer(sk, &sk->sk_timer, jiffies + len);
562 }
563 EXPORT_SYMBOL(inet_csk_reset_keepalive_timer);
564
565 struct dst_entry *inet_csk_route_req(const struct sock *sk,
566                                      struct flowi4 *fl4,
567                                      const struct request_sock *req)
568 {
569         const struct inet_request_sock *ireq = inet_rsk(req);
570         struct net *net = read_pnet(&ireq->ireq_net);
571         struct ip_options_rcu *opt;
572         struct rtable *rt;
573
574         rcu_read_lock();
575         opt = rcu_dereference(ireq->ireq_opt);
576
577         flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
578                            RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
579                            sk->sk_protocol, inet_sk_flowi_flags(sk),
580                            (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
581                            ireq->ir_loc_addr, ireq->ir_rmt_port,
582                            htons(ireq->ir_num), sk->sk_uid);
583         security_req_classify_flow(req, flowi4_to_flowi(fl4));
584         rt = ip_route_output_flow(net, fl4, sk);
585         if (IS_ERR(rt))
586                 goto no_route;
587         if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
588                 goto route_err;
589         rcu_read_unlock();
590         return &rt->dst;
591
592 route_err:
593         ip_rt_put(rt);
594 no_route:
595         rcu_read_unlock();
596         __IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
597         return NULL;
598 }
599 EXPORT_SYMBOL_GPL(inet_csk_route_req);
600
601 struct dst_entry *inet_csk_route_child_sock(const struct sock *sk,
602                                             struct sock *newsk,
603                                             const struct request_sock *req)
604 {
605         const struct inet_request_sock *ireq = inet_rsk(req);
606         struct net *net = read_pnet(&ireq->ireq_net);
607         struct inet_sock *newinet = inet_sk(newsk);
608         struct ip_options_rcu *opt;
609         struct flowi4 *fl4;
610         struct rtable *rt;
611
612         opt = rcu_dereference(ireq->ireq_opt);
613         fl4 = &newinet->cork.fl.u.ip4;
614
615         flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
616                            RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
617                            sk->sk_protocol, inet_sk_flowi_flags(sk),
618                            (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
619                            ireq->ir_loc_addr, ireq->ir_rmt_port,
620                            htons(ireq->ir_num), sk->sk_uid);
621         security_req_classify_flow(req, flowi4_to_flowi(fl4));
622         rt = ip_route_output_flow(net, fl4, sk);
623         if (IS_ERR(rt))
624                 goto no_route;
625         if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
626                 goto route_err;
627         return &rt->dst;
628
629 route_err:
630         ip_rt_put(rt);
631 no_route:
632         __IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
633         return NULL;
634 }
635 EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);
636
637 #if IS_ENABLED(CONFIG_IPV6)
638 #define AF_INET_FAMILY(fam) ((fam) == AF_INET)
639 #else
640 #define AF_INET_FAMILY(fam) true
641 #endif
642
643 /* Decide when to expire the request and when to resend SYN-ACK */
644 static inline void syn_ack_recalc(struct request_sock *req, const int thresh,
645                                   const int max_retries,
646                                   const u8 rskq_defer_accept,
647                                   int *expire, int *resend)
648 {
649         if (!rskq_defer_accept) {
650                 *expire = req->num_timeout >= thresh;
651                 *resend = 1;
652                 return;
653         }
654         *expire = req->num_timeout >= thresh &&
655                   (!inet_rsk(req)->acked || req->num_timeout >= max_retries);
656         /*
657          * Do not resend while waiting for data after ACK,
658          * start to resend on end of deferring period to give
659          * last chance for data or ACK to create established socket.
660          */
661         *resend = !inet_rsk(req)->acked ||
662                   req->num_timeout >= rskq_defer_accept - 1;
663 }
664
665 int inet_rtx_syn_ack(const struct sock *parent, struct request_sock *req)
666 {
667         int err = req->rsk_ops->rtx_syn_ack(parent, req);
668
669         if (!err)
670                 req->num_retrans++;
671         return err;
672 }
673 EXPORT_SYMBOL(inet_rtx_syn_ack);
674
675 /* return true if req was found in the ehash table */
676 static bool reqsk_queue_unlink(struct request_sock_queue *queue,
677                                struct request_sock *req)
678 {
679         struct inet_hashinfo *hashinfo = req_to_sk(req)->sk_prot->h.hashinfo;
680         bool found = false;
681
682         if (sk_hashed(req_to_sk(req))) {
683                 spinlock_t *lock = inet_ehash_lockp(hashinfo, req->rsk_hash);
684
685                 spin_lock(lock);
686                 found = __sk_nulls_del_node_init_rcu(req_to_sk(req));
687                 spin_unlock(lock);
688         }
689         if (timer_pending(&req->rsk_timer) && del_timer_sync(&req->rsk_timer))
690                 reqsk_put(req);
691         return found;
692 }
693
694 void inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req)
695 {
696         if (reqsk_queue_unlink(&inet_csk(sk)->icsk_accept_queue, req)) {
697                 reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
698                 reqsk_put(req);
699         }
700 }
701 EXPORT_SYMBOL(inet_csk_reqsk_queue_drop);
702
703 void inet_csk_reqsk_queue_drop_and_put(struct sock *sk, struct request_sock *req)
704 {
705         inet_csk_reqsk_queue_drop(sk, req);
706         reqsk_put(req);
707 }
708 EXPORT_SYMBOL(inet_csk_reqsk_queue_drop_and_put);
709
710 static void reqsk_timer_handler(unsigned long data)
711 {
712         struct request_sock *req = (struct request_sock *)data;
713         struct sock *sk_listener = req->rsk_listener;
714         struct net *net = sock_net(sk_listener);
715         struct inet_connection_sock *icsk = inet_csk(sk_listener);
716         struct request_sock_queue *queue = &icsk->icsk_accept_queue;
717         int qlen, expire = 0, resend = 0;
718         int max_retries, thresh;
719         u8 defer_accept;
720
721         if (sk_state_load(sk_listener) != TCP_LISTEN)
722                 goto drop;
723
724         max_retries = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_synack_retries;
725         thresh = max_retries;
726         /* Normally all the openreqs are young and become mature
727          * (i.e. converted to established socket) for first timeout.
728          * If synack was not acknowledged for 1 second, it means
729          * one of the following things: synack was lost, ack was lost,
730          * rtt is high or nobody planned to ack (i.e. synflood).
731          * When server is a bit loaded, queue is populated with old
732          * open requests, reducing effective size of queue.
733          * When server is well loaded, queue size reduces to zero
734          * after several minutes of work. It is not synflood,
735          * it is normal operation. The solution is pruning
736          * too old entries overriding normal timeout, when
737          * situation becomes dangerous.
738          *
739          * Essentially, we reserve half of room for young
740          * embrions; and abort old ones without pity, if old
741          * ones are about to clog our table.
742          */
743         qlen = reqsk_queue_len(queue);
744         if ((qlen << 1) > max(8U, sk_listener->sk_max_ack_backlog)) {
745                 int young = reqsk_queue_len_young(queue) << 1;
746
747                 while (thresh > 2) {
748                         if (qlen < young)
749                                 break;
750                         thresh--;
751                         young <<= 1;
752                 }
753         }
754         defer_accept = READ_ONCE(queue->rskq_defer_accept);
755         if (defer_accept)
756                 max_retries = defer_accept;
757         syn_ack_recalc(req, thresh, max_retries, defer_accept,
758                        &expire, &resend);
759         req->rsk_ops->syn_ack_timeout(req);
760         if (!expire &&
761             (!resend ||
762              !inet_rtx_syn_ack(sk_listener, req) ||
763              inet_rsk(req)->acked)) {
764                 unsigned long timeo;
765
766                 if (req->num_timeout++ == 0)
767                         atomic_dec(&queue->young);
768                 timeo = min(TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX);
769                 mod_timer(&req->rsk_timer, jiffies + timeo);
770                 return;
771         }
772 drop:
773         inet_csk_reqsk_queue_drop_and_put(sk_listener, req);
774 }
775
776 static void reqsk_queue_hash_req(struct request_sock *req,
777                                  unsigned long timeout)
778 {
779         req->num_retrans = 0;
780         req->num_timeout = 0;
781         req->sk = NULL;
782
783         setup_pinned_timer(&req->rsk_timer, reqsk_timer_handler,
784                             (unsigned long)req);
785         mod_timer(&req->rsk_timer, jiffies + timeout);
786
787         inet_ehash_insert(req_to_sk(req), NULL);
788         /* before letting lookups find us, make sure all req fields
789          * are committed to memory and refcnt initialized.
790          */
791         smp_wmb();
792         refcount_set(&req->rsk_refcnt, 2 + 1);
793 }
794
795 void inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
796                                    unsigned long timeout)
797 {
798         reqsk_queue_hash_req(req, timeout);
799         inet_csk_reqsk_queue_added(sk);
800 }
801 EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
802
803 /**
804  *      inet_csk_clone_lock - clone an inet socket, and lock its clone
805  *      @sk: the socket to clone
806  *      @req: request_sock
807  *      @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
808  *
809  *      Caller must unlock socket even in error path (bh_unlock_sock(newsk))
810  */
811 struct sock *inet_csk_clone_lock(const struct sock *sk,
812                                  const struct request_sock *req,
813                                  const gfp_t priority)
814 {
815         struct sock *newsk = sk_clone_lock(sk, priority);
816
817         if (newsk) {
818                 struct inet_connection_sock *newicsk = inet_csk(newsk);
819
820                 newsk->sk_state = TCP_SYN_RECV;
821                 newicsk->icsk_bind_hash = NULL;
822
823                 inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
824                 inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
825                 inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
826
827                 /* listeners have SOCK_RCU_FREE, not the children */
828                 sock_reset_flag(newsk, SOCK_RCU_FREE);
829
830                 inet_sk(newsk)->mc_list = NULL;
831
832                 newsk->sk_mark = inet_rsk(req)->ir_mark;
833                 atomic64_set(&newsk->sk_cookie,
834                              atomic64_read(&inet_rsk(req)->ir_cookie));
835
836                 newicsk->icsk_retransmits = 0;
837                 newicsk->icsk_backoff     = 0;
838                 newicsk->icsk_probes_out  = 0;
839
840                 /* Deinitialize accept_queue to trap illegal accesses. */
841                 memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
842
843                 security_inet_csk_clone(newsk, req);
844         }
845         return newsk;
846 }
847 EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
848
849 /*
850  * At this point, there should be no process reference to this
851  * socket, and thus no user references at all.  Therefore we
852  * can assume the socket waitqueue is inactive and nobody will
853  * try to jump onto it.
854  */
855 void inet_csk_destroy_sock(struct sock *sk)
856 {
857         WARN_ON(sk->sk_state != TCP_CLOSE);
858         WARN_ON(!sock_flag(sk, SOCK_DEAD));
859
860         /* It cannot be in hash table! */
861         WARN_ON(!sk_unhashed(sk));
862
863         /* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
864         WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
865
866         sk->sk_prot->destroy(sk);
867
868         sk_stream_kill_queues(sk);
869
870         xfrm_sk_free_policy(sk);
871
872         sk_refcnt_debug_release(sk);
873
874         percpu_counter_dec(sk->sk_prot->orphan_count);
875
876         sock_put(sk);
877 }
878 EXPORT_SYMBOL(inet_csk_destroy_sock);
879
880 /* This function allows to force a closure of a socket after the call to
881  * tcp/dccp_create_openreq_child().
882  */
883 void inet_csk_prepare_forced_close(struct sock *sk)
884         __releases(&sk->sk_lock.slock)
885 {
886         /* sk_clone_lock locked the socket and set refcnt to 2 */
887         bh_unlock_sock(sk);
888         sock_put(sk);
889
890         /* The below has to be done to allow calling inet_csk_destroy_sock */
891         sock_set_flag(sk, SOCK_DEAD);
892         percpu_counter_inc(sk->sk_prot->orphan_count);
893         inet_sk(sk)->inet_num = 0;
894 }
895 EXPORT_SYMBOL(inet_csk_prepare_forced_close);
896
897 int inet_csk_listen_start(struct sock *sk, int backlog)
898 {
899         struct inet_connection_sock *icsk = inet_csk(sk);
900         struct inet_sock *inet = inet_sk(sk);
901         int err = -EADDRINUSE;
902
903         reqsk_queue_alloc(&icsk->icsk_accept_queue);
904
905         sk->sk_max_ack_backlog = backlog;
906         sk->sk_ack_backlog = 0;
907         inet_csk_delack_init(sk);
908
909         /* There is race window here: we announce ourselves listening,
910          * but this transition is still not validated by get_port().
911          * It is OK, because this socket enters to hash table only
912          * after validation is complete.
913          */
914         sk_state_store(sk, TCP_LISTEN);
915         if (!sk->sk_prot->get_port(sk, inet->inet_num)) {
916                 inet->inet_sport = htons(inet->inet_num);
917
918                 sk_dst_reset(sk);
919                 err = sk->sk_prot->hash(sk);
920
921                 if (likely(!err))
922                         return 0;
923         }
924
925         sk->sk_state = TCP_CLOSE;
926         return err;
927 }
928 EXPORT_SYMBOL_GPL(inet_csk_listen_start);
929
930 static void inet_child_forget(struct sock *sk, struct request_sock *req,
931                               struct sock *child)
932 {
933         sk->sk_prot->disconnect(child, O_NONBLOCK);
934
935         sock_orphan(child);
936
937         percpu_counter_inc(sk->sk_prot->orphan_count);
938
939         if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
940                 BUG_ON(tcp_sk(child)->fastopen_rsk != req);
941                 BUG_ON(sk != req->rsk_listener);
942
943                 /* Paranoid, to prevent race condition if
944                  * an inbound pkt destined for child is
945                  * blocked by sock lock in tcp_v4_rcv().
946                  * Also to satisfy an assertion in
947                  * tcp_v4_destroy_sock().
948                  */
949                 tcp_sk(child)->fastopen_rsk = NULL;
950         }
951         inet_csk_destroy_sock(child);
952 }
953
954 struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
955                                       struct request_sock *req,
956                                       struct sock *child)
957 {
958         struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
959
960         spin_lock(&queue->rskq_lock);
961         if (unlikely(sk->sk_state != TCP_LISTEN)) {
962                 inet_child_forget(sk, req, child);
963                 child = NULL;
964         } else {
965                 req->sk = child;
966                 req->dl_next = NULL;
967                 if (queue->rskq_accept_head == NULL)
968                         WRITE_ONCE(queue->rskq_accept_head, req);
969                 else
970                         queue->rskq_accept_tail->dl_next = req;
971                 queue->rskq_accept_tail = req;
972                 sk_acceptq_added(sk);
973         }
974         spin_unlock(&queue->rskq_lock);
975         return child;
976 }
977 EXPORT_SYMBOL(inet_csk_reqsk_queue_add);
978
979 struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child,
980                                          struct request_sock *req, bool own_req)
981 {
982         if (own_req) {
983                 inet_csk_reqsk_queue_drop(sk, req);
984                 reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
985                 if (inet_csk_reqsk_queue_add(sk, req, child))
986                         return child;
987         }
988         /* Too bad, another child took ownership of the request, undo. */
989         bh_unlock_sock(child);
990         sock_put(child);
991         return NULL;
992 }
993 EXPORT_SYMBOL(inet_csk_complete_hashdance);
994
995 /*
996  *      This routine closes sockets which have been at least partially
997  *      opened, but not yet accepted.
998  */
999 void inet_csk_listen_stop(struct sock *sk)
1000 {
1001         struct inet_connection_sock *icsk = inet_csk(sk);
1002         struct request_sock_queue *queue = &icsk->icsk_accept_queue;
1003         struct request_sock *next, *req;
1004
1005         /* Following specs, it would be better either to send FIN
1006          * (and enter FIN-WAIT-1, it is normal close)
1007          * or to send active reset (abort).
1008          * Certainly, it is pretty dangerous while synflood, but it is
1009          * bad justification for our negligence 8)
1010          * To be honest, we are not able to make either
1011          * of the variants now.                 --ANK
1012          */
1013         while ((req = reqsk_queue_remove(queue, sk)) != NULL) {
1014                 struct sock *child = req->sk;
1015
1016                 local_bh_disable();
1017                 bh_lock_sock(child);
1018                 WARN_ON(sock_owned_by_user(child));
1019                 sock_hold(child);
1020
1021                 inet_child_forget(sk, req, child);
1022                 reqsk_put(req);
1023                 bh_unlock_sock(child);
1024                 local_bh_enable();
1025                 sock_put(child);
1026
1027                 cond_resched();
1028         }
1029         if (queue->fastopenq.rskq_rst_head) {
1030                 /* Free all the reqs queued in rskq_rst_head. */
1031                 spin_lock_bh(&queue->fastopenq.lock);
1032                 req = queue->fastopenq.rskq_rst_head;
1033                 queue->fastopenq.rskq_rst_head = NULL;
1034                 spin_unlock_bh(&queue->fastopenq.lock);
1035                 while (req != NULL) {
1036                         next = req->dl_next;
1037                         reqsk_put(req);
1038                         req = next;
1039                 }
1040         }
1041         WARN_ON_ONCE(sk->sk_ack_backlog);
1042 }
1043 EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
1044
1045 void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
1046 {
1047         struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
1048         const struct inet_sock *inet = inet_sk(sk);
1049
1050         sin->sin_family         = AF_INET;
1051         sin->sin_addr.s_addr    = inet->inet_daddr;
1052         sin->sin_port           = inet->inet_dport;
1053 }
1054 EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
1055
1056 #ifdef CONFIG_COMPAT
1057 int inet_csk_compat_getsockopt(struct sock *sk, int level, int optname,
1058                                char __user *optval, int __user *optlen)
1059 {
1060         const struct inet_connection_sock *icsk = inet_csk(sk);
1061
1062         if (icsk->icsk_af_ops->compat_getsockopt)
1063                 return icsk->icsk_af_ops->compat_getsockopt(sk, level, optname,
1064                                                             optval, optlen);
1065         return icsk->icsk_af_ops->getsockopt(sk, level, optname,
1066                                              optval, optlen);
1067 }
1068 EXPORT_SYMBOL_GPL(inet_csk_compat_getsockopt);
1069
1070 int inet_csk_compat_setsockopt(struct sock *sk, int level, int optname,
1071                                char __user *optval, unsigned int optlen)
1072 {
1073         const struct inet_connection_sock *icsk = inet_csk(sk);
1074
1075         if (icsk->icsk_af_ops->compat_setsockopt)
1076                 return icsk->icsk_af_ops->compat_setsockopt(sk, level, optname,
1077                                                             optval, optlen);
1078         return icsk->icsk_af_ops->setsockopt(sk, level, optname,
1079                                              optval, optlen);
1080 }
1081 EXPORT_SYMBOL_GPL(inet_csk_compat_setsockopt);
1082 #endif
1083
1084 static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
1085 {
1086         const struct inet_sock *inet = inet_sk(sk);
1087         const struct ip_options_rcu *inet_opt;
1088         __be32 daddr = inet->inet_daddr;
1089         struct flowi4 *fl4;
1090         struct rtable *rt;
1091
1092         rcu_read_lock();
1093         inet_opt = rcu_dereference(inet->inet_opt);
1094         if (inet_opt && inet_opt->opt.srr)
1095                 daddr = inet_opt->opt.faddr;
1096         fl4 = &fl->u.ip4;
1097         rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
1098                                    inet->inet_saddr, inet->inet_dport,
1099                                    inet->inet_sport, sk->sk_protocol,
1100                                    RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
1101         if (IS_ERR(rt))
1102                 rt = NULL;
1103         if (rt)
1104                 sk_setup_caps(sk, &rt->dst);
1105         rcu_read_unlock();
1106
1107         return &rt->dst;
1108 }
1109
1110 struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
1111 {
1112         struct dst_entry *dst = __sk_dst_check(sk, 0);
1113         struct inet_sock *inet = inet_sk(sk);
1114
1115         if (!dst) {
1116                 dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
1117                 if (!dst)
1118                         goto out;
1119         }
1120         dst->ops->update_pmtu(dst, sk, NULL, mtu, true);
1121
1122         dst = __sk_dst_check(sk, 0);
1123         if (!dst)
1124                 dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
1125 out:
1126         return dst;
1127 }
1128 EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);