GNU Linux-libre 5.4.207-gnu1
[releases.git] / net / ipv6 / udp.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *      UDP over IPv6
4  *      Linux INET6 implementation
5  *
6  *      Authors:
7  *      Pedro Roque             <roque@di.fc.ul.pt>
8  *
9  *      Based on linux/ipv4/udp.c
10  *
11  *      Fixes:
12  *      Hideaki YOSHIFUJI       :       sin6_scope_id support
13  *      YOSHIFUJI Hideaki @USAGI and:   Support IPV6_V6ONLY socket option, which
14  *      Alexey Kuznetsov                allow both IPv4 and IPv6 sockets to bind
15  *                                      a single port at the same time.
16  *      Kazunori MIYAZAWA @USAGI:       change process style to use ip6_append_data
17  *      YOSHIFUJI Hideaki @USAGI:       convert /proc/net/udp6 to seq_file.
18  */
19
20 #include <linux/errno.h>
21 #include <linux/types.h>
22 #include <linux/socket.h>
23 #include <linux/sockios.h>
24 #include <linux/net.h>
25 #include <linux/in6.h>
26 #include <linux/netdevice.h>
27 #include <linux/if_arp.h>
28 #include <linux/ipv6.h>
29 #include <linux/icmpv6.h>
30 #include <linux/init.h>
31 #include <linux/module.h>
32 #include <linux/skbuff.h>
33 #include <linux/slab.h>
34 #include <linux/uaccess.h>
35 #include <linux/indirect_call_wrapper.h>
36
37 #include <net/addrconf.h>
38 #include <net/ndisc.h>
39 #include <net/protocol.h>
40 #include <net/transp_v6.h>
41 #include <net/ip6_route.h>
42 #include <net/raw.h>
43 #include <net/tcp_states.h>
44 #include <net/ip6_checksum.h>
45 #include <net/ip6_tunnel.h>
46 #include <net/xfrm.h>
47 #include <net/inet_hashtables.h>
48 #include <net/inet6_hashtables.h>
49 #include <net/busy_poll.h>
50 #include <net/sock_reuseport.h>
51
52 #include <linux/proc_fs.h>
53 #include <linux/seq_file.h>
54 #include <trace/events/skb.h>
55 #include "udp_impl.h"
56
57 static u32 udp6_ehashfn(const struct net *net,
58                         const struct in6_addr *laddr,
59                         const u16 lport,
60                         const struct in6_addr *faddr,
61                         const __be16 fport)
62 {
63         static u32 udp6_ehash_secret __read_mostly;
64         static u32 udp_ipv6_hash_secret __read_mostly;
65
66         u32 lhash, fhash;
67
68         net_get_random_once(&udp6_ehash_secret,
69                             sizeof(udp6_ehash_secret));
70         net_get_random_once(&udp_ipv6_hash_secret,
71                             sizeof(udp_ipv6_hash_secret));
72
73         lhash = (__force u32)laddr->s6_addr32[3];
74         fhash = __ipv6_addr_jhash(faddr, udp_ipv6_hash_secret);
75
76         return __inet6_ehashfn(lhash, lport, fhash, fport,
77                                udp_ipv6_hash_secret + net_hash_mix(net));
78 }
79
80 int udp_v6_get_port(struct sock *sk, unsigned short snum)
81 {
82         unsigned int hash2_nulladdr =
83                 ipv6_portaddr_hash(sock_net(sk), &in6addr_any, snum);
84         unsigned int hash2_partial =
85                 ipv6_portaddr_hash(sock_net(sk), &sk->sk_v6_rcv_saddr, 0);
86
87         /* precompute partial secondary hash */
88         udp_sk(sk)->udp_portaddr_hash = hash2_partial;
89         return udp_lib_get_port(sk, snum, hash2_nulladdr);
90 }
91
92 void udp_v6_rehash(struct sock *sk)
93 {
94         u16 new_hash = ipv6_portaddr_hash(sock_net(sk),
95                                           &sk->sk_v6_rcv_saddr,
96                                           inet_sk(sk)->inet_num);
97
98         udp_lib_rehash(sk, new_hash);
99 }
100
101 static int compute_score(struct sock *sk, struct net *net,
102                          const struct in6_addr *saddr, __be16 sport,
103                          const struct in6_addr *daddr, unsigned short hnum,
104                          int dif, int sdif)
105 {
106         int score;
107         struct inet_sock *inet;
108         bool dev_match;
109
110         if (!net_eq(sock_net(sk), net) ||
111             udp_sk(sk)->udp_port_hash != hnum ||
112             sk->sk_family != PF_INET6)
113                 return -1;
114
115         if (!ipv6_addr_equal(&sk->sk_v6_rcv_saddr, daddr))
116                 return -1;
117
118         score = 0;
119         inet = inet_sk(sk);
120
121         if (inet->inet_dport) {
122                 if (inet->inet_dport != sport)
123                         return -1;
124                 score++;
125         }
126
127         if (!ipv6_addr_any(&sk->sk_v6_daddr)) {
128                 if (!ipv6_addr_equal(&sk->sk_v6_daddr, saddr))
129                         return -1;
130                 score++;
131         }
132
133         dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif);
134         if (!dev_match)
135                 return -1;
136         if (sk->sk_bound_dev_if)
137                 score++;
138
139         if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
140                 score++;
141
142         return score;
143 }
144
145 /* called with rcu_read_lock() */
146 static struct sock *udp6_lib_lookup2(struct net *net,
147                 const struct in6_addr *saddr, __be16 sport,
148                 const struct in6_addr *daddr, unsigned int hnum,
149                 int dif, int sdif, struct udp_hslot *hslot2,
150                 struct sk_buff *skb)
151 {
152         struct sock *sk, *result, *reuseport_result;
153         int score, badness;
154         u32 hash = 0;
155
156         result = NULL;
157         badness = -1;
158         udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
159                 score = compute_score(sk, net, saddr, sport,
160                                       daddr, hnum, dif, sdif);
161                 if (score > badness) {
162                         reuseport_result = NULL;
163
164                         if (sk->sk_reuseport &&
165                             sk->sk_state != TCP_ESTABLISHED) {
166                                 hash = udp6_ehashfn(net, daddr, hnum,
167                                                     saddr, sport);
168
169                                 reuseport_result = reuseport_select_sock(sk, hash, skb,
170                                                                          sizeof(struct udphdr));
171                                 if (reuseport_result && !reuseport_has_conns(sk, false))
172                                         return reuseport_result;
173                         }
174
175                         result = reuseport_result ? : sk;
176                         badness = score;
177                 }
178         }
179         return result;
180 }
181
182 /* rcu_read_lock() must be held */
183 struct sock *__udp6_lib_lookup(struct net *net,
184                                const struct in6_addr *saddr, __be16 sport,
185                                const struct in6_addr *daddr, __be16 dport,
186                                int dif, int sdif, struct udp_table *udptable,
187                                struct sk_buff *skb)
188 {
189         unsigned short hnum = ntohs(dport);
190         unsigned int hash2, slot2;
191         struct udp_hslot *hslot2;
192         struct sock *result;
193
194         hash2 = ipv6_portaddr_hash(net, daddr, hnum);
195         slot2 = hash2 & udptable->mask;
196         hslot2 = &udptable->hash2[slot2];
197
198         result = udp6_lib_lookup2(net, saddr, sport,
199                                   daddr, hnum, dif, sdif,
200                                   hslot2, skb);
201         if (!result) {
202                 hash2 = ipv6_portaddr_hash(net, &in6addr_any, hnum);
203                 slot2 = hash2 & udptable->mask;
204
205                 hslot2 = &udptable->hash2[slot2];
206
207                 result = udp6_lib_lookup2(net, saddr, sport,
208                                           &in6addr_any, hnum, dif, sdif,
209                                           hslot2, skb);
210         }
211         if (IS_ERR(result))
212                 return NULL;
213         return result;
214 }
215 EXPORT_SYMBOL_GPL(__udp6_lib_lookup);
216
217 static struct sock *__udp6_lib_lookup_skb(struct sk_buff *skb,
218                                           __be16 sport, __be16 dport,
219                                           struct udp_table *udptable)
220 {
221         const struct ipv6hdr *iph = ipv6_hdr(skb);
222
223         return __udp6_lib_lookup(dev_net(skb->dev), &iph->saddr, sport,
224                                  &iph->daddr, dport, inet6_iif(skb),
225                                  inet6_sdif(skb), udptable, skb);
226 }
227
228 struct sock *udp6_lib_lookup_skb(struct sk_buff *skb,
229                                  __be16 sport, __be16 dport)
230 {
231         const struct ipv6hdr *iph = ipv6_hdr(skb);
232
233         return __udp6_lib_lookup(dev_net(skb->dev), &iph->saddr, sport,
234                                  &iph->daddr, dport, inet6_iif(skb),
235                                  inet6_sdif(skb), &udp_table, NULL);
236 }
237 EXPORT_SYMBOL_GPL(udp6_lib_lookup_skb);
238
239 /* Must be called under rcu_read_lock().
240  * Does increment socket refcount.
241  */
242 #if IS_ENABLED(CONFIG_NF_TPROXY_IPV6) || IS_ENABLED(CONFIG_NF_SOCKET_IPV6)
243 struct sock *udp6_lib_lookup(struct net *net, const struct in6_addr *saddr, __be16 sport,
244                              const struct in6_addr *daddr, __be16 dport, int dif)
245 {
246         struct sock *sk;
247
248         sk =  __udp6_lib_lookup(net, saddr, sport, daddr, dport,
249                                 dif, 0, &udp_table, NULL);
250         if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
251                 sk = NULL;
252         return sk;
253 }
254 EXPORT_SYMBOL_GPL(udp6_lib_lookup);
255 #endif
256
257 /* do not use the scratch area len for jumbogram: their length execeeds the
258  * scratch area space; note that the IP6CB flags is still in the first
259  * cacheline, so checking for jumbograms is cheap
260  */
261 static int udp6_skb_len(struct sk_buff *skb)
262 {
263         return unlikely(inet6_is_jumbogram(skb)) ? skb->len : udp_skb_len(skb);
264 }
265
266 /*
267  *      This should be easy, if there is something there we
268  *      return it, otherwise we block.
269  */
270
271 int udpv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
272                   int noblock, int flags, int *addr_len)
273 {
274         struct ipv6_pinfo *np = inet6_sk(sk);
275         struct inet_sock *inet = inet_sk(sk);
276         struct sk_buff *skb;
277         unsigned int ulen, copied;
278         int off, err, peeking = flags & MSG_PEEK;
279         int is_udplite = IS_UDPLITE(sk);
280         struct udp_mib __percpu *mib;
281         bool checksum_valid = false;
282         int is_udp4;
283
284         if (flags & MSG_ERRQUEUE)
285                 return ipv6_recv_error(sk, msg, len, addr_len);
286
287         if (np->rxpmtu && np->rxopt.bits.rxpmtu)
288                 return ipv6_recv_rxpmtu(sk, msg, len, addr_len);
289
290 try_again:
291         off = sk_peek_offset(sk, flags);
292         skb = __skb_recv_udp(sk, flags, noblock, &off, &err);
293         if (!skb)
294                 return err;
295
296         ulen = udp6_skb_len(skb);
297         copied = len;
298         if (copied > ulen - off)
299                 copied = ulen - off;
300         else if (copied < ulen)
301                 msg->msg_flags |= MSG_TRUNC;
302
303         is_udp4 = (skb->protocol == htons(ETH_P_IP));
304         mib = __UDPX_MIB(sk, is_udp4);
305
306         /*
307          * If checksum is needed at all, try to do it while copying the
308          * data.  If the data is truncated, or if we only want a partial
309          * coverage checksum (UDP-Lite), do it before the copy.
310          */
311
312         if (copied < ulen || peeking ||
313             (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
314                 checksum_valid = udp_skb_csum_unnecessary(skb) ||
315                                 !__udp_lib_checksum_complete(skb);
316                 if (!checksum_valid)
317                         goto csum_copy_err;
318         }
319
320         if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
321                 if (udp_skb_is_linear(skb))
322                         err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
323                 else
324                         err = skb_copy_datagram_msg(skb, off, msg, copied);
325         } else {
326                 err = skb_copy_and_csum_datagram_msg(skb, off, msg);
327                 if (err == -EINVAL)
328                         goto csum_copy_err;
329         }
330         if (unlikely(err)) {
331                 if (!peeking) {
332                         atomic_inc(&sk->sk_drops);
333                         SNMP_INC_STATS(mib, UDP_MIB_INERRORS);
334                 }
335                 kfree_skb(skb);
336                 return err;
337         }
338         if (!peeking)
339                 SNMP_INC_STATS(mib, UDP_MIB_INDATAGRAMS);
340
341         sock_recv_ts_and_drops(msg, sk, skb);
342
343         /* Copy the address. */
344         if (msg->msg_name) {
345                 DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
346                 sin6->sin6_family = AF_INET6;
347                 sin6->sin6_port = udp_hdr(skb)->source;
348                 sin6->sin6_flowinfo = 0;
349
350                 if (is_udp4) {
351                         ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
352                                                &sin6->sin6_addr);
353                         sin6->sin6_scope_id = 0;
354                 } else {
355                         sin6->sin6_addr = ipv6_hdr(skb)->saddr;
356                         sin6->sin6_scope_id =
357                                 ipv6_iface_scope_id(&sin6->sin6_addr,
358                                                     inet6_iif(skb));
359                 }
360                 *addr_len = sizeof(*sin6);
361
362                 if (cgroup_bpf_enabled)
363                         BPF_CGROUP_RUN_PROG_UDP6_RECVMSG_LOCK(sk,
364                                                 (struct sockaddr *)sin6);
365         }
366
367         if (udp_sk(sk)->gro_enabled)
368                 udp_cmsg_recv(msg, sk, skb);
369
370         if (np->rxopt.all)
371                 ip6_datagram_recv_common_ctl(sk, msg, skb);
372
373         if (is_udp4) {
374                 if (inet->cmsg_flags)
375                         ip_cmsg_recv_offset(msg, sk, skb,
376                                             sizeof(struct udphdr), off);
377         } else {
378                 if (np->rxopt.all)
379                         ip6_datagram_recv_specific_ctl(sk, msg, skb);
380         }
381
382         err = copied;
383         if (flags & MSG_TRUNC)
384                 err = ulen;
385
386         skb_consume_udp(sk, skb, peeking ? -err : err);
387         return err;
388
389 csum_copy_err:
390         if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
391                                  udp_skb_destructor)) {
392                 SNMP_INC_STATS(mib, UDP_MIB_CSUMERRORS);
393                 SNMP_INC_STATS(mib, UDP_MIB_INERRORS);
394         }
395         kfree_skb(skb);
396
397         /* starting over for a new packet, but check if we need to yield */
398         cond_resched();
399         msg->msg_flags &= ~MSG_TRUNC;
400         goto try_again;
401 }
402
403 DEFINE_STATIC_KEY_FALSE(udpv6_encap_needed_key);
404 void udpv6_encap_enable(void)
405 {
406         static_branch_inc(&udpv6_encap_needed_key);
407 }
408 EXPORT_SYMBOL(udpv6_encap_enable);
409
410 /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
411  * through error handlers in encapsulations looking for a match.
412  */
413 static int __udp6_lib_err_encap_no_sk(struct sk_buff *skb,
414                                       struct inet6_skb_parm *opt,
415                                       u8 type, u8 code, int offset, __be32 info)
416 {
417         int i;
418
419         for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
420                 int (*handler)(struct sk_buff *skb, struct inet6_skb_parm *opt,
421                                u8 type, u8 code, int offset, __be32 info);
422                 const struct ip6_tnl_encap_ops *encap;
423
424                 encap = rcu_dereference(ip6tun_encaps[i]);
425                 if (!encap)
426                         continue;
427                 handler = encap->err_handler;
428                 if (handler && !handler(skb, opt, type, code, offset, info))
429                         return 0;
430         }
431
432         return -ENOENT;
433 }
434
435 /* Try to match ICMP errors to UDP tunnels by looking up a socket without
436  * reversing source and destination port: this will match tunnels that force the
437  * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
438  * lwtunnels might actually break this assumption by being configured with
439  * different destination ports on endpoints, in this case we won't be able to
440  * trace ICMP messages back to them.
441  *
442  * If this doesn't match any socket, probe tunnels with arbitrary destination
443  * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
444  * we've sent packets to won't necessarily match the local destination port.
445  *
446  * Then ask the tunnel implementation to match the error against a valid
447  * association.
448  *
449  * Return an error if we can't find a match, the socket if we need further
450  * processing, zero otherwise.
451  */
452 static struct sock *__udp6_lib_err_encap(struct net *net,
453                                          const struct ipv6hdr *hdr, int offset,
454                                          struct udphdr *uh,
455                                          struct udp_table *udptable,
456                                          struct sk_buff *skb,
457                                          struct inet6_skb_parm *opt,
458                                          u8 type, u8 code, __be32 info)
459 {
460         int network_offset, transport_offset;
461         struct sock *sk;
462
463         network_offset = skb_network_offset(skb);
464         transport_offset = skb_transport_offset(skb);
465
466         /* Network header needs to point to the outer IPv6 header inside ICMP */
467         skb_reset_network_header(skb);
468
469         /* Transport header needs to point to the UDP header */
470         skb_set_transport_header(skb, offset);
471
472         sk = __udp6_lib_lookup(net, &hdr->daddr, uh->source,
473                                &hdr->saddr, uh->dest,
474                                inet6_iif(skb), 0, udptable, skb);
475         if (sk) {
476                 int (*lookup)(struct sock *sk, struct sk_buff *skb);
477                 struct udp_sock *up = udp_sk(sk);
478
479                 lookup = READ_ONCE(up->encap_err_lookup);
480                 if (!lookup || lookup(sk, skb))
481                         sk = NULL;
482         }
483
484         if (!sk) {
485                 sk = ERR_PTR(__udp6_lib_err_encap_no_sk(skb, opt, type, code,
486                                                         offset, info));
487         }
488
489         skb_set_transport_header(skb, transport_offset);
490         skb_set_network_header(skb, network_offset);
491
492         return sk;
493 }
494
495 int __udp6_lib_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
496                    u8 type, u8 code, int offset, __be32 info,
497                    struct udp_table *udptable)
498 {
499         struct ipv6_pinfo *np;
500         const struct ipv6hdr *hdr = (const struct ipv6hdr *)skb->data;
501         const struct in6_addr *saddr = &hdr->saddr;
502         const struct in6_addr *daddr = &hdr->daddr;
503         struct udphdr *uh = (struct udphdr *)(skb->data+offset);
504         bool tunnel = false;
505         struct sock *sk;
506         int harderr;
507         int err;
508         struct net *net = dev_net(skb->dev);
509
510         sk = __udp6_lib_lookup(net, daddr, uh->dest, saddr, uh->source,
511                                inet6_iif(skb), inet6_sdif(skb), udptable, NULL);
512         if (!sk) {
513                 /* No socket for error: try tunnels before discarding */
514                 sk = ERR_PTR(-ENOENT);
515                 if (static_branch_unlikely(&udpv6_encap_needed_key)) {
516                         sk = __udp6_lib_err_encap(net, hdr, offset, uh,
517                                                   udptable, skb,
518                                                   opt, type, code, info);
519                         if (!sk)
520                                 return 0;
521                 }
522
523                 if (IS_ERR(sk)) {
524                         __ICMP6_INC_STATS(net, __in6_dev_get(skb->dev),
525                                           ICMP6_MIB_INERRORS);
526                         return PTR_ERR(sk);
527                 }
528
529                 tunnel = true;
530         }
531
532         harderr = icmpv6_err_convert(type, code, &err);
533         np = inet6_sk(sk);
534
535         if (type == ICMPV6_PKT_TOOBIG) {
536                 if (!ip6_sk_accept_pmtu(sk))
537                         goto out;
538                 ip6_sk_update_pmtu(skb, sk, info);
539                 if (np->pmtudisc != IPV6_PMTUDISC_DONT)
540                         harderr = 1;
541         }
542         if (type == NDISC_REDIRECT) {
543                 if (tunnel) {
544                         ip6_redirect(skb, sock_net(sk), inet6_iif(skb),
545                                      sk->sk_mark, sk->sk_uid);
546                 } else {
547                         ip6_sk_redirect(skb, sk);
548                 }
549                 goto out;
550         }
551
552         /* Tunnels don't have an application socket: don't pass errors back */
553         if (tunnel)
554                 goto out;
555
556         if (!np->recverr) {
557                 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
558                         goto out;
559         } else {
560                 ipv6_icmp_error(sk, skb, err, uh->dest, ntohl(info), (u8 *)(uh+1));
561         }
562
563         sk->sk_err = err;
564         sk->sk_error_report(sk);
565 out:
566         return 0;
567 }
568
569 static int __udpv6_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
570 {
571         int rc;
572
573         if (!ipv6_addr_any(&sk->sk_v6_daddr)) {
574                 sock_rps_save_rxhash(sk, skb);
575                 sk_mark_napi_id(sk, skb);
576                 sk_incoming_cpu_update(sk);
577         } else {
578                 sk_mark_napi_id_once(sk, skb);
579         }
580
581         rc = __udp_enqueue_schedule_skb(sk, skb);
582         if (rc < 0) {
583                 int is_udplite = IS_UDPLITE(sk);
584
585                 /* Note that an ENOMEM error is charged twice */
586                 if (rc == -ENOMEM)
587                         UDP6_INC_STATS(sock_net(sk),
588                                          UDP_MIB_RCVBUFERRORS, is_udplite);
589                 UDP6_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
590                 kfree_skb(skb);
591                 return -1;
592         }
593
594         return 0;
595 }
596
597 static __inline__ int udpv6_err(struct sk_buff *skb,
598                                 struct inet6_skb_parm *opt, u8 type,
599                                 u8 code, int offset, __be32 info)
600 {
601         return __udp6_lib_err(skb, opt, type, code, offset, info, &udp_table);
602 }
603
604 static int udpv6_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
605 {
606         struct udp_sock *up = udp_sk(sk);
607         int is_udplite = IS_UDPLITE(sk);
608
609         if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb))
610                 goto drop;
611
612         if (static_branch_unlikely(&udpv6_encap_needed_key) && up->encap_type) {
613                 int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
614
615                 /*
616                  * This is an encapsulation socket so pass the skb to
617                  * the socket's udp_encap_rcv() hook. Otherwise, just
618                  * fall through and pass this up the UDP socket.
619                  * up->encap_rcv() returns the following value:
620                  * =0 if skb was successfully passed to the encap
621                  *    handler or was discarded by it.
622                  * >0 if skb should be passed on to UDP.
623                  * <0 if skb should be resubmitted as proto -N
624                  */
625
626                 /* if we're overly short, let UDP handle it */
627                 encap_rcv = READ_ONCE(up->encap_rcv);
628                 if (encap_rcv) {
629                         int ret;
630
631                         /* Verify checksum before giving to encap */
632                         if (udp_lib_checksum_complete(skb))
633                                 goto csum_error;
634
635                         ret = encap_rcv(sk, skb);
636                         if (ret <= 0) {
637                                 __UDP_INC_STATS(sock_net(sk),
638                                                 UDP_MIB_INDATAGRAMS,
639                                                 is_udplite);
640                                 return -ret;
641                         }
642                 }
643
644                 /* FALLTHROUGH -- it's a UDP Packet */
645         }
646
647         /*
648          * UDP-Lite specific tests, ignored on UDP sockets (see net/ipv4/udp.c).
649          */
650         if ((up->pcflag & UDPLITE_RECV_CC)  &&  UDP_SKB_CB(skb)->partial_cov) {
651
652                 if (up->pcrlen == 0) {          /* full coverage was set  */
653                         net_dbg_ratelimited("UDPLITE6: partial coverage %d while full coverage %d requested\n",
654                                             UDP_SKB_CB(skb)->cscov, skb->len);
655                         goto drop;
656                 }
657                 if (UDP_SKB_CB(skb)->cscov  <  up->pcrlen) {
658                         net_dbg_ratelimited("UDPLITE6: coverage %d too small, need min %d\n",
659                                             UDP_SKB_CB(skb)->cscov, up->pcrlen);
660                         goto drop;
661                 }
662         }
663
664         prefetch(&sk->sk_rmem_alloc);
665         if (rcu_access_pointer(sk->sk_filter) &&
666             udp_lib_checksum_complete(skb))
667                 goto csum_error;
668
669         if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr)))
670                 goto drop;
671
672         udp_csum_pull_header(skb);
673
674         skb_dst_drop(skb);
675
676         return __udpv6_queue_rcv_skb(sk, skb);
677
678 csum_error:
679         __UDP6_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
680 drop:
681         __UDP6_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
682         atomic_inc(&sk->sk_drops);
683         kfree_skb(skb);
684         return -1;
685 }
686
687 static int udpv6_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
688 {
689         struct sk_buff *next, *segs;
690         int ret;
691
692         if (likely(!udp_unexpected_gso(sk, skb)))
693                 return udpv6_queue_rcv_one_skb(sk, skb);
694
695         __skb_push(skb, -skb_mac_offset(skb));
696         segs = udp_rcv_segment(sk, skb, false);
697         for (skb = segs; skb; skb = next) {
698                 next = skb->next;
699                 __skb_pull(skb, skb_transport_offset(skb));
700
701                 ret = udpv6_queue_rcv_one_skb(sk, skb);
702                 if (ret > 0)
703                         ip6_protocol_deliver_rcu(dev_net(skb->dev), skb, ret,
704                                                  true);
705         }
706         return 0;
707 }
708
709 static bool __udp_v6_is_mcast_sock(struct net *net, struct sock *sk,
710                                    __be16 loc_port, const struct in6_addr *loc_addr,
711                                    __be16 rmt_port, const struct in6_addr *rmt_addr,
712                                    int dif, int sdif, unsigned short hnum)
713 {
714         struct inet_sock *inet = inet_sk(sk);
715
716         if (!net_eq(sock_net(sk), net))
717                 return false;
718
719         if (udp_sk(sk)->udp_port_hash != hnum ||
720             sk->sk_family != PF_INET6 ||
721             (inet->inet_dport && inet->inet_dport != rmt_port) ||
722             (!ipv6_addr_any(&sk->sk_v6_daddr) &&
723                     !ipv6_addr_equal(&sk->sk_v6_daddr, rmt_addr)) ||
724             !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif) ||
725             (!ipv6_addr_any(&sk->sk_v6_rcv_saddr) &&
726                     !ipv6_addr_equal(&sk->sk_v6_rcv_saddr, loc_addr)))
727                 return false;
728         if (!inet6_mc_check(sk, loc_addr, rmt_addr))
729                 return false;
730         return true;
731 }
732
733 static void udp6_csum_zero_error(struct sk_buff *skb)
734 {
735         /* RFC 2460 section 8.1 says that we SHOULD log
736          * this error. Well, it is reasonable.
737          */
738         net_dbg_ratelimited("IPv6: udp checksum is 0 for [%pI6c]:%u->[%pI6c]:%u\n",
739                             &ipv6_hdr(skb)->saddr, ntohs(udp_hdr(skb)->source),
740                             &ipv6_hdr(skb)->daddr, ntohs(udp_hdr(skb)->dest));
741 }
742
743 /*
744  * Note: called only from the BH handler context,
745  * so we don't need to lock the hashes.
746  */
747 static int __udp6_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
748                 const struct in6_addr *saddr, const struct in6_addr *daddr,
749                 struct udp_table *udptable, int proto)
750 {
751         struct sock *sk, *first = NULL;
752         const struct udphdr *uh = udp_hdr(skb);
753         unsigned short hnum = ntohs(uh->dest);
754         struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
755         unsigned int offset = offsetof(typeof(*sk), sk_node);
756         unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
757         int dif = inet6_iif(skb);
758         int sdif = inet6_sdif(skb);
759         struct hlist_node *node;
760         struct sk_buff *nskb;
761
762         if (use_hash2) {
763                 hash2_any = ipv6_portaddr_hash(net, &in6addr_any, hnum) &
764                             udptable->mask;
765                 hash2 = ipv6_portaddr_hash(net, daddr, hnum) & udptable->mask;
766 start_lookup:
767                 hslot = &udptable->hash2[hash2];
768                 offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
769         }
770
771         sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
772                 if (!__udp_v6_is_mcast_sock(net, sk, uh->dest, daddr,
773                                             uh->source, saddr, dif, sdif,
774                                             hnum))
775                         continue;
776                 /* If zero checksum and no_check is not on for
777                  * the socket then skip it.
778                  */
779                 if (!uh->check && !udp_sk(sk)->no_check6_rx)
780                         continue;
781                 if (!first) {
782                         first = sk;
783                         continue;
784                 }
785                 nskb = skb_clone(skb, GFP_ATOMIC);
786                 if (unlikely(!nskb)) {
787                         atomic_inc(&sk->sk_drops);
788                         __UDP6_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
789                                          IS_UDPLITE(sk));
790                         __UDP6_INC_STATS(net, UDP_MIB_INERRORS,
791                                          IS_UDPLITE(sk));
792                         continue;
793                 }
794
795                 if (udpv6_queue_rcv_skb(sk, nskb) > 0)
796                         consume_skb(nskb);
797         }
798
799         /* Also lookup *:port if we are using hash2 and haven't done so yet. */
800         if (use_hash2 && hash2 != hash2_any) {
801                 hash2 = hash2_any;
802                 goto start_lookup;
803         }
804
805         if (first) {
806                 if (udpv6_queue_rcv_skb(first, skb) > 0)
807                         consume_skb(skb);
808         } else {
809                 kfree_skb(skb);
810                 __UDP6_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
811                                  proto == IPPROTO_UDPLITE);
812         }
813         return 0;
814 }
815
816 static void udp6_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
817 {
818         if (udp_sk_rx_dst_set(sk, dst)) {
819                 const struct rt6_info *rt = (const struct rt6_info *)dst;
820
821                 inet6_sk(sk)->rx_dst_cookie = rt6_get_cookie(rt);
822         }
823 }
824
825 /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
826  * return code conversion for ip layer consumption
827  */
828 static int udp6_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
829                                 struct udphdr *uh)
830 {
831         int ret;
832
833         if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
834                 skb_checksum_try_convert(skb, IPPROTO_UDP, ip6_compute_pseudo);
835
836         ret = udpv6_queue_rcv_skb(sk, skb);
837
838         /* a return value > 0 means to resubmit the input */
839         if (ret > 0)
840                 return ret;
841         return 0;
842 }
843
844 int __udp6_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
845                    int proto)
846 {
847         const struct in6_addr *saddr, *daddr;
848         struct net *net = dev_net(skb->dev);
849         struct udphdr *uh;
850         struct sock *sk;
851         u32 ulen = 0;
852
853         if (!pskb_may_pull(skb, sizeof(struct udphdr)))
854                 goto discard;
855
856         saddr = &ipv6_hdr(skb)->saddr;
857         daddr = &ipv6_hdr(skb)->daddr;
858         uh = udp_hdr(skb);
859
860         ulen = ntohs(uh->len);
861         if (ulen > skb->len)
862                 goto short_packet;
863
864         if (proto == IPPROTO_UDP) {
865                 /* UDP validates ulen. */
866
867                 /* Check for jumbo payload */
868                 if (ulen == 0)
869                         ulen = skb->len;
870
871                 if (ulen < sizeof(*uh))
872                         goto short_packet;
873
874                 if (ulen < skb->len) {
875                         if (pskb_trim_rcsum(skb, ulen))
876                                 goto short_packet;
877                         saddr = &ipv6_hdr(skb)->saddr;
878                         daddr = &ipv6_hdr(skb)->daddr;
879                         uh = udp_hdr(skb);
880                 }
881         }
882
883         if (udp6_csum_init(skb, uh, proto))
884                 goto csum_error;
885
886         /* Check if the socket is already available, e.g. due to early demux */
887         sk = skb_steal_sock(skb);
888         if (sk) {
889                 struct dst_entry *dst = skb_dst(skb);
890                 int ret;
891
892                 if (unlikely(sk->sk_rx_dst != dst))
893                         udp6_sk_rx_dst_set(sk, dst);
894
895                 if (!uh->check && !udp_sk(sk)->no_check6_rx) {
896                         sock_put(sk);
897                         goto report_csum_error;
898                 }
899
900                 ret = udp6_unicast_rcv_skb(sk, skb, uh);
901                 sock_put(sk);
902                 return ret;
903         }
904
905         /*
906          *      Multicast receive code
907          */
908         if (ipv6_addr_is_multicast(daddr))
909                 return __udp6_lib_mcast_deliver(net, skb,
910                                 saddr, daddr, udptable, proto);
911
912         /* Unicast */
913         sk = __udp6_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
914         if (sk) {
915                 if (!uh->check && !udp_sk(sk)->no_check6_rx)
916                         goto report_csum_error;
917                 return udp6_unicast_rcv_skb(sk, skb, uh);
918         }
919
920         if (!uh->check)
921                 goto report_csum_error;
922
923         if (!xfrm6_policy_check(NULL, XFRM_POLICY_IN, skb))
924                 goto discard;
925
926         if (udp_lib_checksum_complete(skb))
927                 goto csum_error;
928
929         __UDP6_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
930         icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_PORT_UNREACH, 0);
931
932         kfree_skb(skb);
933         return 0;
934
935 short_packet:
936         net_dbg_ratelimited("UDP%sv6: short packet: From [%pI6c]:%u %d/%d to [%pI6c]:%u\n",
937                             proto == IPPROTO_UDPLITE ? "-Lite" : "",
938                             saddr, ntohs(uh->source),
939                             ulen, skb->len,
940                             daddr, ntohs(uh->dest));
941         goto discard;
942
943 report_csum_error:
944         udp6_csum_zero_error(skb);
945 csum_error:
946         __UDP6_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
947 discard:
948         __UDP6_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
949         kfree_skb(skb);
950         return 0;
951 }
952
953
954 static struct sock *__udp6_lib_demux_lookup(struct net *net,
955                         __be16 loc_port, const struct in6_addr *loc_addr,
956                         __be16 rmt_port, const struct in6_addr *rmt_addr,
957                         int dif, int sdif)
958 {
959         unsigned short hnum = ntohs(loc_port);
960         unsigned int hash2 = ipv6_portaddr_hash(net, loc_addr, hnum);
961         unsigned int slot2 = hash2 & udp_table.mask;
962         struct udp_hslot *hslot2 = &udp_table.hash2[slot2];
963         const __portpair ports = INET_COMBINED_PORTS(rmt_port, hnum);
964         struct sock *sk;
965
966         udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
967                 if (sk->sk_state == TCP_ESTABLISHED &&
968                     INET6_MATCH(sk, net, rmt_addr, loc_addr, ports, dif, sdif))
969                         return sk;
970                 /* Only check first socket in chain */
971                 break;
972         }
973         return NULL;
974 }
975
976 INDIRECT_CALLABLE_SCOPE void udp_v6_early_demux(struct sk_buff *skb)
977 {
978         struct net *net = dev_net(skb->dev);
979         const struct udphdr *uh;
980         struct sock *sk;
981         struct dst_entry *dst;
982         int dif = skb->dev->ifindex;
983         int sdif = inet6_sdif(skb);
984
985         if (!pskb_may_pull(skb, skb_transport_offset(skb) +
986             sizeof(struct udphdr)))
987                 return;
988
989         uh = udp_hdr(skb);
990
991         if (skb->pkt_type == PACKET_HOST)
992                 sk = __udp6_lib_demux_lookup(net, uh->dest,
993                                              &ipv6_hdr(skb)->daddr,
994                                              uh->source, &ipv6_hdr(skb)->saddr,
995                                              dif, sdif);
996         else
997                 return;
998
999         if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
1000                 return;
1001
1002         skb->sk = sk;
1003         skb->destructor = sock_efree;
1004         dst = READ_ONCE(sk->sk_rx_dst);
1005
1006         if (dst)
1007                 dst = dst_check(dst, inet6_sk(sk)->rx_dst_cookie);
1008         if (dst) {
1009                 /* set noref for now.
1010                  * any place which wants to hold dst has to call
1011                  * dst_hold_safe()
1012                  */
1013                 skb_dst_set_noref(skb, dst);
1014         }
1015 }
1016
1017 INDIRECT_CALLABLE_SCOPE int udpv6_rcv(struct sk_buff *skb)
1018 {
1019         return __udp6_lib_rcv(skb, &udp_table, IPPROTO_UDP);
1020 }
1021
1022 /*
1023  * Throw away all pending data and cancel the corking. Socket is locked.
1024  */
1025 static void udp_v6_flush_pending_frames(struct sock *sk)
1026 {
1027         struct udp_sock *up = udp_sk(sk);
1028
1029         if (up->pending == AF_INET)
1030                 udp_flush_pending_frames(sk);
1031         else if (up->pending) {
1032                 up->len = 0;
1033                 up->pending = 0;
1034                 ip6_flush_pending_frames(sk);
1035         }
1036 }
1037
1038 static int udpv6_pre_connect(struct sock *sk, struct sockaddr *uaddr,
1039                              int addr_len)
1040 {
1041         if (addr_len < offsetofend(struct sockaddr, sa_family))
1042                 return -EINVAL;
1043         /* The following checks are replicated from __ip6_datagram_connect()
1044          * and intended to prevent BPF program called below from accessing
1045          * bytes that are out of the bound specified by user in addr_len.
1046          */
1047         if (uaddr->sa_family == AF_INET) {
1048                 if (__ipv6_only_sock(sk))
1049                         return -EAFNOSUPPORT;
1050                 return udp_pre_connect(sk, uaddr, addr_len);
1051         }
1052
1053         if (addr_len < SIN6_LEN_RFC2133)
1054                 return -EINVAL;
1055
1056         return BPF_CGROUP_RUN_PROG_INET6_CONNECT_LOCK(sk, uaddr);
1057 }
1058
1059 /**
1060  *      udp6_hwcsum_outgoing  -  handle outgoing HW checksumming
1061  *      @sk:    socket we are sending on
1062  *      @skb:   sk_buff containing the filled-in UDP header
1063  *              (checksum field must be zeroed out)
1064  */
1065 static void udp6_hwcsum_outgoing(struct sock *sk, struct sk_buff *skb,
1066                                  const struct in6_addr *saddr,
1067                                  const struct in6_addr *daddr, int len)
1068 {
1069         unsigned int offset;
1070         struct udphdr *uh = udp_hdr(skb);
1071         struct sk_buff *frags = skb_shinfo(skb)->frag_list;
1072         __wsum csum = 0;
1073
1074         if (!frags) {
1075                 /* Only one fragment on the socket.  */
1076                 skb->csum_start = skb_transport_header(skb) - skb->head;
1077                 skb->csum_offset = offsetof(struct udphdr, check);
1078                 uh->check = ~csum_ipv6_magic(saddr, daddr, len, IPPROTO_UDP, 0);
1079         } else {
1080                 /*
1081                  * HW-checksum won't work as there are two or more
1082                  * fragments on the socket so that all csums of sk_buffs
1083                  * should be together
1084                  */
1085                 offset = skb_transport_offset(skb);
1086                 skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
1087                 csum = skb->csum;
1088
1089                 skb->ip_summed = CHECKSUM_NONE;
1090
1091                 do {
1092                         csum = csum_add(csum, frags->csum);
1093                 } while ((frags = frags->next));
1094
1095                 uh->check = csum_ipv6_magic(saddr, daddr, len, IPPROTO_UDP,
1096                                             csum);
1097                 if (uh->check == 0)
1098                         uh->check = CSUM_MANGLED_0;
1099         }
1100 }
1101
1102 /*
1103  *      Sending
1104  */
1105
1106 static int udp_v6_send_skb(struct sk_buff *skb, struct flowi6 *fl6,
1107                            struct inet_cork *cork)
1108 {
1109         struct sock *sk = skb->sk;
1110         struct udphdr *uh;
1111         int err = 0;
1112         int is_udplite = IS_UDPLITE(sk);
1113         __wsum csum = 0;
1114         int offset = skb_transport_offset(skb);
1115         int len = skb->len - offset;
1116         int datalen = len - sizeof(*uh);
1117
1118         /*
1119          * Create a UDP header
1120          */
1121         uh = udp_hdr(skb);
1122         uh->source = fl6->fl6_sport;
1123         uh->dest = fl6->fl6_dport;
1124         uh->len = htons(len);
1125         uh->check = 0;
1126
1127         if (cork->gso_size) {
1128                 const int hlen = skb_network_header_len(skb) +
1129                                  sizeof(struct udphdr);
1130
1131                 if (hlen + cork->gso_size > cork->fragsize) {
1132                         kfree_skb(skb);
1133                         return -EINVAL;
1134                 }
1135                 if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
1136                         kfree_skb(skb);
1137                         return -EINVAL;
1138                 }
1139                 if (udp_sk(sk)->no_check6_tx) {
1140                         kfree_skb(skb);
1141                         return -EINVAL;
1142                 }
1143                 if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
1144                     dst_xfrm(skb_dst(skb))) {
1145                         kfree_skb(skb);
1146                         return -EIO;
1147                 }
1148
1149                 if (datalen > cork->gso_size) {
1150                         skb_shinfo(skb)->gso_size = cork->gso_size;
1151                         skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
1152                         skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
1153                                                                  cork->gso_size);
1154                 }
1155                 goto csum_partial;
1156         }
1157
1158         if (is_udplite)
1159                 csum = udplite_csum(skb);
1160         else if (udp_sk(sk)->no_check6_tx) {   /* UDP csum disabled */
1161                 skb->ip_summed = CHECKSUM_NONE;
1162                 goto send;
1163         } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
1164 csum_partial:
1165                 udp6_hwcsum_outgoing(sk, skb, &fl6->saddr, &fl6->daddr, len);
1166                 goto send;
1167         } else
1168                 csum = udp_csum(skb);
1169
1170         /* add protocol-dependent pseudo-header */
1171         uh->check = csum_ipv6_magic(&fl6->saddr, &fl6->daddr,
1172                                     len, fl6->flowi6_proto, csum);
1173         if (uh->check == 0)
1174                 uh->check = CSUM_MANGLED_0;
1175
1176 send:
1177         err = ip6_send_skb(skb);
1178         if (err) {
1179                 if (err == -ENOBUFS && !inet6_sk(sk)->recverr) {
1180                         UDP6_INC_STATS(sock_net(sk),
1181                                        UDP_MIB_SNDBUFERRORS, is_udplite);
1182                         err = 0;
1183                 }
1184         } else {
1185                 UDP6_INC_STATS(sock_net(sk),
1186                                UDP_MIB_OUTDATAGRAMS, is_udplite);
1187         }
1188         return err;
1189 }
1190
1191 static int udp_v6_push_pending_frames(struct sock *sk)
1192 {
1193         struct sk_buff *skb;
1194         struct udp_sock  *up = udp_sk(sk);
1195         struct flowi6 fl6;
1196         int err = 0;
1197
1198         if (up->pending == AF_INET)
1199                 return udp_push_pending_frames(sk);
1200
1201         /* ip6_finish_skb will release the cork, so make a copy of
1202          * fl6 here.
1203          */
1204         fl6 = inet_sk(sk)->cork.fl.u.ip6;
1205
1206         skb = ip6_finish_skb(sk);
1207         if (!skb)
1208                 goto out;
1209
1210         err = udp_v6_send_skb(skb, &fl6, &inet_sk(sk)->cork.base);
1211
1212 out:
1213         up->len = 0;
1214         up->pending = 0;
1215         return err;
1216 }
1217
1218 int udpv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1219 {
1220         struct ipv6_txoptions opt_space;
1221         struct udp_sock *up = udp_sk(sk);
1222         struct inet_sock *inet = inet_sk(sk);
1223         struct ipv6_pinfo *np = inet6_sk(sk);
1224         DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
1225         struct in6_addr *daddr, *final_p, final;
1226         struct ipv6_txoptions *opt = NULL;
1227         struct ipv6_txoptions *opt_to_free = NULL;
1228         struct ip6_flowlabel *flowlabel = NULL;
1229         struct flowi6 fl6;
1230         struct dst_entry *dst;
1231         struct ipcm6_cookie ipc6;
1232         int addr_len = msg->msg_namelen;
1233         bool connected = false;
1234         int ulen = len;
1235         int corkreq = READ_ONCE(up->corkflag) || msg->msg_flags&MSG_MORE;
1236         int err;
1237         int is_udplite = IS_UDPLITE(sk);
1238         int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
1239
1240         ipcm6_init(&ipc6);
1241         ipc6.gso_size = READ_ONCE(up->gso_size);
1242         ipc6.sockc.tsflags = sk->sk_tsflags;
1243         ipc6.sockc.mark = sk->sk_mark;
1244
1245         /* destination address check */
1246         if (sin6) {
1247                 if (addr_len < offsetof(struct sockaddr, sa_data))
1248                         return -EINVAL;
1249
1250                 switch (sin6->sin6_family) {
1251                 case AF_INET6:
1252                         if (addr_len < SIN6_LEN_RFC2133)
1253                                 return -EINVAL;
1254                         daddr = &sin6->sin6_addr;
1255                         if (ipv6_addr_any(daddr) &&
1256                             ipv6_addr_v4mapped(&np->saddr))
1257                                 ipv6_addr_set_v4mapped(htonl(INADDR_LOOPBACK),
1258                                                        daddr);
1259                         break;
1260                 case AF_INET:
1261                         goto do_udp_sendmsg;
1262                 case AF_UNSPEC:
1263                         msg->msg_name = sin6 = NULL;
1264                         msg->msg_namelen = addr_len = 0;
1265                         daddr = NULL;
1266                         break;
1267                 default:
1268                         return -EINVAL;
1269                 }
1270         } else if (!up->pending) {
1271                 if (sk->sk_state != TCP_ESTABLISHED)
1272                         return -EDESTADDRREQ;
1273                 daddr = &sk->sk_v6_daddr;
1274         } else
1275                 daddr = NULL;
1276
1277         if (daddr) {
1278                 if (ipv6_addr_v4mapped(daddr)) {
1279                         struct sockaddr_in sin;
1280                         sin.sin_family = AF_INET;
1281                         sin.sin_port = sin6 ? sin6->sin6_port : inet->inet_dport;
1282                         sin.sin_addr.s_addr = daddr->s6_addr32[3];
1283                         msg->msg_name = &sin;
1284                         msg->msg_namelen = sizeof(sin);
1285 do_udp_sendmsg:
1286                         if (__ipv6_only_sock(sk))
1287                                 return -ENETUNREACH;
1288                         return udp_sendmsg(sk, msg, len);
1289                 }
1290         }
1291
1292         if (up->pending == AF_INET)
1293                 return udp_sendmsg(sk, msg, len);
1294
1295         /* Rough check on arithmetic overflow,
1296            better check is made in ip6_append_data().
1297            */
1298         if (len > INT_MAX - sizeof(struct udphdr))
1299                 return -EMSGSIZE;
1300
1301         getfrag  =  is_udplite ?  udplite_getfrag : ip_generic_getfrag;
1302         if (up->pending) {
1303                 /*
1304                  * There are pending frames.
1305                  * The socket lock must be held while it's corked.
1306                  */
1307                 lock_sock(sk);
1308                 if (likely(up->pending)) {
1309                         if (unlikely(up->pending != AF_INET6)) {
1310                                 release_sock(sk);
1311                                 return -EAFNOSUPPORT;
1312                         }
1313                         dst = NULL;
1314                         goto do_append_data;
1315                 }
1316                 release_sock(sk);
1317         }
1318         ulen += sizeof(struct udphdr);
1319
1320         memset(&fl6, 0, sizeof(fl6));
1321
1322         if (sin6) {
1323                 if (sin6->sin6_port == 0)
1324                         return -EINVAL;
1325
1326                 fl6.fl6_dport = sin6->sin6_port;
1327                 daddr = &sin6->sin6_addr;
1328
1329                 if (np->sndflow) {
1330                         fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
1331                         if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
1332                                 flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
1333                                 if (IS_ERR(flowlabel))
1334                                         return -EINVAL;
1335                         }
1336                 }
1337
1338                 /*
1339                  * Otherwise it will be difficult to maintain
1340                  * sk->sk_dst_cache.
1341                  */
1342                 if (sk->sk_state == TCP_ESTABLISHED &&
1343                     ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
1344                         daddr = &sk->sk_v6_daddr;
1345
1346                 if (addr_len >= sizeof(struct sockaddr_in6) &&
1347                     sin6->sin6_scope_id &&
1348                     __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
1349                         fl6.flowi6_oif = sin6->sin6_scope_id;
1350         } else {
1351                 if (sk->sk_state != TCP_ESTABLISHED)
1352                         return -EDESTADDRREQ;
1353
1354                 fl6.fl6_dport = inet->inet_dport;
1355                 daddr = &sk->sk_v6_daddr;
1356                 fl6.flowlabel = np->flow_label;
1357                 connected = true;
1358         }
1359
1360         if (!fl6.flowi6_oif)
1361                 fl6.flowi6_oif = sk->sk_bound_dev_if;
1362
1363         if (!fl6.flowi6_oif)
1364                 fl6.flowi6_oif = np->sticky_pktinfo.ipi6_ifindex;
1365
1366         fl6.flowi6_uid = sk->sk_uid;
1367
1368         if (msg->msg_controllen) {
1369                 opt = &opt_space;
1370                 memset(opt, 0, sizeof(struct ipv6_txoptions));
1371                 opt->tot_len = sizeof(*opt);
1372                 ipc6.opt = opt;
1373
1374                 err = udp_cmsg_send(sk, msg, &ipc6.gso_size);
1375                 if (err > 0)
1376                         err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6,
1377                                                     &ipc6);
1378                 if (err < 0) {
1379                         fl6_sock_release(flowlabel);
1380                         return err;
1381                 }
1382                 if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
1383                         flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
1384                         if (IS_ERR(flowlabel))
1385                                 return -EINVAL;
1386                 }
1387                 if (!(opt->opt_nflen|opt->opt_flen))
1388                         opt = NULL;
1389                 connected = false;
1390         }
1391         if (!opt) {
1392                 opt = txopt_get(np);
1393                 opt_to_free = opt;
1394         }
1395         if (flowlabel)
1396                 opt = fl6_merge_options(&opt_space, flowlabel, opt);
1397         opt = ipv6_fixup_options(&opt_space, opt);
1398         ipc6.opt = opt;
1399
1400         fl6.flowi6_proto = sk->sk_protocol;
1401         fl6.flowi6_mark = ipc6.sockc.mark;
1402         fl6.daddr = *daddr;
1403         if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
1404                 fl6.saddr = np->saddr;
1405         fl6.fl6_sport = inet->inet_sport;
1406
1407         if (cgroup_bpf_enabled && !connected) {
1408                 err = BPF_CGROUP_RUN_PROG_UDP6_SENDMSG_LOCK(sk,
1409                                            (struct sockaddr *)sin6, &fl6.saddr);
1410                 if (err)
1411                         goto out_no_dst;
1412                 if (sin6) {
1413                         if (ipv6_addr_v4mapped(&sin6->sin6_addr)) {
1414                                 /* BPF program rewrote IPv6-only by IPv4-mapped
1415                                  * IPv6. It's currently unsupported.
1416                                  */
1417                                 err = -ENOTSUPP;
1418                                 goto out_no_dst;
1419                         }
1420                         if (sin6->sin6_port == 0) {
1421                                 /* BPF program set invalid port. Reject it. */
1422                                 err = -EINVAL;
1423                                 goto out_no_dst;
1424                         }
1425                         fl6.fl6_dport = sin6->sin6_port;
1426                         fl6.daddr = sin6->sin6_addr;
1427                 }
1428         }
1429
1430         if (ipv6_addr_any(&fl6.daddr))
1431                 fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
1432
1433         final_p = fl6_update_dst(&fl6, opt, &final);
1434         if (final_p)
1435                 connected = false;
1436
1437         if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) {
1438                 fl6.flowi6_oif = np->mcast_oif;
1439                 connected = false;
1440         } else if (!fl6.flowi6_oif)
1441                 fl6.flowi6_oif = np->ucast_oif;
1442
1443         security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
1444
1445         if (ipc6.tclass < 0)
1446                 ipc6.tclass = np->tclass;
1447
1448         fl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel);
1449
1450         dst = ip6_sk_dst_lookup_flow(sk, &fl6, final_p, connected);
1451         if (IS_ERR(dst)) {
1452                 err = PTR_ERR(dst);
1453                 dst = NULL;
1454                 goto out;
1455         }
1456
1457         if (ipc6.hlimit < 0)
1458                 ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
1459
1460         if (msg->msg_flags&MSG_CONFIRM)
1461                 goto do_confirm;
1462 back_from_confirm:
1463
1464         /* Lockless fast path for the non-corking case */
1465         if (!corkreq) {
1466                 struct inet_cork_full cork;
1467                 struct sk_buff *skb;
1468
1469                 skb = ip6_make_skb(sk, getfrag, msg, ulen,
1470                                    sizeof(struct udphdr), &ipc6,
1471                                    &fl6, (struct rt6_info *)dst,
1472                                    msg->msg_flags, &cork);
1473                 err = PTR_ERR(skb);
1474                 if (!IS_ERR_OR_NULL(skb))
1475                         err = udp_v6_send_skb(skb, &fl6, &cork.base);
1476                 goto out;
1477         }
1478
1479         lock_sock(sk);
1480         if (unlikely(up->pending)) {
1481                 /* The socket is already corked while preparing it. */
1482                 /* ... which is an evident application bug. --ANK */
1483                 release_sock(sk);
1484
1485                 net_dbg_ratelimited("udp cork app bug 2\n");
1486                 err = -EINVAL;
1487                 goto out;
1488         }
1489
1490         up->pending = AF_INET6;
1491
1492 do_append_data:
1493         if (ipc6.dontfrag < 0)
1494                 ipc6.dontfrag = np->dontfrag;
1495         up->len += ulen;
1496         err = ip6_append_data(sk, getfrag, msg, ulen, sizeof(struct udphdr),
1497                               &ipc6, &fl6, (struct rt6_info *)dst,
1498                               corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1499         if (err)
1500                 udp_v6_flush_pending_frames(sk);
1501         else if (!corkreq)
1502                 err = udp_v6_push_pending_frames(sk);
1503         else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1504                 up->pending = 0;
1505
1506         if (err > 0)
1507                 err = np->recverr ? net_xmit_errno(err) : 0;
1508         release_sock(sk);
1509
1510 out:
1511         dst_release(dst);
1512 out_no_dst:
1513         fl6_sock_release(flowlabel);
1514         txopt_put(opt_to_free);
1515         if (!err)
1516                 return len;
1517         /*
1518          * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space.  Reporting
1519          * ENOBUFS might not be good (it's not tunable per se), but otherwise
1520          * we don't have a good statistic (IpOutDiscards but it can be too many
1521          * things).  We could add another new stat but at least for now that
1522          * seems like overkill.
1523          */
1524         if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
1525                 UDP6_INC_STATS(sock_net(sk),
1526                                UDP_MIB_SNDBUFERRORS, is_udplite);
1527         }
1528         return err;
1529
1530 do_confirm:
1531         if (msg->msg_flags & MSG_PROBE)
1532                 dst_confirm_neigh(dst, &fl6.daddr);
1533         if (!(msg->msg_flags&MSG_PROBE) || len)
1534                 goto back_from_confirm;
1535         err = 0;
1536         goto out;
1537 }
1538
1539 void udpv6_destroy_sock(struct sock *sk)
1540 {
1541         struct udp_sock *up = udp_sk(sk);
1542         lock_sock(sk);
1543
1544         /* protects from races with udp_abort() */
1545         sock_set_flag(sk, SOCK_DEAD);
1546         udp_v6_flush_pending_frames(sk);
1547         release_sock(sk);
1548
1549         if (static_branch_unlikely(&udpv6_encap_needed_key)) {
1550                 if (up->encap_type) {
1551                         void (*encap_destroy)(struct sock *sk);
1552                         encap_destroy = READ_ONCE(up->encap_destroy);
1553                         if (encap_destroy)
1554                                 encap_destroy(sk);
1555                 }
1556                 if (up->encap_enabled) {
1557                         static_branch_dec(&udpv6_encap_needed_key);
1558                         udp_encap_disable();
1559                 }
1560         }
1561
1562         inet6_destroy_sock(sk);
1563 }
1564
1565 /*
1566  *      Socket option code for UDP
1567  */
1568 int udpv6_setsockopt(struct sock *sk, int level, int optname,
1569                      char __user *optval, unsigned int optlen)
1570 {
1571         if (level == SOL_UDP  ||  level == SOL_UDPLITE)
1572                 return udp_lib_setsockopt(sk, level, optname, optval, optlen,
1573                                           udp_v6_push_pending_frames);
1574         return ipv6_setsockopt(sk, level, optname, optval, optlen);
1575 }
1576
1577 #ifdef CONFIG_COMPAT
1578 int compat_udpv6_setsockopt(struct sock *sk, int level, int optname,
1579                             char __user *optval, unsigned int optlen)
1580 {
1581         if (level == SOL_UDP  ||  level == SOL_UDPLITE)
1582                 return udp_lib_setsockopt(sk, level, optname, optval, optlen,
1583                                           udp_v6_push_pending_frames);
1584         return compat_ipv6_setsockopt(sk, level, optname, optval, optlen);
1585 }
1586 #endif
1587
1588 int udpv6_getsockopt(struct sock *sk, int level, int optname,
1589                      char __user *optval, int __user *optlen)
1590 {
1591         if (level == SOL_UDP  ||  level == SOL_UDPLITE)
1592                 return udp_lib_getsockopt(sk, level, optname, optval, optlen);
1593         return ipv6_getsockopt(sk, level, optname, optval, optlen);
1594 }
1595
1596 #ifdef CONFIG_COMPAT
1597 int compat_udpv6_getsockopt(struct sock *sk, int level, int optname,
1598                             char __user *optval, int __user *optlen)
1599 {
1600         if (level == SOL_UDP  ||  level == SOL_UDPLITE)
1601                 return udp_lib_getsockopt(sk, level, optname, optval, optlen);
1602         return compat_ipv6_getsockopt(sk, level, optname, optval, optlen);
1603 }
1604 #endif
1605
1606 /* thinking of making this const? Don't.
1607  * early_demux can change based on sysctl.
1608  */
1609 static struct inet6_protocol udpv6_protocol = {
1610         .early_demux    =       udp_v6_early_demux,
1611         .early_demux_handler =  udp_v6_early_demux,
1612         .handler        =       udpv6_rcv,
1613         .err_handler    =       udpv6_err,
1614         .flags          =       INET6_PROTO_NOPOLICY|INET6_PROTO_FINAL,
1615 };
1616
1617 /* ------------------------------------------------------------------------ */
1618 #ifdef CONFIG_PROC_FS
1619 int udp6_seq_show(struct seq_file *seq, void *v)
1620 {
1621         if (v == SEQ_START_TOKEN) {
1622                 seq_puts(seq, IPV6_SEQ_DGRAM_HEADER);
1623         } else {
1624                 int bucket = ((struct udp_iter_state *)seq->private)->bucket;
1625                 struct inet_sock *inet = inet_sk(v);
1626                 __u16 srcp = ntohs(inet->inet_sport);
1627                 __u16 destp = ntohs(inet->inet_dport);
1628                 __ip6_dgram_sock_seq_show(seq, v, srcp, destp,
1629                                           udp_rqueue_get(v), bucket);
1630         }
1631         return 0;
1632 }
1633
1634 const struct seq_operations udp6_seq_ops = {
1635         .start          = udp_seq_start,
1636         .next           = udp_seq_next,
1637         .stop           = udp_seq_stop,
1638         .show           = udp6_seq_show,
1639 };
1640 EXPORT_SYMBOL(udp6_seq_ops);
1641
1642 static struct udp_seq_afinfo udp6_seq_afinfo = {
1643         .family         = AF_INET6,
1644         .udp_table      = &udp_table,
1645 };
1646
1647 int __net_init udp6_proc_init(struct net *net)
1648 {
1649         if (!proc_create_net_data("udp6", 0444, net->proc_net, &udp6_seq_ops,
1650                         sizeof(struct udp_iter_state), &udp6_seq_afinfo))
1651                 return -ENOMEM;
1652         return 0;
1653 }
1654
1655 void udp6_proc_exit(struct net *net)
1656 {
1657         remove_proc_entry("udp6", net->proc_net);
1658 }
1659 #endif /* CONFIG_PROC_FS */
1660
1661 /* ------------------------------------------------------------------------ */
1662
1663 struct proto udpv6_prot = {
1664         .name                   = "UDPv6",
1665         .owner                  = THIS_MODULE,
1666         .close                  = udp_lib_close,
1667         .pre_connect            = udpv6_pre_connect,
1668         .connect                = ip6_datagram_connect,
1669         .disconnect             = udp_disconnect,
1670         .ioctl                  = udp_ioctl,
1671         .init                   = udp_init_sock,
1672         .destroy                = udpv6_destroy_sock,
1673         .setsockopt             = udpv6_setsockopt,
1674         .getsockopt             = udpv6_getsockopt,
1675         .sendmsg                = udpv6_sendmsg,
1676         .recvmsg                = udpv6_recvmsg,
1677         .release_cb             = ip6_datagram_release_cb,
1678         .hash                   = udp_lib_hash,
1679         .unhash                 = udp_lib_unhash,
1680         .rehash                 = udp_v6_rehash,
1681         .get_port               = udp_v6_get_port,
1682         .memory_allocated       = &udp_memory_allocated,
1683         .sysctl_mem             = sysctl_udp_mem,
1684         .sysctl_wmem_offset     = offsetof(struct net, ipv4.sysctl_udp_wmem_min),
1685         .sysctl_rmem_offset     = offsetof(struct net, ipv4.sysctl_udp_rmem_min),
1686         .obj_size               = sizeof(struct udp6_sock),
1687         .h.udp_table            = &udp_table,
1688 #ifdef CONFIG_COMPAT
1689         .compat_setsockopt      = compat_udpv6_setsockopt,
1690         .compat_getsockopt      = compat_udpv6_getsockopt,
1691 #endif
1692         .diag_destroy           = udp_abort,
1693 };
1694
1695 static struct inet_protosw udpv6_protosw = {
1696         .type =      SOCK_DGRAM,
1697         .protocol =  IPPROTO_UDP,
1698         .prot =      &udpv6_prot,
1699         .ops =       &inet6_dgram_ops,
1700         .flags =     INET_PROTOSW_PERMANENT,
1701 };
1702
1703 int __init udpv6_init(void)
1704 {
1705         int ret;
1706
1707         ret = inet6_add_protocol(&udpv6_protocol, IPPROTO_UDP);
1708         if (ret)
1709                 goto out;
1710
1711         ret = inet6_register_protosw(&udpv6_protosw);
1712         if (ret)
1713                 goto out_udpv6_protocol;
1714 out:
1715         return ret;
1716
1717 out_udpv6_protocol:
1718         inet6_del_protocol(&udpv6_protocol, IPPROTO_UDP);
1719         goto out;
1720 }
1721
1722 void udpv6_exit(void)
1723 {
1724         inet6_unregister_protosw(&udpv6_protosw);
1725         inet6_del_protocol(&udpv6_protocol, IPPROTO_UDP);
1726 }