1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * INET An implementation of the TCP/IP protocol suite for the LINUX
4 * operating system. INET is implemented using the BSD Socket
5 * interface as the means of communication with the user level.
6 *
7 * The User Datagram Protocol (UDP).
8 *
9 * Authors: Ross Biro
10 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11 * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
12 * Alan Cox, <alan@lxorguk.ukuu.org.uk>
13 * Hirokazu Takahashi, <taka@valinux.co.jp>
14 *
15 * Fixes:
16 * Alan Cox : verify_area() calls
17 * Alan Cox : stopped close while in use off icmp
18 * messages. Not a fix but a botch that
19 * for udp at least is 'valid'.
20 * Alan Cox : Fixed icmp handling properly
21 * Alan Cox : Correct error for oversized datagrams
22 * Alan Cox : Tidied select() semantics.
23 * Alan Cox : udp_err() fixed properly, also now
24 * select and read wake correctly on errors
25 * Alan Cox : udp_send verify_area moved to avoid mem leak
26 * Alan Cox : UDP can count its memory
27 * Alan Cox : send to an unknown connection causes
28 * an ECONNREFUSED off the icmp, but
29 * does NOT close.
30 * Alan Cox : Switched to new sk_buff handlers. No more backlog!
31 * Alan Cox : Using generic datagram code. Even smaller and the PEEK
32 * bug no longer crashes it.
33 * Fred Van Kempen : Net2e support for sk->broadcast.
34 * Alan Cox : Uses skb_free_datagram
35 * Alan Cox : Added get/set sockopt support.
36 * Alan Cox : Broadcasting without option set returns EACCES.
37 * Alan Cox : No wakeup calls. Instead we now use the callbacks.
38 * Alan Cox : Use ip_tos and ip_ttl
39 * Alan Cox : SNMP Mibs
40 * Alan Cox : MSG_DONTROUTE, and 0.0.0.0 support.
41 * Matt Dillon : UDP length checks.
42 * Alan Cox : Smarter af_inet used properly.
43 * Alan Cox : Use new kernel side addressing.
44 * Alan Cox : Incorrect return on truncated datagram receive.
45 * Arnt Gulbrandsen : New udp_send and stuff
46 * Alan Cox : Cache last socket
47 * Alan Cox : Route cache
48 * Jon Peatfield : Minor efficiency fix to sendto().
49 * Mike Shaver : RFC1122 checks.
50 * Alan Cox : Nonblocking error fix.
51 * Willy Konynenberg : Transparent proxying support.
52 * Mike McLagan : Routing by source
53 * David S. Miller : New socket lookup architecture.
54 * Last socket cache retained as it
55 * does have a high hit rate.
56 * Olaf Kirch : Don't linearise iovec on sendmsg.
57 * Andi Kleen : Some cleanups, cache destination entry
58 * for connect.
59 * Vitaly E. Lavrov : Transparent proxy revived after year coma.
60 * Melvin Smith : Check msg_name not msg_namelen in sendto(),
61 * return ENOTCONN for unconnected sockets (POSIX)
62 * Janos Farkas : don't deliver multi/broadcasts to a different
63 * bound-to-device socket
64 * Hirokazu Takahashi : HW checksumming for outgoing UDP
65 * datagrams.
66 * Hirokazu Takahashi : sendfile() on UDP works now.
67 * Arnaldo C. Melo : convert /proc/net/udp to seq_file
68 * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which
69 * Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind
70 * a single port at the same time.
71 * Derek Atkins <derek@ihtfp.com>: Add Encapulation Support
72 * James Chapman : Add L2TP encapsulation type.
73 */
74
75 #define pr_fmt(fmt) "UDP: " fmt
76
77 #include <linux/bpf-cgroup.h>
78 #include <linux/uaccess.h>
79 #include <asm/ioctls.h>
80 #include <linux/memblock.h>
81 #include <linux/highmem.h>
82 #include <linux/types.h>
83 #include <linux/fcntl.h>
84 #include <linux/module.h>
85 #include <linux/socket.h>
86 #include <linux/sockios.h>
87 #include <linux/igmp.h>
88 #include <linux/inetdevice.h>
89 #include <linux/in.h>
90 #include <linux/errno.h>
91 #include <linux/timer.h>
92 #include <linux/mm.h>
93 #include <linux/inet.h>
94 #include <linux/netdevice.h>
95 #include <linux/slab.h>
96 #include <net/tcp_states.h>
97 #include <linux/skbuff.h>
98 #include <linux/proc_fs.h>
99 #include <linux/seq_file.h>
100 #include <net/net_namespace.h>
101 #include <net/icmp.h>
102 #include <net/inet_hashtables.h>
103 #include <net/ip_tunnels.h>
104 #include <net/route.h>
105 #include <net/checksum.h>
106 #include <net/gso.h>
107 #include <net/xfrm.h>
108 #include <trace/events/udp.h>
109 #include <linux/static_key.h>
110 #include <linux/btf_ids.h>
111 #include <trace/events/skb.h>
112 #include <net/busy_poll.h>
113 #include "udp_impl.h"
114 #include <net/sock_reuseport.h>
115 #include <net/addrconf.h>
116 #include <net/udp_tunnel.h>
117 #include <net/gro.h>
118 #if IS_ENABLED(CONFIG_IPV6)
119 #include <net/ipv6_stubs.h>
120 #endif
121 #include <trace/hooks/net.h>
122
123 struct udp_table udp_table __read_mostly;
124 EXPORT_SYMBOL(udp_table);
125
126 long sysctl_udp_mem[3] __read_mostly;
127 EXPORT_SYMBOL(sysctl_udp_mem);
128
129 atomic_long_t udp_memory_allocated ____cacheline_aligned_in_smp;
130 EXPORT_SYMBOL(udp_memory_allocated);
131 DEFINE_PER_CPU(int, udp_memory_per_cpu_fw_alloc);
132 EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc);
133
134 #define MAX_UDP_PORTS 65536
135 #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN_PERNET)
136
udp_get_table_prot(struct sock * sk)137 static struct udp_table *udp_get_table_prot(struct sock *sk)
138 {
139 return sk->sk_prot->h.udp_table ? : sock_net(sk)->ipv4.udp_table;
140 }
141
udp_lib_lport_inuse(struct net * net,__u16 num,const struct udp_hslot * hslot,unsigned long * bitmap,struct sock * sk,unsigned int log)142 static int udp_lib_lport_inuse(struct net *net, __u16 num,
143 const struct udp_hslot *hslot,
144 unsigned long *bitmap,
145 struct sock *sk, unsigned int log)
146 {
147 struct sock *sk2;
148 kuid_t uid = sock_i_uid(sk);
149
150 sk_for_each(sk2, &hslot->head) {
151 if (net_eq(sock_net(sk2), net) &&
152 sk2 != sk &&
153 (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
154 (!sk2->sk_reuse || !sk->sk_reuse) &&
155 (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
156 sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
157 inet_rcv_saddr_equal(sk, sk2, true)) {
158 if (sk2->sk_reuseport && sk->sk_reuseport &&
159 !rcu_access_pointer(sk->sk_reuseport_cb) &&
160 uid_eq(uid, sock_i_uid(sk2))) {
161 if (!bitmap)
162 return 0;
163 } else {
164 if (!bitmap)
165 return 1;
166 __set_bit(udp_sk(sk2)->udp_port_hash >> log,
167 bitmap);
168 }
169 }
170 }
171 return 0;
172 }
173
174 /*
175 * Note: we still hold spinlock of primary hash chain, so no other writer
176 * can insert/delete a socket with local_port == num
177 */
udp_lib_lport_inuse2(struct net * net,__u16 num,struct udp_hslot * hslot2,struct sock * sk)178 static int udp_lib_lport_inuse2(struct net *net, __u16 num,
179 struct udp_hslot *hslot2,
180 struct sock *sk)
181 {
182 struct sock *sk2;
183 kuid_t uid = sock_i_uid(sk);
184 int res = 0;
185
186 spin_lock(&hslot2->lock);
187 udp_portaddr_for_each_entry(sk2, &hslot2->head) {
188 if (net_eq(sock_net(sk2), net) &&
189 sk2 != sk &&
190 (udp_sk(sk2)->udp_port_hash == num) &&
191 (!sk2->sk_reuse || !sk->sk_reuse) &&
192 (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
193 sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
194 inet_rcv_saddr_equal(sk, sk2, true)) {
195 if (sk2->sk_reuseport && sk->sk_reuseport &&
196 !rcu_access_pointer(sk->sk_reuseport_cb) &&
197 uid_eq(uid, sock_i_uid(sk2))) {
198 res = 0;
199 } else {
200 res = 1;
201 }
202 break;
203 }
204 }
205 spin_unlock(&hslot2->lock);
206 return res;
207 }
208
udp_reuseport_add_sock(struct sock * sk,struct udp_hslot * hslot)209 static int udp_reuseport_add_sock(struct sock *sk, struct udp_hslot *hslot)
210 {
211 struct net *net = sock_net(sk);
212 kuid_t uid = sock_i_uid(sk);
213 struct sock *sk2;
214
215 sk_for_each(sk2, &hslot->head) {
216 if (net_eq(sock_net(sk2), net) &&
217 sk2 != sk &&
218 sk2->sk_family == sk->sk_family &&
219 ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
220 (udp_sk(sk2)->udp_port_hash == udp_sk(sk)->udp_port_hash) &&
221 (sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
222 sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
223 inet_rcv_saddr_equal(sk, sk2, false)) {
224 return reuseport_add_sock(sk, sk2,
225 inet_rcv_saddr_any(sk));
226 }
227 }
228
229 return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
230 }
231
232 /**
233 * udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6
234 *
235 * @sk: socket struct in question
236 * @snum: port number to look up
237 * @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
238 * with NULL address
239 */
udp_lib_get_port(struct sock * sk,unsigned short snum,unsigned int hash2_nulladdr)240 int udp_lib_get_port(struct sock *sk, unsigned short snum,
241 unsigned int hash2_nulladdr)
242 {
243 struct udp_table *udptable = udp_get_table_prot(sk);
244 struct udp_hslot *hslot, *hslot2;
245 struct net *net = sock_net(sk);
246 int error = -EADDRINUSE;
247
248 if (!snum) {
249 DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
250 unsigned short first, last;
251 int low, high, remaining;
252 unsigned int rand;
253
254 inet_sk_get_local_port_range(sk, &low, &high);
255 remaining = (high - low) + 1;
256
257 rand = get_random_u32();
258 first = reciprocal_scale(rand, remaining) + low;
259 /*
260 * force rand to be an odd multiple of UDP_HTABLE_SIZE
261 */
262 rand = (rand | 1) * (udptable->mask + 1);
263 last = first + udptable->mask + 1;
264 do {
265 hslot = udp_hashslot(udptable, net, first);
266 bitmap_zero(bitmap, PORTS_PER_CHAIN);
267 spin_lock_bh(&hslot->lock);
268 udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
269 udptable->log);
270
271 snum = first;
272 /*
273 * Iterate on all possible values of snum for this hash.
274 * Using steps of an odd multiple of UDP_HTABLE_SIZE
275 * give us randomization and full range coverage.
276 */
277 do {
278 if (low <= snum && snum <= high &&
279 !test_bit(snum >> udptable->log, bitmap) &&
280 !inet_is_local_reserved_port(net, snum))
281 goto found;
282 snum += rand;
283 } while (snum != first);
284 spin_unlock_bh(&hslot->lock);
285 cond_resched();
286 } while (++first != last);
287 goto fail;
288 } else {
289 hslot = udp_hashslot(udptable, net, snum);
290 spin_lock_bh(&hslot->lock);
291 if (hslot->count > 10) {
292 int exist;
293 unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
294
295 slot2 &= udptable->mask;
296 hash2_nulladdr &= udptable->mask;
297
298 hslot2 = udp_hashslot2(udptable, slot2);
299 if (hslot->count < hslot2->count)
300 goto scan_primary_hash;
301
302 exist = udp_lib_lport_inuse2(net, snum, hslot2, sk);
303 if (!exist && (hash2_nulladdr != slot2)) {
304 hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
305 exist = udp_lib_lport_inuse2(net, snum, hslot2,
306 sk);
307 }
308 if (exist)
309 goto fail_unlock;
310 else
311 goto found;
312 }
313 scan_primary_hash:
314 if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0))
315 goto fail_unlock;
316 }
317 found:
318 inet_sk(sk)->inet_num = snum;
319 udp_sk(sk)->udp_port_hash = snum;
320 udp_sk(sk)->udp_portaddr_hash ^= snum;
321 if (sk_unhashed(sk)) {
322 if (sk->sk_reuseport &&
323 udp_reuseport_add_sock(sk, hslot)) {
324 inet_sk(sk)->inet_num = 0;
325 udp_sk(sk)->udp_port_hash = 0;
326 udp_sk(sk)->udp_portaddr_hash ^= snum;
327 goto fail_unlock;
328 }
329
330 sock_set_flag(sk, SOCK_RCU_FREE);
331
332 sk_add_node_rcu(sk, &hslot->head);
333 hslot->count++;
334 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
335
336 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
337 spin_lock(&hslot2->lock);
338 if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
339 sk->sk_family == AF_INET6)
340 hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node,
341 &hslot2->head);
342 else
343 hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
344 &hslot2->head);
345 hslot2->count++;
346 spin_unlock(&hslot2->lock);
347 }
348
349 error = 0;
350 fail_unlock:
351 spin_unlock_bh(&hslot->lock);
352 fail:
353 return error;
354 }
355 EXPORT_SYMBOL(udp_lib_get_port);
356
udp_v4_get_port(struct sock * sk,unsigned short snum)357 int udp_v4_get_port(struct sock *sk, unsigned short snum)
358 {
359 unsigned int hash2_nulladdr =
360 ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
361 unsigned int hash2_partial =
362 ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
363
364 /* precompute partial secondary hash */
365 udp_sk(sk)->udp_portaddr_hash = hash2_partial;
366 return udp_lib_get_port(sk, snum, hash2_nulladdr);
367 }
368
compute_score(struct sock * sk,struct net * net,__be32 saddr,__be16 sport,__be32 daddr,unsigned short hnum,int dif,int sdif)369 static int compute_score(struct sock *sk, struct net *net,
370 __be32 saddr, __be16 sport,
371 __be32 daddr, unsigned short hnum,
372 int dif, int sdif)
373 {
374 int score;
375 struct inet_sock *inet;
376 bool dev_match;
377
378 if (!net_eq(sock_net(sk), net) ||
379 udp_sk(sk)->udp_port_hash != hnum ||
380 ipv6_only_sock(sk))
381 return -1;
382
383 if (sk->sk_rcv_saddr != daddr)
384 return -1;
385
386 score = (sk->sk_family == PF_INET) ? 2 : 1;
387
388 inet = inet_sk(sk);
389 if (inet->inet_daddr) {
390 if (inet->inet_daddr != saddr)
391 return -1;
392 score += 4;
393 }
394
395 if (inet->inet_dport) {
396 if (inet->inet_dport != sport)
397 return -1;
398 score += 4;
399 }
400
401 dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
402 dif, sdif);
403 if (!dev_match)
404 return -1;
405 if (sk->sk_bound_dev_if)
406 score += 4;
407
408 if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
409 score++;
410 return score;
411 }
412
413 INDIRECT_CALLABLE_SCOPE
udp_ehashfn(const struct net * net,const __be32 laddr,const __u16 lport,const __be32 faddr,const __be16 fport)414 u32 udp_ehashfn(const struct net *net, const __be32 laddr, const __u16 lport,
415 const __be32 faddr, const __be16 fport)
416 {
417 static u32 udp_ehash_secret __read_mostly;
418
419 net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret));
420
421 return __inet_ehashfn(laddr, lport, faddr, fport,
422 udp_ehash_secret + net_hash_mix(net));
423 }
424
425 /* called with rcu_read_lock() */
udp4_lib_lookup2(struct net * net,__be32 saddr,__be16 sport,__be32 daddr,unsigned int hnum,int dif,int sdif,struct udp_hslot * hslot2,struct sk_buff * skb)426 static struct sock *udp4_lib_lookup2(struct net *net,
427 __be32 saddr, __be16 sport,
428 __be32 daddr, unsigned int hnum,
429 int dif, int sdif,
430 struct udp_hslot *hslot2,
431 struct sk_buff *skb)
432 {
433 struct sock *sk, *result;
434 int score, badness;
435 bool need_rescore;
436
437 result = NULL;
438 badness = 0;
439 udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
440 need_rescore = false;
441 rescore:
442 score = compute_score(need_rescore ? result : sk, net, saddr,
443 sport, daddr, hnum, dif, sdif);
444 if (score > badness) {
445 badness = score;
446
447 if (need_rescore)
448 continue;
449
450 if (sk->sk_state == TCP_ESTABLISHED) {
451 result = sk;
452 continue;
453 }
454
455 result = inet_lookup_reuseport(net, sk, skb, sizeof(struct udphdr),
456 saddr, sport, daddr, hnum, udp_ehashfn);
457 if (!result) {
458 result = sk;
459 continue;
460 }
461
462 /* Fall back to scoring if group has connections */
463 if (!reuseport_has_conns(sk))
464 return result;
465
466 /* Reuseport logic returned an error, keep original score. */
467 if (IS_ERR(result))
468 continue;
469
470 /* compute_score is too long of a function to be
471 * inlined, and calling it again here yields
472 * measureable overhead for some
473 * workloads. Work around it by jumping
474 * backwards to rescore 'result'.
475 */
476 need_rescore = true;
477 goto rescore;
478 }
479 }
480 return result;
481 }
482
483 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
484 * harder than this. -DaveM
485 */
__udp4_lib_lookup(struct net * net,__be32 saddr,__be16 sport,__be32 daddr,__be16 dport,int dif,int sdif,struct udp_table * udptable,struct sk_buff * skb)486 struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
487 __be16 sport, __be32 daddr, __be16 dport, int dif,
488 int sdif, struct udp_table *udptable, struct sk_buff *skb)
489 {
490 unsigned short hnum = ntohs(dport);
491 unsigned int hash2, slot2;
492 struct udp_hslot *hslot2;
493 struct sock *result, *sk;
494
495 hash2 = ipv4_portaddr_hash(net, daddr, hnum);
496 slot2 = hash2 & udptable->mask;
497 hslot2 = &udptable->hash2[slot2];
498
499 /* Lookup connected or non-wildcard socket */
500 result = udp4_lib_lookup2(net, saddr, sport,
501 daddr, hnum, dif, sdif,
502 hslot2, skb);
503 if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED)
504 goto done;
505
506 /* Lookup redirect from BPF */
507 if (static_branch_unlikely(&bpf_sk_lookup_enabled) &&
508 udptable == net->ipv4.udp_table) {
509 sk = inet_lookup_run_sk_lookup(net, IPPROTO_UDP, skb, sizeof(struct udphdr),
510 saddr, sport, daddr, hnum, dif,
511 udp_ehashfn);
512 if (sk) {
513 result = sk;
514 goto done;
515 }
516 }
517
518 /* Got non-wildcard socket or error on first lookup */
519 if (result)
520 goto done;
521
522 /* Lookup wildcard sockets */
523 hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
524 slot2 = hash2 & udptable->mask;
525 hslot2 = &udptable->hash2[slot2];
526
527 result = udp4_lib_lookup2(net, saddr, sport,
528 htonl(INADDR_ANY), hnum, dif, sdif,
529 hslot2, skb);
530 done:
531 if (IS_ERR(result))
532 return NULL;
533 return result;
534 }
535 EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
536
__udp4_lib_lookup_skb(struct sk_buff * skb,__be16 sport,__be16 dport,struct udp_table * udptable)537 static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
538 __be16 sport, __be16 dport,
539 struct udp_table *udptable)
540 {
541 const struct iphdr *iph = ip_hdr(skb);
542
543 return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport,
544 iph->daddr, dport, inet_iif(skb),
545 inet_sdif(skb), udptable, skb);
546 }
547
udp4_lib_lookup_skb(const struct sk_buff * skb,__be16 sport,__be16 dport)548 struct sock *udp4_lib_lookup_skb(const struct sk_buff *skb,
549 __be16 sport, __be16 dport)
550 {
551 const u16 offset = NAPI_GRO_CB(skb)->network_offsets[skb->encapsulation];
552 const struct iphdr *iph = (struct iphdr *)(skb->data + offset);
553 struct net *net = dev_net(skb->dev);
554 int iif, sdif;
555
556 inet_get_iif_sdif(skb, &iif, &sdif);
557
558 return __udp4_lib_lookup(net, iph->saddr, sport,
559 iph->daddr, dport, iif,
560 sdif, net->ipv4.udp_table, NULL);
561 }
562
563 /* Must be called under rcu_read_lock().
564 * Does increment socket refcount.
565 */
566 #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4)
udp4_lib_lookup(struct net * net,__be32 saddr,__be16 sport,__be32 daddr,__be16 dport,int dif)567 struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
568 __be32 daddr, __be16 dport, int dif)
569 {
570 struct sock *sk;
571
572 sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport,
573 dif, 0, net->ipv4.udp_table, NULL);
574 if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
575 sk = NULL;
576 return sk;
577 }
578 EXPORT_SYMBOL_GPL(udp4_lib_lookup);
579 #endif
580
__udp_is_mcast_sock(struct net * net,const struct sock * sk,__be16 loc_port,__be32 loc_addr,__be16 rmt_port,__be32 rmt_addr,int dif,int sdif,unsigned short hnum)581 static inline bool __udp_is_mcast_sock(struct net *net, const struct sock *sk,
582 __be16 loc_port, __be32 loc_addr,
583 __be16 rmt_port, __be32 rmt_addr,
584 int dif, int sdif, unsigned short hnum)
585 {
586 const struct inet_sock *inet = inet_sk(sk);
587
588 if (!net_eq(sock_net(sk), net) ||
589 udp_sk(sk)->udp_port_hash != hnum ||
590 (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
591 (inet->inet_dport != rmt_port && inet->inet_dport) ||
592 (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) ||
593 ipv6_only_sock(sk) ||
594 !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
595 return false;
596 if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif))
597 return false;
598 return true;
599 }
600
601 DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key);
602 EXPORT_SYMBOL(udp_encap_needed_key);
603
604 #if IS_ENABLED(CONFIG_IPV6)
605 DEFINE_STATIC_KEY_FALSE(udpv6_encap_needed_key);
606 EXPORT_SYMBOL(udpv6_encap_needed_key);
607 #endif
608
udp_encap_enable(void)609 void udp_encap_enable(void)
610 {
611 static_branch_inc(&udp_encap_needed_key);
612 }
613 EXPORT_SYMBOL(udp_encap_enable);
614
udp_encap_disable(void)615 void udp_encap_disable(void)
616 {
617 static_branch_dec(&udp_encap_needed_key);
618 }
619 EXPORT_SYMBOL(udp_encap_disable);
620
621 /* Handler for tunnels with arbitrary destination ports: no socket lookup, go
622 * through error handlers in encapsulations looking for a match.
623 */
__udp4_lib_err_encap_no_sk(struct sk_buff * skb,u32 info)624 static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info)
625 {
626 int i;
627
628 for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) {
629 int (*handler)(struct sk_buff *skb, u32 info);
630 const struct ip_tunnel_encap_ops *encap;
631
632 encap = rcu_dereference(iptun_encaps[i]);
633 if (!encap)
634 continue;
635 handler = encap->err_handler;
636 if (handler && !handler(skb, info))
637 return 0;
638 }
639
640 return -ENOENT;
641 }
642
643 /* Try to match ICMP errors to UDP tunnels by looking up a socket without
644 * reversing source and destination port: this will match tunnels that force the
645 * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that
646 * lwtunnels might actually break this assumption by being configured with
647 * different destination ports on endpoints, in this case we won't be able to
648 * trace ICMP messages back to them.
649 *
650 * If this doesn't match any socket, probe tunnels with arbitrary destination
651 * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port
652 * we've sent packets to won't necessarily match the local destination port.
653 *
654 * Then ask the tunnel implementation to match the error against a valid
655 * association.
656 *
657 * Return an error if we can't find a match, the socket if we need further
658 * processing, zero otherwise.
659 */
__udp4_lib_err_encap(struct net * net,const struct iphdr * iph,struct udphdr * uh,struct udp_table * udptable,struct sock * sk,struct sk_buff * skb,u32 info)660 static struct sock *__udp4_lib_err_encap(struct net *net,
661 const struct iphdr *iph,
662 struct udphdr *uh,
663 struct udp_table *udptable,
664 struct sock *sk,
665 struct sk_buff *skb, u32 info)
666 {
667 int (*lookup)(struct sock *sk, struct sk_buff *skb);
668 int network_offset, transport_offset;
669 struct udp_sock *up;
670
671 network_offset = skb_network_offset(skb);
672 transport_offset = skb_transport_offset(skb);
673
674 /* Network header needs to point to the outer IPv4 header inside ICMP */
675 skb_reset_network_header(skb);
676
677 /* Transport header needs to point to the UDP header */
678 skb_set_transport_header(skb, iph->ihl << 2);
679
680 if (sk) {
681 up = udp_sk(sk);
682
683 lookup = READ_ONCE(up->encap_err_lookup);
684 if (lookup && lookup(sk, skb))
685 sk = NULL;
686
687 goto out;
688 }
689
690 sk = __udp4_lib_lookup(net, iph->daddr, uh->source,
691 iph->saddr, uh->dest, skb->dev->ifindex, 0,
692 udptable, NULL);
693 if (sk) {
694 up = udp_sk(sk);
695
696 lookup = READ_ONCE(up->encap_err_lookup);
697 if (!lookup || lookup(sk, skb))
698 sk = NULL;
699 }
700
701 out:
702 if (!sk)
703 sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info));
704
705 skb_set_transport_header(skb, transport_offset);
706 skb_set_network_header(skb, network_offset);
707
708 return sk;
709 }
710
711 /*
712 * This routine is called by the ICMP module when it gets some
713 * sort of error condition. If err < 0 then the socket should
714 * be closed and the error returned to the user. If err > 0
715 * it's just the icmp type << 8 | icmp code.
716 * Header points to the ip header of the error packet. We move
717 * on past this. Then (as it used to claim before adjustment)
718 * header points to the first 8 bytes of the udp header. We need
719 * to find the appropriate port.
720 */
721
__udp4_lib_err(struct sk_buff * skb,u32 info,struct udp_table * udptable)722 int __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
723 {
724 struct inet_sock *inet;
725 const struct iphdr *iph = (const struct iphdr *)skb->data;
726 struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
727 const int type = icmp_hdr(skb)->type;
728 const int code = icmp_hdr(skb)->code;
729 bool tunnel = false;
730 struct sock *sk;
731 int harderr;
732 int err;
733 struct net *net = dev_net(skb->dev);
734
735 sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
736 iph->saddr, uh->source, skb->dev->ifindex,
737 inet_sdif(skb), udptable, NULL);
738
739 if (!sk || READ_ONCE(udp_sk(sk)->encap_type)) {
740 /* No socket for error: try tunnels before discarding */
741 if (static_branch_unlikely(&udp_encap_needed_key)) {
742 sk = __udp4_lib_err_encap(net, iph, uh, udptable, sk, skb,
743 info);
744 if (!sk)
745 return 0;
746 } else
747 sk = ERR_PTR(-ENOENT);
748
749 if (IS_ERR(sk)) {
750 __ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
751 return PTR_ERR(sk);
752 }
753
754 tunnel = true;
755 }
756
757 err = 0;
758 harderr = 0;
759 inet = inet_sk(sk);
760
761 switch (type) {
762 default:
763 case ICMP_TIME_EXCEEDED:
764 err = EHOSTUNREACH;
765 break;
766 case ICMP_SOURCE_QUENCH:
767 goto out;
768 case ICMP_PARAMETERPROB:
769 err = EPROTO;
770 harderr = 1;
771 break;
772 case ICMP_DEST_UNREACH:
773 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
774 ipv4_sk_update_pmtu(skb, sk, info);
775 if (inet->pmtudisc != IP_PMTUDISC_DONT) {
776 err = EMSGSIZE;
777 harderr = 1;
778 break;
779 }
780 goto out;
781 }
782 err = EHOSTUNREACH;
783 if (code <= NR_ICMP_UNREACH) {
784 harderr = icmp_err_convert[code].fatal;
785 err = icmp_err_convert[code].errno;
786 }
787 break;
788 case ICMP_REDIRECT:
789 ipv4_sk_redirect(skb, sk);
790 goto out;
791 }
792
793 /*
794 * RFC1122: OK. Passes ICMP errors back to application, as per
795 * 4.1.3.3.
796 */
797 if (tunnel) {
798 /* ...not for tunnels though: we don't have a sending socket */
799 if (udp_sk(sk)->encap_err_rcv)
800 udp_sk(sk)->encap_err_rcv(sk, skb, err, uh->dest, info,
801 (u8 *)(uh+1));
802 goto out;
803 }
804 if (!inet_test_bit(RECVERR, sk)) {
805 if (!harderr || sk->sk_state != TCP_ESTABLISHED)
806 goto out;
807 } else
808 ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
809
810 sk->sk_err = err;
811 sk_error_report(sk);
812 out:
813 return 0;
814 }
815
udp_err(struct sk_buff * skb,u32 info)816 int udp_err(struct sk_buff *skb, u32 info)
817 {
818 return __udp4_lib_err(skb, info, dev_net(skb->dev)->ipv4.udp_table);
819 }
820
821 /*
822 * Throw away all pending data and cancel the corking. Socket is locked.
823 */
udp_flush_pending_frames(struct sock * sk)824 void udp_flush_pending_frames(struct sock *sk)
825 {
826 struct udp_sock *up = udp_sk(sk);
827
828 if (up->pending) {
829 up->len = 0;
830 WRITE_ONCE(up->pending, 0);
831 ip_flush_pending_frames(sk);
832 }
833 }
834 EXPORT_SYMBOL(udp_flush_pending_frames);
835
836 /**
837 * udp4_hwcsum - handle outgoing HW checksumming
838 * @skb: sk_buff containing the filled-in UDP header
839 * (checksum field must be zeroed out)
840 * @src: source IP address
841 * @dst: destination IP address
842 */
udp4_hwcsum(struct sk_buff * skb,__be32 src,__be32 dst)843 void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
844 {
845 struct udphdr *uh = udp_hdr(skb);
846 int offset = skb_transport_offset(skb);
847 int len = skb->len - offset;
848 int hlen = len;
849 __wsum csum = 0;
850
851 if (!skb_has_frag_list(skb)) {
852 /*
853 * Only one fragment on the socket.
854 */
855 skb->csum_start = skb_transport_header(skb) - skb->head;
856 skb->csum_offset = offsetof(struct udphdr, check);
857 uh->check = ~csum_tcpudp_magic(src, dst, len,
858 IPPROTO_UDP, 0);
859 } else {
860 struct sk_buff *frags;
861
862 /*
863 * HW-checksum won't work as there are two or more
864 * fragments on the socket so that all csums of sk_buffs
865 * should be together
866 */
867 skb_walk_frags(skb, frags) {
868 csum = csum_add(csum, frags->csum);
869 hlen -= frags->len;
870 }
871
872 csum = skb_checksum(skb, offset, hlen, csum);
873 skb->ip_summed = CHECKSUM_NONE;
874
875 uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
876 if (uh->check == 0)
877 uh->check = CSUM_MANGLED_0;
878 }
879 }
880 EXPORT_SYMBOL_GPL(udp4_hwcsum);
881
882 /* Function to set UDP checksum for an IPv4 UDP packet. This is intended
883 * for the simple case like when setting the checksum for a UDP tunnel.
884 */
udp_set_csum(bool nocheck,struct sk_buff * skb,__be32 saddr,__be32 daddr,int len)885 void udp_set_csum(bool nocheck, struct sk_buff *skb,
886 __be32 saddr, __be32 daddr, int len)
887 {
888 struct udphdr *uh = udp_hdr(skb);
889
890 if (nocheck) {
891 uh->check = 0;
892 } else if (skb_is_gso(skb)) {
893 uh->check = ~udp_v4_check(len, saddr, daddr, 0);
894 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
895 uh->check = 0;
896 uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb));
897 if (uh->check == 0)
898 uh->check = CSUM_MANGLED_0;
899 } else {
900 skb->ip_summed = CHECKSUM_PARTIAL;
901 skb->csum_start = skb_transport_header(skb) - skb->head;
902 skb->csum_offset = offsetof(struct udphdr, check);
903 uh->check = ~udp_v4_check(len, saddr, daddr, 0);
904 }
905 }
906 EXPORT_SYMBOL(udp_set_csum);
907
udp_send_skb(struct sk_buff * skb,struct flowi4 * fl4,struct inet_cork * cork)908 static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4,
909 struct inet_cork *cork)
910 {
911 struct sock *sk = skb->sk;
912 struct inet_sock *inet = inet_sk(sk);
913 struct udphdr *uh;
914 int err;
915 int is_udplite = IS_UDPLITE(sk);
916 int offset = skb_transport_offset(skb);
917 int len = skb->len - offset;
918 int datalen = len - sizeof(*uh);
919 __wsum csum = 0;
920
921 /*
922 * Create a UDP header
923 */
924 uh = udp_hdr(skb);
925 uh->source = inet->inet_sport;
926 uh->dest = fl4->fl4_dport;
927 uh->len = htons(len);
928 uh->check = 0;
929
930 if (cork->gso_size) {
931 const int hlen = skb_network_header_len(skb) +
932 sizeof(struct udphdr);
933
934 if (hlen + cork->gso_size > cork->fragsize) {
935 kfree_skb(skb);
936 return -EINVAL;
937 }
938 if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) {
939 kfree_skb(skb);
940 return -EINVAL;
941 }
942 if (sk->sk_no_check_tx) {
943 kfree_skb(skb);
944 return -EINVAL;
945 }
946 if (skb->ip_summed != CHECKSUM_PARTIAL || is_udplite ||
947 dst_xfrm(skb_dst(skb))) {
948 kfree_skb(skb);
949 return -EIO;
950 }
951
952 if (datalen > cork->gso_size) {
953 skb_shinfo(skb)->gso_size = cork->gso_size;
954 skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4;
955 skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen,
956 cork->gso_size);
957 }
958 goto csum_partial;
959 }
960
961 if (is_udplite) /* UDP-Lite */
962 csum = udplite_csum(skb);
963
964 else if (sk->sk_no_check_tx) { /* UDP csum off */
965
966 skb->ip_summed = CHECKSUM_NONE;
967 goto send;
968
969 } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
970 csum_partial:
971
972 udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
973 goto send;
974
975 } else
976 csum = udp_csum(skb);
977
978 /* add protocol-dependent pseudo-header */
979 uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
980 sk->sk_protocol, csum);
981 if (uh->check == 0)
982 uh->check = CSUM_MANGLED_0;
983
984 send:
985 err = ip_send_skb(sock_net(sk), skb);
986 if (err) {
987 if (err == -ENOBUFS &&
988 !inet_test_bit(RECVERR, sk)) {
989 UDP_INC_STATS(sock_net(sk),
990 UDP_MIB_SNDBUFERRORS, is_udplite);
991 err = 0;
992 }
993 } else
994 UDP_INC_STATS(sock_net(sk),
995 UDP_MIB_OUTDATAGRAMS, is_udplite);
996 return err;
997 }
998
999 /*
1000 * Push out all pending data as one UDP datagram. Socket is locked.
1001 */
udp_push_pending_frames(struct sock * sk)1002 int udp_push_pending_frames(struct sock *sk)
1003 {
1004 struct udp_sock *up = udp_sk(sk);
1005 struct inet_sock *inet = inet_sk(sk);
1006 struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
1007 struct sk_buff *skb;
1008 int err = 0;
1009
1010 skb = ip_finish_skb(sk, fl4);
1011 if (!skb)
1012 goto out;
1013
1014 err = udp_send_skb(skb, fl4, &inet->cork.base);
1015
1016 out:
1017 up->len = 0;
1018 WRITE_ONCE(up->pending, 0);
1019 return err;
1020 }
1021 EXPORT_SYMBOL(udp_push_pending_frames);
1022
__udp_cmsg_send(struct cmsghdr * cmsg,u16 * gso_size)1023 static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size)
1024 {
1025 switch (cmsg->cmsg_type) {
1026 case UDP_SEGMENT:
1027 if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16)))
1028 return -EINVAL;
1029 *gso_size = *(__u16 *)CMSG_DATA(cmsg);
1030 return 0;
1031 default:
1032 return -EINVAL;
1033 }
1034 }
1035
udp_cmsg_send(struct sock * sk,struct msghdr * msg,u16 * gso_size)1036 int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size)
1037 {
1038 struct cmsghdr *cmsg;
1039 bool need_ip = false;
1040 int err;
1041
1042 for_each_cmsghdr(cmsg, msg) {
1043 if (!CMSG_OK(msg, cmsg))
1044 return -EINVAL;
1045
1046 if (cmsg->cmsg_level != SOL_UDP) {
1047 need_ip = true;
1048 continue;
1049 }
1050
1051 err = __udp_cmsg_send(cmsg, gso_size);
1052 if (err)
1053 return err;
1054 }
1055
1056 return need_ip;
1057 }
1058 EXPORT_SYMBOL_GPL(udp_cmsg_send);
1059
udp_sendmsg(struct sock * sk,struct msghdr * msg,size_t len)1060 int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
1061 {
1062 struct inet_sock *inet = inet_sk(sk);
1063 struct udp_sock *up = udp_sk(sk);
1064 DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
1065 struct flowi4 fl4_stack;
1066 struct flowi4 *fl4;
1067 int ulen = len;
1068 struct ipcm_cookie ipc;
1069 struct rtable *rt = NULL;
1070 int free = 0;
1071 int connected = 0;
1072 __be32 daddr, faddr, saddr;
1073 u8 tos, scope;
1074 __be16 dport;
1075 int err, is_udplite = IS_UDPLITE(sk);
1076 int corkreq = udp_test_bit(CORK, sk) || msg->msg_flags & MSG_MORE;
1077 int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
1078 struct sk_buff *skb;
1079 struct ip_options_data opt_copy;
1080
1081 trace_android_rvh_udp_sendmsg(sk, msg, len);
1082
1083 if (len > 0xFFFF)
1084 return -EMSGSIZE;
1085
1086 /*
1087 * Check the flags.
1088 */
1089
1090 if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
1091 return -EOPNOTSUPP;
1092
1093 trace_android_vh_uplink_send_msg(sk);
1094
1095 getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
1096
1097 fl4 = &inet->cork.fl.u.ip4;
1098 if (READ_ONCE(up->pending)) {
1099 /*
1100 * There are pending frames.
1101 * The socket lock must be held while it's corked.
1102 */
1103 lock_sock(sk);
1104 if (likely(up->pending)) {
1105 if (unlikely(up->pending != AF_INET)) {
1106 release_sock(sk);
1107 return -EINVAL;
1108 }
1109 goto do_append_data;
1110 }
1111 release_sock(sk);
1112 }
1113 ulen += sizeof(struct udphdr);
1114
1115 /*
1116 * Get and verify the address.
1117 */
1118 if (usin) {
1119 if (msg->msg_namelen < sizeof(*usin))
1120 return -EINVAL;
1121 if (usin->sin_family != AF_INET) {
1122 if (usin->sin_family != AF_UNSPEC)
1123 return -EAFNOSUPPORT;
1124 }
1125
1126 daddr = usin->sin_addr.s_addr;
1127 dport = usin->sin_port;
1128 if (dport == 0)
1129 return -EINVAL;
1130 } else {
1131 if (sk->sk_state != TCP_ESTABLISHED)
1132 return -EDESTADDRREQ;
1133 daddr = inet->inet_daddr;
1134 dport = inet->inet_dport;
1135 /* Open fast path for connected socket.
1136 Route will not be used, if at least one option is set.
1137 */
1138 connected = 1;
1139 }
1140
1141 trace_android_vh_udp_v4_connect(sk, daddr, dport, AF_INET);
1142
1143 ipcm_init_sk(&ipc, inet);
1144 ipc.gso_size = READ_ONCE(up->gso_size);
1145
1146 if (msg->msg_controllen) {
1147 err = udp_cmsg_send(sk, msg, &ipc.gso_size);
1148 if (err > 0) {
1149 err = ip_cmsg_send(sk, msg, &ipc,
1150 sk->sk_family == AF_INET6);
1151 connected = 0;
1152 }
1153 if (unlikely(err < 0)) {
1154 kfree(ipc.opt);
1155 return err;
1156 }
1157 if (ipc.opt)
1158 free = 1;
1159 }
1160 if (!ipc.opt) {
1161 struct ip_options_rcu *inet_opt;
1162
1163 rcu_read_lock();
1164 inet_opt = rcu_dereference(inet->inet_opt);
1165 if (inet_opt) {
1166 memcpy(&opt_copy, inet_opt,
1167 sizeof(*inet_opt) + inet_opt->opt.optlen);
1168 ipc.opt = &opt_copy.opt;
1169 }
1170 rcu_read_unlock();
1171 }
1172
1173 if (cgroup_bpf_enabled(CGROUP_UDP4_SENDMSG) && !connected) {
1174 err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk,
1175 (struct sockaddr *)usin,
1176 &msg->msg_namelen,
1177 &ipc.addr);
1178 if (err)
1179 goto out_free;
1180 if (usin) {
1181 if (usin->sin_port == 0) {
1182 /* BPF program set invalid port. Reject it. */
1183 err = -EINVAL;
1184 goto out_free;
1185 }
1186 daddr = usin->sin_addr.s_addr;
1187 dport = usin->sin_port;
1188 }
1189 }
1190
1191 saddr = ipc.addr;
1192 ipc.addr = faddr = daddr;
1193
1194 if (ipc.opt && ipc.opt->opt.srr) {
1195 if (!daddr) {
1196 err = -EINVAL;
1197 goto out_free;
1198 }
1199 faddr = ipc.opt->opt.faddr;
1200 connected = 0;
1201 }
1202 tos = get_rttos(&ipc, inet);
1203 scope = ip_sendmsg_scope(inet, &ipc, msg);
1204 if (scope == RT_SCOPE_LINK)
1205 connected = 0;
1206
1207 if (ipv4_is_multicast(daddr)) {
1208 if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
1209 ipc.oif = inet->mc_index;
1210 if (!saddr)
1211 saddr = inet->mc_addr;
1212 connected = 0;
1213 } else if (!ipc.oif) {
1214 ipc.oif = inet->uc_index;
1215 } else if (ipv4_is_lbcast(daddr) && inet->uc_index) {
1216 /* oif is set, packet is to local broadcast and
1217 * uc_index is set. oif is most likely set
1218 * by sk_bound_dev_if. If uc_index != oif check if the
1219 * oif is an L3 master and uc_index is an L3 slave.
1220 * If so, we want to allow the send using the uc_index.
1221 */
1222 if (ipc.oif != inet->uc_index &&
1223 ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk),
1224 inet->uc_index)) {
1225 ipc.oif = inet->uc_index;
1226 }
1227 }
1228
1229 if (connected)
1230 rt = (struct rtable *)sk_dst_check(sk, 0);
1231
1232 if (!rt) {
1233 struct net *net = sock_net(sk);
1234 __u8 flow_flags = inet_sk_flowi_flags(sk);
1235
1236 fl4 = &fl4_stack;
1237
1238 flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, tos, scope,
1239 sk->sk_protocol, flow_flags, faddr, saddr,
1240 dport, inet->inet_sport, sk->sk_uid);
1241
1242 security_sk_classify_flow(sk, flowi4_to_flowi_common(fl4));
1243 rt = ip_route_output_flow(net, fl4, sk);
1244 if (IS_ERR(rt)) {
1245 err = PTR_ERR(rt);
1246 rt = NULL;
1247 if (err == -ENETUNREACH)
1248 IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
1249 goto out;
1250 }
1251
1252 err = -EACCES;
1253 if ((rt->rt_flags & RTCF_BROADCAST) &&
1254 !sock_flag(sk, SOCK_BROADCAST))
1255 goto out;
1256 if (connected)
1257 sk_dst_set(sk, dst_clone(&rt->dst));
1258 }
1259
1260 if (msg->msg_flags&MSG_CONFIRM)
1261 goto do_confirm;
1262 back_from_confirm:
1263
1264 saddr = fl4->saddr;
1265 if (!ipc.addr)
1266 daddr = ipc.addr = fl4->daddr;
1267
1268 /* Lockless fast path for the non-corking case. */
1269 if (!corkreq) {
1270 struct inet_cork cork;
1271
1272 skb = ip_make_skb(sk, fl4, getfrag, msg, ulen,
1273 sizeof(struct udphdr), &ipc, &rt,
1274 &cork, msg->msg_flags);
1275 err = PTR_ERR(skb);
1276 if (!IS_ERR_OR_NULL(skb))
1277 err = udp_send_skb(skb, fl4, &cork);
1278 goto out;
1279 }
1280
1281 lock_sock(sk);
1282 if (unlikely(up->pending)) {
1283 /* The socket is already corked while preparing it. */
1284 /* ... which is an evident application bug. --ANK */
1285 release_sock(sk);
1286
1287 net_dbg_ratelimited("socket already corked\n");
1288 err = -EINVAL;
1289 goto out;
1290 }
1291 /*
1292 * Now cork the socket to pend data.
1293 */
1294 fl4 = &inet->cork.fl.u.ip4;
1295 fl4->daddr = daddr;
1296 fl4->saddr = saddr;
1297 fl4->fl4_dport = dport;
1298 fl4->fl4_sport = inet->inet_sport;
1299 WRITE_ONCE(up->pending, AF_INET);
1300
1301 do_append_data:
1302 up->len += ulen;
1303 err = ip_append_data(sk, fl4, getfrag, msg, ulen,
1304 sizeof(struct udphdr), &ipc, &rt,
1305 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
1306 if (err)
1307 udp_flush_pending_frames(sk);
1308 else if (!corkreq)
1309 err = udp_push_pending_frames(sk);
1310 else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
1311 WRITE_ONCE(up->pending, 0);
1312 release_sock(sk);
1313
1314 out:
1315 ip_rt_put(rt);
1316 out_free:
1317 if (free)
1318 kfree(ipc.opt);
1319 if (!err)
1320 return len;
1321 /*
1322 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
1323 * ENOBUFS might not be good (it's not tunable per se), but otherwise
1324 * we don't have a good statistic (IpOutDiscards but it can be too many
1325 * things). We could add another new stat but at least for now that
1326 * seems like overkill.
1327 */
1328 if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
1329 UDP_INC_STATS(sock_net(sk),
1330 UDP_MIB_SNDBUFERRORS, is_udplite);
1331 }
1332 return err;
1333
1334 do_confirm:
1335 if (msg->msg_flags & MSG_PROBE)
1336 dst_confirm_neigh(&rt->dst, &fl4->daddr);
1337 if (!(msg->msg_flags&MSG_PROBE) || len)
1338 goto back_from_confirm;
1339 err = 0;
1340 goto out;
1341 }
1342 EXPORT_SYMBOL(udp_sendmsg);
1343
udp_splice_eof(struct socket * sock)1344 void udp_splice_eof(struct socket *sock)
1345 {
1346 struct sock *sk = sock->sk;
1347 struct udp_sock *up = udp_sk(sk);
1348
1349 if (!READ_ONCE(up->pending) || udp_test_bit(CORK, sk))
1350 return;
1351
1352 lock_sock(sk);
1353 if (up->pending && !udp_test_bit(CORK, sk))
1354 udp_push_pending_frames(sk);
1355 release_sock(sk);
1356 }
1357 EXPORT_SYMBOL_GPL(udp_splice_eof);
1358
1359 #define UDP_SKB_IS_STATELESS 0x80000000
1360
1361 /* all head states (dst, sk, nf conntrack) except skb extensions are
1362 * cleared by udp_rcv().
1363 *
1364 * We need to preserve secpath, if present, to eventually process
1365 * IP_CMSG_PASSSEC at recvmsg() time.
1366 *
1367 * Other extensions can be cleared.
1368 */
udp_try_make_stateless(struct sk_buff * skb)1369 static bool udp_try_make_stateless(struct sk_buff *skb)
1370 {
1371 if (!skb_has_extensions(skb))
1372 return true;
1373
1374 if (!secpath_exists(skb)) {
1375 skb_ext_reset(skb);
1376 return true;
1377 }
1378
1379 return false;
1380 }
1381
udp_set_dev_scratch(struct sk_buff * skb)1382 static void udp_set_dev_scratch(struct sk_buff *skb)
1383 {
1384 struct udp_dev_scratch *scratch = udp_skb_scratch(skb);
1385
1386 BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long));
1387 scratch->_tsize_state = skb->truesize;
1388 #if BITS_PER_LONG == 64
1389 scratch->len = skb->len;
1390 scratch->csum_unnecessary = !!skb_csum_unnecessary(skb);
1391 scratch->is_linear = !skb_is_nonlinear(skb);
1392 #endif
1393 if (udp_try_make_stateless(skb))
1394 scratch->_tsize_state |= UDP_SKB_IS_STATELESS;
1395 }
1396
udp_skb_csum_unnecessary_set(struct sk_buff * skb)1397 static void udp_skb_csum_unnecessary_set(struct sk_buff *skb)
1398 {
1399 /* We come here after udp_lib_checksum_complete() returned 0.
1400 * This means that __skb_checksum_complete() might have
1401 * set skb->csum_valid to 1.
1402 * On 64bit platforms, we can set csum_unnecessary
1403 * to true, but only if the skb is not shared.
1404 */
1405 #if BITS_PER_LONG == 64
1406 if (!skb_shared(skb))
1407 udp_skb_scratch(skb)->csum_unnecessary = true;
1408 #endif
1409 }
1410
udp_skb_truesize(struct sk_buff * skb)1411 static int udp_skb_truesize(struct sk_buff *skb)
1412 {
1413 return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS;
1414 }
1415
udp_skb_has_head_state(struct sk_buff * skb)1416 static bool udp_skb_has_head_state(struct sk_buff *skb)
1417 {
1418 return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS);
1419 }
1420
1421 /* fully reclaim rmem/fwd memory allocated for skb */
udp_rmem_release(struct sock * sk,int size,int partial,bool rx_queue_lock_held)1422 static void udp_rmem_release(struct sock *sk, int size, int partial,
1423 bool rx_queue_lock_held)
1424 {
1425 struct udp_sock *up = udp_sk(sk);
1426 struct sk_buff_head *sk_queue;
1427 int amt;
1428
1429 if (likely(partial)) {
1430 up->forward_deficit += size;
1431 size = up->forward_deficit;
1432 if (size < READ_ONCE(up->forward_threshold) &&
1433 !skb_queue_empty(&up->reader_queue))
1434 return;
1435 } else {
1436 size += up->forward_deficit;
1437 }
1438 up->forward_deficit = 0;
1439
1440 /* acquire the sk_receive_queue for fwd allocated memory scheduling,
1441 * if the called don't held it already
1442 */
1443 sk_queue = &sk->sk_receive_queue;
1444 if (!rx_queue_lock_held)
1445 spin_lock(&sk_queue->lock);
1446
1447
1448 sk_forward_alloc_add(sk, size);
1449 amt = (sk->sk_forward_alloc - partial) & ~(PAGE_SIZE - 1);
1450 sk_forward_alloc_add(sk, -amt);
1451
1452 if (amt)
1453 __sk_mem_reduce_allocated(sk, amt >> PAGE_SHIFT);
1454
1455 atomic_sub(size, &sk->sk_rmem_alloc);
1456
1457 /* this can save us from acquiring the rx queue lock on next receive */
1458 skb_queue_splice_tail_init(sk_queue, &up->reader_queue);
1459
1460 if (!rx_queue_lock_held)
1461 spin_unlock(&sk_queue->lock);
1462 }
1463
1464 /* Note: called with reader_queue.lock held.
1465 * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch
1466 * This avoids a cache line miss while receive_queue lock is held.
1467 * Look at __udp_enqueue_schedule_skb() to find where this copy is done.
1468 */
udp_skb_destructor(struct sock * sk,struct sk_buff * skb)1469 void udp_skb_destructor(struct sock *sk, struct sk_buff *skb)
1470 {
1471 prefetch(&skb->data);
1472 udp_rmem_release(sk, udp_skb_truesize(skb), 1, false);
1473 }
1474 EXPORT_SYMBOL(udp_skb_destructor);
1475
1476 /* as above, but the caller held the rx queue lock, too */
udp_skb_dtor_locked(struct sock * sk,struct sk_buff * skb)1477 static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb)
1478 {
1479 prefetch(&skb->data);
1480 udp_rmem_release(sk, udp_skb_truesize(skb), 1, true);
1481 }
1482
1483 /* Idea of busylocks is to let producers grab an extra spinlock
1484 * to relieve pressure on the receive_queue spinlock shared by consumer.
1485 * Under flood, this means that only one producer can be in line
1486 * trying to acquire the receive_queue spinlock.
1487 * These busylock can be allocated on a per cpu manner, instead of a
1488 * per socket one (that would consume a cache line per socket)
1489 */
1490 static int udp_busylocks_log __read_mostly;
1491 static spinlock_t *udp_busylocks __read_mostly;
1492
busylock_acquire(void * ptr)1493 static spinlock_t *busylock_acquire(void *ptr)
1494 {
1495 spinlock_t *busy;
1496
1497 busy = udp_busylocks + hash_ptr(ptr, udp_busylocks_log);
1498 spin_lock(busy);
1499 return busy;
1500 }
1501
busylock_release(spinlock_t * busy)1502 static void busylock_release(spinlock_t *busy)
1503 {
1504 if (busy)
1505 spin_unlock(busy);
1506 }
1507
udp_rmem_schedule(struct sock * sk,int size)1508 static int udp_rmem_schedule(struct sock *sk, int size)
1509 {
1510 int delta;
1511
1512 delta = size - sk->sk_forward_alloc;
1513 if (delta > 0 && !__sk_mem_schedule(sk, delta, SK_MEM_RECV))
1514 return -ENOBUFS;
1515
1516 return 0;
1517 }
1518
__udp_enqueue_schedule_skb(struct sock * sk,struct sk_buff * skb)1519 int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb)
1520 {
1521 struct sk_buff_head *list = &sk->sk_receive_queue;
1522 int rmem, err = -ENOMEM;
1523 spinlock_t *busy = NULL;
1524 int size;
1525
1526 trace_android_vh_udp_enqueue_schedule_skb(sk, skb);
1527
1528 /* try to avoid the costly atomic add/sub pair when the receive
1529 * queue is full; always allow at least a packet
1530 */
1531 rmem = atomic_read(&sk->sk_rmem_alloc);
1532 if (rmem > sk->sk_rcvbuf)
1533 goto drop;
1534
1535 /* Under mem pressure, it might be helpful to help udp_recvmsg()
1536 * having linear skbs :
1537 * - Reduce memory overhead and thus increase receive queue capacity
1538 * - Less cache line misses at copyout() time
1539 * - Less work at consume_skb() (less alien page frag freeing)
1540 */
1541 if (rmem > (sk->sk_rcvbuf >> 1)) {
1542 skb_condense(skb);
1543
1544 busy = busylock_acquire(sk);
1545 }
1546 size = skb->truesize;
1547 udp_set_dev_scratch(skb);
1548
1549 /* we drop only if the receive buf is full and the receive
1550 * queue contains some other skb
1551 */
1552 rmem = atomic_add_return(size, &sk->sk_rmem_alloc);
1553 if (rmem > (size + (unsigned int)sk->sk_rcvbuf))
1554 goto uncharge_drop;
1555
1556 spin_lock(&list->lock);
1557 err = udp_rmem_schedule(sk, size);
1558 if (err) {
1559 spin_unlock(&list->lock);
1560 goto uncharge_drop;
1561 }
1562
1563 sk_forward_alloc_add(sk, -size);
1564
1565 /* no need to setup a destructor, we will explicitly release the
1566 * forward allocated memory on dequeue
1567 */
1568 sock_skb_set_dropcount(sk, skb);
1569
1570 __skb_queue_tail(list, skb);
1571 spin_unlock(&list->lock);
1572
1573 if (!sock_flag(sk, SOCK_DEAD))
1574 INDIRECT_CALL_1(sk->sk_data_ready, sock_def_readable, sk);
1575
1576 busylock_release(busy);
1577 return 0;
1578
1579 uncharge_drop:
1580 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1581
1582 drop:
1583 atomic_inc(&sk->sk_drops);
1584 busylock_release(busy);
1585 return err;
1586 }
1587 EXPORT_SYMBOL_GPL(__udp_enqueue_schedule_skb);
1588
udp_destruct_common(struct sock * sk)1589 void udp_destruct_common(struct sock *sk)
1590 {
1591 /* reclaim completely the forward allocated memory */
1592 struct udp_sock *up = udp_sk(sk);
1593 unsigned int total = 0;
1594 struct sk_buff *skb;
1595
1596 skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue);
1597 while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) {
1598 total += skb->truesize;
1599 kfree_skb(skb);
1600 }
1601 udp_rmem_release(sk, total, 0, true);
1602 }
1603 EXPORT_SYMBOL_GPL(udp_destruct_common);
1604
udp_destruct_sock(struct sock * sk)1605 static void udp_destruct_sock(struct sock *sk)
1606 {
1607 udp_destruct_common(sk);
1608 inet_sock_destruct(sk);
1609 }
1610
udp_init_sock(struct sock * sk)1611 int udp_init_sock(struct sock *sk)
1612 {
1613 udp_lib_init_sock(sk);
1614 sk->sk_destruct = udp_destruct_sock;
1615 set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags);
1616 return 0;
1617 }
1618
skb_consume_udp(struct sock * sk,struct sk_buff * skb,int len)1619 void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len)
1620 {
1621 if (unlikely(READ_ONCE(sk->sk_peek_off) >= 0)) {
1622 bool slow = lock_sock_fast(sk);
1623
1624 sk_peek_offset_bwd(sk, len);
1625 unlock_sock_fast(sk, slow);
1626 }
1627
1628 if (!skb_unref(skb))
1629 return;
1630
1631 /* In the more common cases we cleared the head states previously,
1632 * see __udp_queue_rcv_skb().
1633 */
1634 if (unlikely(udp_skb_has_head_state(skb)))
1635 skb_release_head_state(skb);
1636 __consume_stateless_skb(skb);
1637 }
1638 EXPORT_SYMBOL_GPL(skb_consume_udp);
1639
__first_packet_length(struct sock * sk,struct sk_buff_head * rcvq,int * total)1640 static struct sk_buff *__first_packet_length(struct sock *sk,
1641 struct sk_buff_head *rcvq,
1642 int *total)
1643 {
1644 struct sk_buff *skb;
1645
1646 while ((skb = skb_peek(rcvq)) != NULL) {
1647 if (udp_lib_checksum_complete(skb)) {
1648 __UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS,
1649 IS_UDPLITE(sk));
1650 __UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS,
1651 IS_UDPLITE(sk));
1652 atomic_inc(&sk->sk_drops);
1653 __skb_unlink(skb, rcvq);
1654 *total += skb->truesize;
1655 kfree_skb(skb);
1656 } else {
1657 udp_skb_csum_unnecessary_set(skb);
1658 break;
1659 }
1660 }
1661 return skb;
1662 }
1663
1664 /**
1665 * first_packet_length - return length of first packet in receive queue
1666 * @sk: socket
1667 *
1668 * Drops all bad checksum frames, until a valid one is found.
1669 * Returns the length of found skb, or -1 if none is found.
1670 */
first_packet_length(struct sock * sk)1671 static int first_packet_length(struct sock *sk)
1672 {
1673 struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue;
1674 struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
1675 struct sk_buff *skb;
1676 int total = 0;
1677 int res;
1678
1679 spin_lock_bh(&rcvq->lock);
1680 skb = __first_packet_length(sk, rcvq, &total);
1681 if (!skb && !skb_queue_empty_lockless(sk_queue)) {
1682 spin_lock(&sk_queue->lock);
1683 skb_queue_splice_tail_init(sk_queue, rcvq);
1684 spin_unlock(&sk_queue->lock);
1685
1686 skb = __first_packet_length(sk, rcvq, &total);
1687 }
1688 res = skb ? skb->len : -1;
1689 if (total)
1690 udp_rmem_release(sk, total, 1, false);
1691 spin_unlock_bh(&rcvq->lock);
1692 return res;
1693 }
1694
1695 /*
1696 * IOCTL requests applicable to the UDP protocol
1697 */
1698
udp_ioctl(struct sock * sk,int cmd,int * karg)1699 int udp_ioctl(struct sock *sk, int cmd, int *karg)
1700 {
1701 switch (cmd) {
1702 case SIOCOUTQ:
1703 {
1704 *karg = sk_wmem_alloc_get(sk);
1705 return 0;
1706 }
1707
1708 case SIOCINQ:
1709 {
1710 *karg = max_t(int, 0, first_packet_length(sk));
1711 return 0;
1712 }
1713
1714 default:
1715 return -ENOIOCTLCMD;
1716 }
1717
1718 return 0;
1719 }
1720 EXPORT_SYMBOL(udp_ioctl);
1721
__skb_recv_udp(struct sock * sk,unsigned int flags,int * off,int * err)1722 struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags,
1723 int *off, int *err)
1724 {
1725 struct sk_buff_head *sk_queue = &sk->sk_receive_queue;
1726 struct sk_buff_head *queue;
1727 struct sk_buff *last;
1728 long timeo;
1729 int error;
1730
1731 queue = &udp_sk(sk)->reader_queue;
1732 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1733 do {
1734 struct sk_buff *skb;
1735
1736 error = sock_error(sk);
1737 if (error)
1738 break;
1739
1740 error = -EAGAIN;
1741 do {
1742 spin_lock_bh(&queue->lock);
1743 skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1744 err, &last);
1745 if (skb) {
1746 if (!(flags & MSG_PEEK))
1747 udp_skb_destructor(sk, skb);
1748 spin_unlock_bh(&queue->lock);
1749 return skb;
1750 }
1751
1752 if (skb_queue_empty_lockless(sk_queue)) {
1753 spin_unlock_bh(&queue->lock);
1754 goto busy_check;
1755 }
1756
1757 /* refill the reader queue and walk it again
1758 * keep both queues locked to avoid re-acquiring
1759 * the sk_receive_queue lock if fwd memory scheduling
1760 * is needed.
1761 */
1762 spin_lock(&sk_queue->lock);
1763 skb_queue_splice_tail_init(sk_queue, queue);
1764
1765 skb = __skb_try_recv_from_queue(sk, queue, flags, off,
1766 err, &last);
1767 if (skb && !(flags & MSG_PEEK))
1768 udp_skb_dtor_locked(sk, skb);
1769 spin_unlock(&sk_queue->lock);
1770 spin_unlock_bh(&queue->lock);
1771 if (skb)
1772 return skb;
1773
1774 busy_check:
1775 if (!sk_can_busy_loop(sk))
1776 break;
1777
1778 sk_busy_loop(sk, flags & MSG_DONTWAIT);
1779 } while (!skb_queue_empty_lockless(sk_queue));
1780
1781 /* sk_queue is empty, reader_queue may contain peeked packets */
1782 } while (timeo &&
1783 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
1784 &error, &timeo,
1785 (struct sk_buff *)sk_queue));
1786
1787 *err = error;
1788 return NULL;
1789 }
1790 EXPORT_SYMBOL(__skb_recv_udp);
1791
udp_read_skb(struct sock * sk,skb_read_actor_t recv_actor)1792 int udp_read_skb(struct sock *sk, skb_read_actor_t recv_actor)
1793 {
1794 struct sk_buff *skb;
1795 int err;
1796
1797 try_again:
1798 skb = skb_recv_udp(sk, MSG_DONTWAIT, &err);
1799 if (!skb)
1800 return err;
1801
1802 if (udp_lib_checksum_complete(skb)) {
1803 int is_udplite = IS_UDPLITE(sk);
1804 struct net *net = sock_net(sk);
1805
1806 __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, is_udplite);
1807 __UDP_INC_STATS(net, UDP_MIB_INERRORS, is_udplite);
1808 atomic_inc(&sk->sk_drops);
1809 kfree_skb(skb);
1810 goto try_again;
1811 }
1812
1813 WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk));
1814 return recv_actor(sk, skb);
1815 }
1816 EXPORT_SYMBOL(udp_read_skb);
1817
1818 /*
1819 * This should be easy, if there is something there we
1820 * return it, otherwise we block.
1821 */
1822
udp_recvmsg(struct sock * sk,struct msghdr * msg,size_t len,int flags,int * addr_len)1823 int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags,
1824 int *addr_len)
1825 {
1826 struct inet_sock *inet = inet_sk(sk);
1827 DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
1828 struct sk_buff *skb;
1829 unsigned int ulen, copied;
1830 int off, err, peeking = flags & MSG_PEEK;
1831 int is_udplite = IS_UDPLITE(sk);
1832 bool checksum_valid = false;
1833
1834 if (flags & MSG_ERRQUEUE)
1835 return ip_recv_error(sk, msg, len, addr_len);
1836
1837 try_again:
1838 off = sk_peek_offset(sk, flags);
1839 skb = __skb_recv_udp(sk, flags, &off, &err);
1840 if (!skb)
1841 return err;
1842
1843 ulen = udp_skb_len(skb);
1844 copied = len;
1845 if (copied > ulen - off)
1846 copied = ulen - off;
1847 else if (copied < ulen)
1848 msg->msg_flags |= MSG_TRUNC;
1849
1850 /*
1851 * If checksum is needed at all, try to do it while copying the
1852 * data. If the data is truncated, or if we only want a partial
1853 * coverage checksum (UDP-Lite), do it before the copy.
1854 */
1855
1856 if (copied < ulen || peeking ||
1857 (is_udplite && UDP_SKB_CB(skb)->partial_cov)) {
1858 checksum_valid = udp_skb_csum_unnecessary(skb) ||
1859 !__udp_lib_checksum_complete(skb);
1860 if (!checksum_valid)
1861 goto csum_copy_err;
1862 }
1863
1864 if (checksum_valid || udp_skb_csum_unnecessary(skb)) {
1865 if (udp_skb_is_linear(skb))
1866 err = copy_linear_skb(skb, copied, off, &msg->msg_iter);
1867 else
1868 err = skb_copy_datagram_msg(skb, off, msg, copied);
1869 } else {
1870 err = skb_copy_and_csum_datagram_msg(skb, off, msg);
1871
1872 if (err == -EINVAL)
1873 goto csum_copy_err;
1874 }
1875
1876 if (unlikely(err)) {
1877 if (!peeking) {
1878 atomic_inc(&sk->sk_drops);
1879 UDP_INC_STATS(sock_net(sk),
1880 UDP_MIB_INERRORS, is_udplite);
1881 }
1882 kfree_skb(skb);
1883 return err;
1884 }
1885
1886 if (!peeking)
1887 UDP_INC_STATS(sock_net(sk),
1888 UDP_MIB_INDATAGRAMS, is_udplite);
1889
1890 sock_recv_cmsgs(msg, sk, skb);
1891
1892 /* Copy the address. */
1893 if (sin) {
1894 sin->sin_family = AF_INET;
1895 sin->sin_port = udp_hdr(skb)->source;
1896 sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
1897 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
1898 *addr_len = sizeof(*sin);
1899
1900 BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk,
1901 (struct sockaddr *)sin,
1902 addr_len);
1903 }
1904
1905 if (udp_test_bit(GRO_ENABLED, sk))
1906 udp_cmsg_recv(msg, sk, skb);
1907
1908 if (inet_cmsg_flags(inet))
1909 ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off);
1910
1911 err = copied;
1912 if (flags & MSG_TRUNC)
1913 err = ulen;
1914
1915 trace_android_rvh_udp_recvmsg(sk, msg, len, flags, addr_len);
1916
1917 skb_consume_udp(sk, skb, peeking ? -err : err);
1918 return err;
1919
1920 csum_copy_err:
1921 if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags,
1922 udp_skb_destructor)) {
1923 UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
1924 UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
1925 }
1926 kfree_skb(skb);
1927
1928 /* starting over for a new packet, but check if we need to yield */
1929 cond_resched();
1930 msg->msg_flags &= ~MSG_TRUNC;
1931 goto try_again;
1932 }
1933
udp_pre_connect(struct sock * sk,struct sockaddr * uaddr,int addr_len)1934 int udp_pre_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
1935 {
1936 /* This check is replicated from __ip4_datagram_connect() and
1937 * intended to prevent BPF program called below from accessing bytes
1938 * that are out of the bound specified by user in addr_len.
1939 */
1940 if (addr_len < sizeof(struct sockaddr_in))
1941 return -EINVAL;
1942
1943 return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr, &addr_len);
1944 }
1945 EXPORT_SYMBOL(udp_pre_connect);
1946
__udp_disconnect(struct sock * sk,int flags)1947 int __udp_disconnect(struct sock *sk, int flags)
1948 {
1949 struct inet_sock *inet = inet_sk(sk);
1950 /*
1951 * 1003.1g - break association.
1952 */
1953
1954 sk->sk_state = TCP_CLOSE;
1955 inet->inet_daddr = 0;
1956 inet->inet_dport = 0;
1957 sock_rps_reset_rxhash(sk);
1958 sk->sk_bound_dev_if = 0;
1959 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) {
1960 inet_reset_saddr(sk);
1961 if (sk->sk_prot->rehash &&
1962 (sk->sk_userlocks & SOCK_BINDPORT_LOCK))
1963 sk->sk_prot->rehash(sk);
1964 }
1965
1966 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
1967 sk->sk_prot->unhash(sk);
1968 inet->inet_sport = 0;
1969 }
1970 sk_dst_reset(sk);
1971 return 0;
1972 }
1973 EXPORT_SYMBOL(__udp_disconnect);
1974
udp_disconnect(struct sock * sk,int flags)1975 int udp_disconnect(struct sock *sk, int flags)
1976 {
1977 lock_sock(sk);
1978 __udp_disconnect(sk, flags);
1979 release_sock(sk);
1980 return 0;
1981 }
1982 EXPORT_SYMBOL(udp_disconnect);
1983
udp_lib_unhash(struct sock * sk)1984 void udp_lib_unhash(struct sock *sk)
1985 {
1986 if (sk_hashed(sk)) {
1987 struct udp_table *udptable = udp_get_table_prot(sk);
1988 struct udp_hslot *hslot, *hslot2;
1989
1990 hslot = udp_hashslot(udptable, sock_net(sk),
1991 udp_sk(sk)->udp_port_hash);
1992 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
1993
1994 spin_lock_bh(&hslot->lock);
1995 if (rcu_access_pointer(sk->sk_reuseport_cb))
1996 reuseport_detach_sock(sk);
1997 if (sk_del_node_init_rcu(sk)) {
1998 hslot->count--;
1999 inet_sk(sk)->inet_num = 0;
2000 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
2001
2002 spin_lock(&hslot2->lock);
2003 hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2004 hslot2->count--;
2005 spin_unlock(&hslot2->lock);
2006 }
2007 spin_unlock_bh(&hslot->lock);
2008 }
2009 }
2010 EXPORT_SYMBOL(udp_lib_unhash);
2011
2012 /*
2013 * inet_rcv_saddr was changed, we must rehash secondary hash
2014 */
udp_lib_rehash(struct sock * sk,u16 newhash)2015 void udp_lib_rehash(struct sock *sk, u16 newhash)
2016 {
2017 if (sk_hashed(sk)) {
2018 struct udp_table *udptable = udp_get_table_prot(sk);
2019 struct udp_hslot *hslot, *hslot2, *nhslot2;
2020
2021 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
2022 nhslot2 = udp_hashslot2(udptable, newhash);
2023 udp_sk(sk)->udp_portaddr_hash = newhash;
2024
2025 if (hslot2 != nhslot2 ||
2026 rcu_access_pointer(sk->sk_reuseport_cb)) {
2027 hslot = udp_hashslot(udptable, sock_net(sk),
2028 udp_sk(sk)->udp_port_hash);
2029 /* we must lock primary chain too */
2030 spin_lock_bh(&hslot->lock);
2031 if (rcu_access_pointer(sk->sk_reuseport_cb))
2032 reuseport_detach_sock(sk);
2033
2034 if (hslot2 != nhslot2) {
2035 spin_lock(&hslot2->lock);
2036 hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
2037 hslot2->count--;
2038 spin_unlock(&hslot2->lock);
2039
2040 spin_lock(&nhslot2->lock);
2041 hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
2042 &nhslot2->head);
2043 nhslot2->count++;
2044 spin_unlock(&nhslot2->lock);
2045 }
2046
2047 spin_unlock_bh(&hslot->lock);
2048 }
2049 }
2050 }
2051 EXPORT_SYMBOL(udp_lib_rehash);
2052
udp_v4_rehash(struct sock * sk)2053 void udp_v4_rehash(struct sock *sk)
2054 {
2055 u16 new_hash = ipv4_portaddr_hash(sock_net(sk),
2056 inet_sk(sk)->inet_rcv_saddr,
2057 inet_sk(sk)->inet_num);
2058 udp_lib_rehash(sk, new_hash);
2059 }
2060
__udp_queue_rcv_skb(struct sock * sk,struct sk_buff * skb)2061 static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2062 {
2063 int rc;
2064
2065 if (inet_sk(sk)->inet_daddr) {
2066 sock_rps_save_rxhash(sk, skb);
2067 sk_mark_napi_id(sk, skb);
2068 sk_incoming_cpu_update(sk);
2069 } else {
2070 sk_mark_napi_id_once(sk, skb);
2071 }
2072
2073 rc = __udp_enqueue_schedule_skb(sk, skb);
2074 if (rc < 0) {
2075 int is_udplite = IS_UDPLITE(sk);
2076 int drop_reason;
2077
2078 /* Note that an ENOMEM error is charged twice */
2079 if (rc == -ENOMEM) {
2080 UDP_INC_STATS(sock_net(sk), UDP_MIB_RCVBUFERRORS,
2081 is_udplite);
2082 drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF;
2083 } else {
2084 UDP_INC_STATS(sock_net(sk), UDP_MIB_MEMERRORS,
2085 is_udplite);
2086 drop_reason = SKB_DROP_REASON_PROTO_MEM;
2087 }
2088 UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
2089 kfree_skb_reason(skb, drop_reason);
2090 trace_udp_fail_queue_rcv_skb(rc, sk);
2091 return -1;
2092 }
2093
2094 return 0;
2095 }
2096
2097 /* returns:
2098 * -1: error
2099 * 0: success
2100 * >0: "udp encap" protocol resubmission
2101 *
2102 * Note that in the success and error cases, the skb is assumed to
2103 * have either been requeued or freed.
2104 */
udp_queue_rcv_one_skb(struct sock * sk,struct sk_buff * skb)2105 static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb)
2106 {
2107 int drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2108 struct udp_sock *up = udp_sk(sk);
2109 int is_udplite = IS_UDPLITE(sk);
2110
2111 /*
2112 * Charge it to the socket, dropping if the queue is full.
2113 */
2114 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
2115 drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2116 goto drop;
2117 }
2118 nf_reset_ct(skb);
2119
2120 if (static_branch_unlikely(&udp_encap_needed_key) &&
2121 READ_ONCE(up->encap_type)) {
2122 int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
2123
2124 /*
2125 * This is an encapsulation socket so pass the skb to
2126 * the socket's udp_encap_rcv() hook. Otherwise, just
2127 * fall through and pass this up the UDP socket.
2128 * up->encap_rcv() returns the following value:
2129 * =0 if skb was successfully passed to the encap
2130 * handler or was discarded by it.
2131 * >0 if skb should be passed on to UDP.
2132 * <0 if skb should be resubmitted as proto -N
2133 */
2134
2135 /* if we're overly short, let UDP handle it */
2136 encap_rcv = READ_ONCE(up->encap_rcv);
2137 if (encap_rcv) {
2138 int ret;
2139
2140 /* Verify checksum before giving to encap */
2141 if (udp_lib_checksum_complete(skb))
2142 goto csum_error;
2143
2144 ret = encap_rcv(sk, skb);
2145 if (ret <= 0) {
2146 __UDP_INC_STATS(sock_net(sk),
2147 UDP_MIB_INDATAGRAMS,
2148 is_udplite);
2149 return -ret;
2150 }
2151 }
2152
2153 /* FALLTHROUGH -- it's a UDP Packet */
2154 }
2155
2156 /*
2157 * UDP-Lite specific tests, ignored on UDP sockets
2158 */
2159 if (udp_test_bit(UDPLITE_RECV_CC, sk) && UDP_SKB_CB(skb)->partial_cov) {
2160 u16 pcrlen = READ_ONCE(up->pcrlen);
2161
2162 /*
2163 * MIB statistics other than incrementing the error count are
2164 * disabled for the following two types of errors: these depend
2165 * on the application settings, not on the functioning of the
2166 * protocol stack as such.
2167 *
2168 * RFC 3828 here recommends (sec 3.3): "There should also be a
2169 * way ... to ... at least let the receiving application block
2170 * delivery of packets with coverage values less than a value
2171 * provided by the application."
2172 */
2173 if (pcrlen == 0) { /* full coverage was set */
2174 net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n",
2175 UDP_SKB_CB(skb)->cscov, skb->len);
2176 goto drop;
2177 }
2178 /* The next case involves violating the min. coverage requested
2179 * by the receiver. This is subtle: if receiver wants x and x is
2180 * greater than the buffersize/MTU then receiver will complain
2181 * that it wants x while sender emits packets of smaller size y.
2182 * Therefore the above ...()->partial_cov statement is essential.
2183 */
2184 if (UDP_SKB_CB(skb)->cscov < pcrlen) {
2185 net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n",
2186 UDP_SKB_CB(skb)->cscov, pcrlen);
2187 goto drop;
2188 }
2189 }
2190
2191 prefetch(&sk->sk_rmem_alloc);
2192 if (rcu_access_pointer(sk->sk_filter) &&
2193 udp_lib_checksum_complete(skb))
2194 goto csum_error;
2195
2196 if (sk_filter_trim_cap(sk, skb, sizeof(struct udphdr))) {
2197 drop_reason = SKB_DROP_REASON_SOCKET_FILTER;
2198 goto drop;
2199 }
2200
2201 udp_csum_pull_header(skb);
2202
2203 ipv4_pktinfo_prepare(sk, skb, true);
2204 return __udp_queue_rcv_skb(sk, skb);
2205
2206 csum_error:
2207 drop_reason = SKB_DROP_REASON_UDP_CSUM;
2208 __UDP_INC_STATS(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
2209 drop:
2210 __UDP_INC_STATS(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
2211 atomic_inc(&sk->sk_drops);
2212 kfree_skb_reason(skb, drop_reason);
2213 return -1;
2214 }
2215
udp_queue_rcv_skb(struct sock * sk,struct sk_buff * skb)2216 static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
2217 {
2218 struct sk_buff *next, *segs;
2219 int ret;
2220
2221 if (likely(!udp_unexpected_gso(sk, skb)))
2222 return udp_queue_rcv_one_skb(sk, skb);
2223
2224 BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET);
2225 __skb_push(skb, -skb_mac_offset(skb));
2226 segs = udp_rcv_segment(sk, skb, true);
2227 skb_list_walk_safe(segs, skb, next) {
2228 __skb_pull(skb, skb_transport_offset(skb));
2229
2230 udp_post_segment_fix_csum(skb);
2231 ret = udp_queue_rcv_one_skb(sk, skb);
2232 if (ret > 0)
2233 ip_protocol_deliver_rcu(dev_net(skb->dev), skb, ret);
2234 }
2235 return 0;
2236 }
2237
2238 /* For TCP sockets, sk_rx_dst is protected by socket lock
2239 * For UDP, we use xchg() to guard against concurrent changes.
2240 */
udp_sk_rx_dst_set(struct sock * sk,struct dst_entry * dst)2241 bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst)
2242 {
2243 struct dst_entry *old;
2244
2245 if (dst_hold_safe(dst)) {
2246 old = xchg((__force struct dst_entry **)&sk->sk_rx_dst, dst);
2247 dst_release(old);
2248 return old != dst;
2249 }
2250 return false;
2251 }
2252 EXPORT_SYMBOL(udp_sk_rx_dst_set);
2253
2254 /*
2255 * Multicasts and broadcasts go to each listener.
2256 *
2257 * Note: called only from the BH handler context.
2258 */
__udp4_lib_mcast_deliver(struct net * net,struct sk_buff * skb,struct udphdr * uh,__be32 saddr,__be32 daddr,struct udp_table * udptable,int proto)2259 static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
2260 struct udphdr *uh,
2261 __be32 saddr, __be32 daddr,
2262 struct udp_table *udptable,
2263 int proto)
2264 {
2265 struct sock *sk, *first = NULL;
2266 unsigned short hnum = ntohs(uh->dest);
2267 struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum);
2268 unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10);
2269 unsigned int offset = offsetof(typeof(*sk), sk_node);
2270 int dif = skb->dev->ifindex;
2271 int sdif = inet_sdif(skb);
2272 struct hlist_node *node;
2273 struct sk_buff *nskb;
2274
2275 if (use_hash2) {
2276 hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) &
2277 udptable->mask;
2278 hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask;
2279 start_lookup:
2280 hslot = &udptable->hash2[hash2];
2281 offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node);
2282 }
2283
2284 sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) {
2285 if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr,
2286 uh->source, saddr, dif, sdif, hnum))
2287 continue;
2288
2289 if (!first) {
2290 first = sk;
2291 continue;
2292 }
2293 nskb = skb_clone(skb, GFP_ATOMIC);
2294
2295 if (unlikely(!nskb)) {
2296 atomic_inc(&sk->sk_drops);
2297 __UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS,
2298 IS_UDPLITE(sk));
2299 __UDP_INC_STATS(net, UDP_MIB_INERRORS,
2300 IS_UDPLITE(sk));
2301 continue;
2302 }
2303 if (udp_queue_rcv_skb(sk, nskb) > 0)
2304 consume_skb(nskb);
2305 }
2306
2307 /* Also lookup *:port if we are using hash2 and haven't done so yet. */
2308 if (use_hash2 && hash2 != hash2_any) {
2309 hash2 = hash2_any;
2310 goto start_lookup;
2311 }
2312
2313 if (first) {
2314 if (udp_queue_rcv_skb(first, skb) > 0)
2315 consume_skb(skb);
2316 } else {
2317 kfree_skb(skb);
2318 __UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI,
2319 proto == IPPROTO_UDPLITE);
2320 }
2321 return 0;
2322 }
2323
2324 /* Initialize UDP checksum. If exited with zero value (success),
2325 * CHECKSUM_UNNECESSARY means, that no more checks are required.
2326 * Otherwise, csum completion requires checksumming packet body,
2327 * including udp header and folding it to skb->csum.
2328 */
udp4_csum_init(struct sk_buff * skb,struct udphdr * uh,int proto)2329 static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
2330 int proto)
2331 {
2332 int err;
2333
2334 UDP_SKB_CB(skb)->partial_cov = 0;
2335 UDP_SKB_CB(skb)->cscov = skb->len;
2336
2337 if (proto == IPPROTO_UDPLITE) {
2338 err = udplite_checksum_init(skb, uh);
2339 if (err)
2340 return err;
2341
2342 if (UDP_SKB_CB(skb)->partial_cov) {
2343 skb->csum = inet_compute_pseudo(skb, proto);
2344 return 0;
2345 }
2346 }
2347
2348 /* Note, we are only interested in != 0 or == 0, thus the
2349 * force to int.
2350 */
2351 err = (__force int)skb_checksum_init_zero_check(skb, proto, uh->check,
2352 inet_compute_pseudo);
2353 if (err)
2354 return err;
2355
2356 if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) {
2357 /* If SW calculated the value, we know it's bad */
2358 if (skb->csum_complete_sw)
2359 return 1;
2360
2361 /* HW says the value is bad. Let's validate that.
2362 * skb->csum is no longer the full packet checksum,
2363 * so don't treat it as such.
2364 */
2365 skb_checksum_complete_unset(skb);
2366 }
2367
2368 return 0;
2369 }
2370
2371 /* wrapper for udp_queue_rcv_skb tacking care of csum conversion and
2372 * return code conversion for ip layer consumption
2373 */
udp_unicast_rcv_skb(struct sock * sk,struct sk_buff * skb,struct udphdr * uh)2374 static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb,
2375 struct udphdr *uh)
2376 {
2377 int ret;
2378
2379 if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk))
2380 skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo);
2381
2382 ret = udp_queue_rcv_skb(sk, skb);
2383
2384 /* a return value > 0 means to resubmit the input, but
2385 * it wants the return to be -protocol, or 0
2386 */
2387 if (ret > 0)
2388 return -ret;
2389 return 0;
2390 }
2391
2392 /*
2393 * All we need to do is get the socket, and then do a checksum.
2394 */
2395
__udp4_lib_rcv(struct sk_buff * skb,struct udp_table * udptable,int proto)2396 int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
2397 int proto)
2398 {
2399 struct sock *sk;
2400 struct udphdr *uh;
2401 unsigned short ulen;
2402 struct rtable *rt = skb_rtable(skb);
2403 __be32 saddr, daddr;
2404 struct net *net = dev_net(skb->dev);
2405 bool refcounted;
2406 int drop_reason;
2407
2408 drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2409
2410 /*
2411 * Validate the packet.
2412 */
2413 if (!pskb_may_pull(skb, sizeof(struct udphdr)))
2414 goto drop; /* No space for header. */
2415
2416 uh = udp_hdr(skb);
2417 ulen = ntohs(uh->len);
2418 saddr = ip_hdr(skb)->saddr;
2419 daddr = ip_hdr(skb)->daddr;
2420
2421 if (ulen > skb->len)
2422 goto short_packet;
2423
2424 if (proto == IPPROTO_UDP) {
2425 /* UDP validates ulen. */
2426 if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
2427 goto short_packet;
2428 uh = udp_hdr(skb);
2429 }
2430
2431 if (udp4_csum_init(skb, uh, proto))
2432 goto csum_error;
2433
2434 sk = inet_steal_sock(net, skb, sizeof(struct udphdr), saddr, uh->source, daddr, uh->dest,
2435 &refcounted, udp_ehashfn);
2436 if (IS_ERR(sk))
2437 goto no_sk;
2438
2439 if (sk) {
2440 struct dst_entry *dst = skb_dst(skb);
2441 int ret;
2442
2443 if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst))
2444 udp_sk_rx_dst_set(sk, dst);
2445
2446 ret = udp_unicast_rcv_skb(sk, skb, uh);
2447 if (refcounted)
2448 sock_put(sk);
2449 return ret;
2450 }
2451
2452 if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
2453 return __udp4_lib_mcast_deliver(net, skb, uh,
2454 saddr, daddr, udptable, proto);
2455
2456 sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
2457 if (sk)
2458 return udp_unicast_rcv_skb(sk, skb, uh);
2459 no_sk:
2460 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2461 goto drop;
2462 nf_reset_ct(skb);
2463
2464 /* No socket. Drop packet silently, if checksum is wrong */
2465 if (udp_lib_checksum_complete(skb))
2466 goto csum_error;
2467
2468 drop_reason = SKB_DROP_REASON_NO_SOCKET;
2469 __UDP_INC_STATS(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
2470 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
2471
2472 /*
2473 * Hmm. We got an UDP packet to a port to which we
2474 * don't wanna listen. Ignore it.
2475 */
2476 kfree_skb_reason(skb, drop_reason);
2477 return 0;
2478
2479 short_packet:
2480 drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
2481 net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
2482 proto == IPPROTO_UDPLITE ? "Lite" : "",
2483 &saddr, ntohs(uh->source),
2484 ulen, skb->len,
2485 &daddr, ntohs(uh->dest));
2486 goto drop;
2487
2488 csum_error:
2489 /*
2490 * RFC1122: OK. Discards the bad packet silently (as far as
2491 * the network is concerned, anyway) as per 4.1.3.4 (MUST).
2492 */
2493 drop_reason = SKB_DROP_REASON_UDP_CSUM;
2494 net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
2495 proto == IPPROTO_UDPLITE ? "Lite" : "",
2496 &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
2497 ulen);
2498 __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
2499 drop:
2500 __UDP_INC_STATS(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
2501 kfree_skb_reason(skb, drop_reason);
2502 return 0;
2503 }
2504
2505 /* We can only early demux multicast if there is a single matching socket.
2506 * If more than one socket found returns NULL
2507 */
__udp4_lib_mcast_demux_lookup(struct net * net,__be16 loc_port,__be32 loc_addr,__be16 rmt_port,__be32 rmt_addr,int dif,int sdif)2508 static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net,
2509 __be16 loc_port, __be32 loc_addr,
2510 __be16 rmt_port, __be32 rmt_addr,
2511 int dif, int sdif)
2512 {
2513 struct udp_table *udptable = net->ipv4.udp_table;
2514 unsigned short hnum = ntohs(loc_port);
2515 struct sock *sk, *result;
2516 struct udp_hslot *hslot;
2517 unsigned int slot;
2518
2519 slot = udp_hashfn(net, hnum, udptable->mask);
2520 hslot = &udptable->hash[slot];
2521
2522 /* Do not bother scanning a too big list */
2523 if (hslot->count > 10)
2524 return NULL;
2525
2526 result = NULL;
2527 sk_for_each_rcu(sk, &hslot->head) {
2528 if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr,
2529 rmt_port, rmt_addr, dif, sdif, hnum)) {
2530 if (result)
2531 return NULL;
2532 result = sk;
2533 }
2534 }
2535
2536 return result;
2537 }
2538
2539 /* For unicast we should only early demux connected sockets or we can
2540 * break forwarding setups. The chains here can be long so only check
2541 * if the first socket is an exact match and if not move on.
2542 */
__udp4_lib_demux_lookup(struct net * net,__be16 loc_port,__be32 loc_addr,__be16 rmt_port,__be32 rmt_addr,int dif,int sdif)2543 static struct sock *__udp4_lib_demux_lookup(struct net *net,
2544 __be16 loc_port, __be32 loc_addr,
2545 __be16 rmt_port, __be32 rmt_addr,
2546 int dif, int sdif)
2547 {
2548 struct udp_table *udptable = net->ipv4.udp_table;
2549 INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr);
2550 unsigned short hnum = ntohs(loc_port);
2551 unsigned int hash2, slot2;
2552 struct udp_hslot *hslot2;
2553 __portpair ports;
2554 struct sock *sk;
2555
2556 hash2 = ipv4_portaddr_hash(net, loc_addr, hnum);
2557 slot2 = hash2 & udptable->mask;
2558 hslot2 = &udptable->hash2[slot2];
2559 ports = INET_COMBINED_PORTS(rmt_port, hnum);
2560
2561 udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) {
2562 if (inet_match(net, sk, acookie, ports, dif, sdif))
2563 return sk;
2564 /* Only check first socket in chain */
2565 break;
2566 }
2567 return NULL;
2568 }
2569
udp_v4_early_demux(struct sk_buff * skb)2570 int udp_v4_early_demux(struct sk_buff *skb)
2571 {
2572 struct net *net = dev_net(skb->dev);
2573 struct in_device *in_dev = NULL;
2574 const struct iphdr *iph;
2575 const struct udphdr *uh;
2576 struct sock *sk = NULL;
2577 struct dst_entry *dst;
2578 int dif = skb->dev->ifindex;
2579 int sdif = inet_sdif(skb);
2580 int ours;
2581
2582 /* validate the packet */
2583 if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr)))
2584 return 0;
2585
2586 iph = ip_hdr(skb);
2587 uh = udp_hdr(skb);
2588
2589 if (skb->pkt_type == PACKET_MULTICAST) {
2590 in_dev = __in_dev_get_rcu(skb->dev);
2591
2592 if (!in_dev)
2593 return 0;
2594
2595 ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr,
2596 iph->protocol);
2597 if (!ours)
2598 return 0;
2599
2600 sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr,
2601 uh->source, iph->saddr,
2602 dif, sdif);
2603 } else if (skb->pkt_type == PACKET_HOST) {
2604 sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr,
2605 uh->source, iph->saddr, dif, sdif);
2606 }
2607
2608 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
2609 return 0;
2610
2611 skb->sk = sk;
2612 skb->destructor = sock_efree;
2613 dst = rcu_dereference(sk->sk_rx_dst);
2614
2615 if (dst)
2616 dst = dst_check(dst, 0);
2617 if (dst) {
2618 u32 itag = 0;
2619
2620 /* set noref for now.
2621 * any place which wants to hold dst has to call
2622 * dst_hold_safe()
2623 */
2624 skb_dst_set_noref(skb, dst);
2625
2626 /* for unconnected multicast sockets we need to validate
2627 * the source on each packet
2628 */
2629 if (!inet_sk(sk)->inet_daddr && in_dev)
2630 return ip_mc_validate_source(skb, iph->daddr,
2631 iph->saddr,
2632 iph->tos & IPTOS_RT_MASK,
2633 skb->dev, in_dev, &itag);
2634 }
2635 return 0;
2636 }
2637
udp_rcv(struct sk_buff * skb)2638 int udp_rcv(struct sk_buff *skb)
2639 {
2640 return __udp4_lib_rcv(skb, dev_net(skb->dev)->ipv4.udp_table, IPPROTO_UDP);
2641 }
2642
udp_destroy_sock(struct sock * sk)2643 void udp_destroy_sock(struct sock *sk)
2644 {
2645 struct udp_sock *up = udp_sk(sk);
2646 bool slow = lock_sock_fast(sk);
2647
2648 /* protects from races with udp_abort() */
2649 sock_set_flag(sk, SOCK_DEAD);
2650 udp_flush_pending_frames(sk);
2651 unlock_sock_fast(sk, slow);
2652 if (static_branch_unlikely(&udp_encap_needed_key)) {
2653 if (up->encap_type) {
2654 void (*encap_destroy)(struct sock *sk);
2655 encap_destroy = READ_ONCE(up->encap_destroy);
2656 if (encap_destroy)
2657 encap_destroy(sk);
2658 }
2659 if (udp_test_bit(ENCAP_ENABLED, sk))
2660 static_branch_dec(&udp_encap_needed_key);
2661 }
2662 }
2663
2664 /*
2665 * Socket option code for UDP
2666 */
udp_lib_setsockopt(struct sock * sk,int level,int optname,sockptr_t optval,unsigned int optlen,int (* push_pending_frames)(struct sock *))2667 int udp_lib_setsockopt(struct sock *sk, int level, int optname,
2668 sockptr_t optval, unsigned int optlen,
2669 int (*push_pending_frames)(struct sock *))
2670 {
2671 struct udp_sock *up = udp_sk(sk);
2672 int val, valbool;
2673 int err = 0;
2674 int is_udplite = IS_UDPLITE(sk);
2675
2676 if (level == SOL_SOCKET) {
2677 err = sk_setsockopt(sk, level, optname, optval, optlen);
2678
2679 if (optname == SO_RCVBUF || optname == SO_RCVBUFFORCE) {
2680 sockopt_lock_sock(sk);
2681 /* paired with READ_ONCE in udp_rmem_release() */
2682 WRITE_ONCE(up->forward_threshold, sk->sk_rcvbuf >> 2);
2683 sockopt_release_sock(sk);
2684 }
2685 return err;
2686 }
2687
2688 if (optlen < sizeof(int))
2689 return -EINVAL;
2690
2691 if (copy_from_sockptr(&val, optval, sizeof(val)))
2692 return -EFAULT;
2693
2694 valbool = val ? 1 : 0;
2695
2696 switch (optname) {
2697 case UDP_CORK:
2698 if (val != 0) {
2699 udp_set_bit(CORK, sk);
2700 } else {
2701 udp_clear_bit(CORK, sk);
2702 lock_sock(sk);
2703 push_pending_frames(sk);
2704 release_sock(sk);
2705 }
2706 break;
2707
2708 case UDP_ENCAP:
2709 switch (val) {
2710 case 0:
2711 #ifdef CONFIG_XFRM
2712 case UDP_ENCAP_ESPINUDP:
2713 case UDP_ENCAP_ESPINUDP_NON_IKE:
2714 #if IS_ENABLED(CONFIG_IPV6)
2715 if (sk->sk_family == AF_INET6)
2716 WRITE_ONCE(up->encap_rcv,
2717 ipv6_stub->xfrm6_udp_encap_rcv);
2718 else
2719 #endif
2720 WRITE_ONCE(up->encap_rcv,
2721 xfrm4_udp_encap_rcv);
2722 #endif
2723 fallthrough;
2724 case UDP_ENCAP_L2TPINUDP:
2725 WRITE_ONCE(up->encap_type, val);
2726 udp_tunnel_encap_enable(sk);
2727 break;
2728 default:
2729 err = -ENOPROTOOPT;
2730 break;
2731 }
2732 break;
2733
2734 case UDP_NO_CHECK6_TX:
2735 udp_set_no_check6_tx(sk, valbool);
2736 break;
2737
2738 case UDP_NO_CHECK6_RX:
2739 udp_set_no_check6_rx(sk, valbool);
2740 break;
2741
2742 case UDP_SEGMENT:
2743 if (val < 0 || val > USHRT_MAX)
2744 return -EINVAL;
2745 WRITE_ONCE(up->gso_size, val);
2746 break;
2747
2748 case UDP_GRO:
2749
2750 /* when enabling GRO, accept the related GSO packet type */
2751 if (valbool)
2752 udp_tunnel_encap_enable(sk);
2753 udp_assign_bit(GRO_ENABLED, sk, valbool);
2754 udp_assign_bit(ACCEPT_L4, sk, valbool);
2755 break;
2756
2757 /*
2758 * UDP-Lite's partial checksum coverage (RFC 3828).
2759 */
2760 /* The sender sets actual checksum coverage length via this option.
2761 * The case coverage > packet length is handled by send module. */
2762 case UDPLITE_SEND_CSCOV:
2763 if (!is_udplite) /* Disable the option on UDP sockets */
2764 return -ENOPROTOOPT;
2765 if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
2766 val = 8;
2767 else if (val > USHRT_MAX)
2768 val = USHRT_MAX;
2769 WRITE_ONCE(up->pcslen, val);
2770 udp_set_bit(UDPLITE_SEND_CC, sk);
2771 break;
2772
2773 /* The receiver specifies a minimum checksum coverage value. To make
2774 * sense, this should be set to at least 8 (as done below). If zero is
2775 * used, this again means full checksum coverage. */
2776 case UDPLITE_RECV_CSCOV:
2777 if (!is_udplite) /* Disable the option on UDP sockets */
2778 return -ENOPROTOOPT;
2779 if (val != 0 && val < 8) /* Avoid silly minimal values. */
2780 val = 8;
2781 else if (val > USHRT_MAX)
2782 val = USHRT_MAX;
2783 WRITE_ONCE(up->pcrlen, val);
2784 udp_set_bit(UDPLITE_RECV_CC, sk);
2785 break;
2786
2787 default:
2788 err = -ENOPROTOOPT;
2789 break;
2790 }
2791
2792 return err;
2793 }
2794 EXPORT_SYMBOL(udp_lib_setsockopt);
2795
udp_setsockopt(struct sock * sk,int level,int optname,sockptr_t optval,unsigned int optlen)2796 int udp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval,
2797 unsigned int optlen)
2798 {
2799 if (level == SOL_UDP || level == SOL_UDPLITE || level == SOL_SOCKET)
2800 return udp_lib_setsockopt(sk, level, optname,
2801 optval, optlen,
2802 udp_push_pending_frames);
2803 return ip_setsockopt(sk, level, optname, optval, optlen);
2804 }
2805
udp_lib_getsockopt(struct sock * sk,int level,int optname,char __user * optval,int __user * optlen)2806 int udp_lib_getsockopt(struct sock *sk, int level, int optname,
2807 char __user *optval, int __user *optlen)
2808 {
2809 struct udp_sock *up = udp_sk(sk);
2810 int val, len;
2811
2812 if (get_user(len, optlen))
2813 return -EFAULT;
2814
2815 if (len < 0)
2816 return -EINVAL;
2817
2818 len = min_t(unsigned int, len, sizeof(int));
2819
2820 switch (optname) {
2821 case UDP_CORK:
2822 val = udp_test_bit(CORK, sk);
2823 break;
2824
2825 case UDP_ENCAP:
2826 val = READ_ONCE(up->encap_type);
2827 break;
2828
2829 case UDP_NO_CHECK6_TX:
2830 val = udp_get_no_check6_tx(sk);
2831 break;
2832
2833 case UDP_NO_CHECK6_RX:
2834 val = udp_get_no_check6_rx(sk);
2835 break;
2836
2837 case UDP_SEGMENT:
2838 val = READ_ONCE(up->gso_size);
2839 break;
2840
2841 case UDP_GRO:
2842 val = udp_test_bit(GRO_ENABLED, sk);
2843 break;
2844
2845 /* The following two cannot be changed on UDP sockets, the return is
2846 * always 0 (which corresponds to the full checksum coverage of UDP). */
2847 case UDPLITE_SEND_CSCOV:
2848 val = READ_ONCE(up->pcslen);
2849 break;
2850
2851 case UDPLITE_RECV_CSCOV:
2852 val = READ_ONCE(up->pcrlen);
2853 break;
2854
2855 default:
2856 return -ENOPROTOOPT;
2857 }
2858
2859 if (put_user(len, optlen))
2860 return -EFAULT;
2861 if (copy_to_user(optval, &val, len))
2862 return -EFAULT;
2863 return 0;
2864 }
2865 EXPORT_SYMBOL(udp_lib_getsockopt);
2866
udp_getsockopt(struct sock * sk,int level,int optname,char __user * optval,int __user * optlen)2867 int udp_getsockopt(struct sock *sk, int level, int optname,
2868 char __user *optval, int __user *optlen)
2869 {
2870 if (level == SOL_UDP || level == SOL_UDPLITE)
2871 return udp_lib_getsockopt(sk, level, optname, optval, optlen);
2872 return ip_getsockopt(sk, level, optname, optval, optlen);
2873 }
2874
2875 /**
2876 * udp_poll - wait for a UDP event.
2877 * @file: - file struct
2878 * @sock: - socket
2879 * @wait: - poll table
2880 *
2881 * This is same as datagram poll, except for the special case of
2882 * blocking sockets. If application is using a blocking fd
2883 * and a packet with checksum error is in the queue;
2884 * then it could get return from select indicating data available
2885 * but then block when reading it. Add special case code
2886 * to work around these arguably broken applications.
2887 */
udp_poll(struct file * file,struct socket * sock,poll_table * wait)2888 __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait)
2889 {
2890 __poll_t mask = datagram_poll(file, sock, wait);
2891 struct sock *sk = sock->sk;
2892
2893 if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue))
2894 mask |= EPOLLIN | EPOLLRDNORM;
2895
2896 /* Check for false positives due to checksum errors */
2897 if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
2898 !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1)
2899 mask &= ~(EPOLLIN | EPOLLRDNORM);
2900
2901 /* psock ingress_msg queue should not contain any bad checksum frames */
2902 if (sk_is_readable(sk))
2903 mask |= EPOLLIN | EPOLLRDNORM;
2904 return mask;
2905
2906 }
2907 EXPORT_SYMBOL(udp_poll);
2908
udp_abort(struct sock * sk,int err)2909 int udp_abort(struct sock *sk, int err)
2910 {
2911 if (!has_current_bpf_ctx())
2912 lock_sock(sk);
2913
2914 /* udp{v6}_destroy_sock() sets it under the sk lock, avoid racing
2915 * with close()
2916 */
2917 if (sock_flag(sk, SOCK_DEAD))
2918 goto out;
2919
2920 sk->sk_err = err;
2921 sk_error_report(sk);
2922 __udp_disconnect(sk, 0);
2923
2924 out:
2925 if (!has_current_bpf_ctx())
2926 release_sock(sk);
2927
2928 return 0;
2929 }
2930 EXPORT_SYMBOL_GPL(udp_abort);
2931
2932 struct proto udp_prot = {
2933 .name = "UDP",
2934 .owner = THIS_MODULE,
2935 .close = udp_lib_close,
2936 .pre_connect = udp_pre_connect,
2937 .connect = ip4_datagram_connect,
2938 .disconnect = udp_disconnect,
2939 .ioctl = udp_ioctl,
2940 .init = udp_init_sock,
2941 .destroy = udp_destroy_sock,
2942 .setsockopt = udp_setsockopt,
2943 .getsockopt = udp_getsockopt,
2944 .sendmsg = udp_sendmsg,
2945 .recvmsg = udp_recvmsg,
2946 .splice_eof = udp_splice_eof,
2947 .release_cb = ip4_datagram_release_cb,
2948 .hash = udp_lib_hash,
2949 .unhash = udp_lib_unhash,
2950 .rehash = udp_v4_rehash,
2951 .get_port = udp_v4_get_port,
2952 .put_port = udp_lib_unhash,
2953 #ifdef CONFIG_BPF_SYSCALL
2954 .psock_update_sk_prot = udp_bpf_update_proto,
2955 #endif
2956 .memory_allocated = &udp_memory_allocated,
2957 .per_cpu_fw_alloc = &udp_memory_per_cpu_fw_alloc,
2958
2959 .sysctl_mem = sysctl_udp_mem,
2960 .sysctl_wmem_offset = offsetof(struct net, ipv4.sysctl_udp_wmem_min),
2961 .sysctl_rmem_offset = offsetof(struct net, ipv4.sysctl_udp_rmem_min),
2962 .obj_size = sizeof(struct udp_sock),
2963 .h.udp_table = NULL,
2964 .diag_destroy = udp_abort,
2965 };
2966 EXPORT_SYMBOL(udp_prot);
2967
2968 /* ------------------------------------------------------------------------ */
2969 #ifdef CONFIG_PROC_FS
2970
2971 static unsigned short seq_file_family(const struct seq_file *seq);
seq_sk_match(struct seq_file * seq,const struct sock * sk)2972 static bool seq_sk_match(struct seq_file *seq, const struct sock *sk)
2973 {
2974 unsigned short family = seq_file_family(seq);
2975
2976 /* AF_UNSPEC is used as a match all */
2977 return ((family == AF_UNSPEC || family == sk->sk_family) &&
2978 net_eq(sock_net(sk), seq_file_net(seq)));
2979 }
2980
2981 #ifdef CONFIG_BPF_SYSCALL
2982 static const struct seq_operations bpf_iter_udp_seq_ops;
2983 #endif
udp_get_table_seq(struct seq_file * seq,struct net * net)2984 static struct udp_table *udp_get_table_seq(struct seq_file *seq,
2985 struct net *net)
2986 {
2987 const struct udp_seq_afinfo *afinfo;
2988
2989 #ifdef CONFIG_BPF_SYSCALL
2990 if (seq->op == &bpf_iter_udp_seq_ops)
2991 return net->ipv4.udp_table;
2992 #endif
2993
2994 afinfo = pde_data(file_inode(seq->file));
2995 return afinfo->udp_table ? : net->ipv4.udp_table;
2996 }
2997
udp_get_first(struct seq_file * seq,int start)2998 static struct sock *udp_get_first(struct seq_file *seq, int start)
2999 {
3000 struct udp_iter_state *state = seq->private;
3001 struct net *net = seq_file_net(seq);
3002 struct udp_table *udptable;
3003 struct sock *sk;
3004
3005 udptable = udp_get_table_seq(seq, net);
3006
3007 for (state->bucket = start; state->bucket <= udptable->mask;
3008 ++state->bucket) {
3009 struct udp_hslot *hslot = &udptable->hash[state->bucket];
3010
3011 if (hlist_empty(&hslot->head))
3012 continue;
3013
3014 spin_lock_bh(&hslot->lock);
3015 sk_for_each(sk, &hslot->head) {
3016 if (seq_sk_match(seq, sk))
3017 goto found;
3018 }
3019 spin_unlock_bh(&hslot->lock);
3020 }
3021 sk = NULL;
3022 found:
3023 return sk;
3024 }
3025
udp_get_next(struct seq_file * seq,struct sock * sk)3026 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
3027 {
3028 struct udp_iter_state *state = seq->private;
3029 struct net *net = seq_file_net(seq);
3030 struct udp_table *udptable;
3031
3032 do {
3033 sk = sk_next(sk);
3034 } while (sk && !seq_sk_match(seq, sk));
3035
3036 if (!sk) {
3037 udptable = udp_get_table_seq(seq, net);
3038
3039 if (state->bucket <= udptable->mask)
3040 spin_unlock_bh(&udptable->hash[state->bucket].lock);
3041
3042 return udp_get_first(seq, state->bucket + 1);
3043 }
3044 return sk;
3045 }
3046
udp_get_idx(struct seq_file * seq,loff_t pos)3047 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
3048 {
3049 struct sock *sk = udp_get_first(seq, 0);
3050
3051 if (sk)
3052 while (pos && (sk = udp_get_next(seq, sk)) != NULL)
3053 --pos;
3054 return pos ? NULL : sk;
3055 }
3056
udp_seq_start(struct seq_file * seq,loff_t * pos)3057 void *udp_seq_start(struct seq_file *seq, loff_t *pos)
3058 {
3059 struct udp_iter_state *state = seq->private;
3060 state->bucket = MAX_UDP_PORTS;
3061
3062 return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
3063 }
3064 EXPORT_SYMBOL(udp_seq_start);
3065
udp_seq_next(struct seq_file * seq,void * v,loff_t * pos)3066 void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3067 {
3068 struct sock *sk;
3069
3070 if (v == SEQ_START_TOKEN)
3071 sk = udp_get_idx(seq, 0);
3072 else
3073 sk = udp_get_next(seq, v);
3074
3075 ++*pos;
3076 return sk;
3077 }
3078 EXPORT_SYMBOL(udp_seq_next);
3079
udp_seq_stop(struct seq_file * seq,void * v)3080 void udp_seq_stop(struct seq_file *seq, void *v)
3081 {
3082 struct udp_iter_state *state = seq->private;
3083 struct udp_table *udptable;
3084
3085 udptable = udp_get_table_seq(seq, seq_file_net(seq));
3086
3087 if (state->bucket <= udptable->mask)
3088 spin_unlock_bh(&udptable->hash[state->bucket].lock);
3089 }
3090 EXPORT_SYMBOL(udp_seq_stop);
3091
3092 /* ------------------------------------------------------------------------ */
udp4_format_sock(struct sock * sp,struct seq_file * f,int bucket)3093 static void udp4_format_sock(struct sock *sp, struct seq_file *f,
3094 int bucket)
3095 {
3096 struct inet_sock *inet = inet_sk(sp);
3097 __be32 dest = inet->inet_daddr;
3098 __be32 src = inet->inet_rcv_saddr;
3099 __u16 destp = ntohs(inet->inet_dport);
3100 __u16 srcp = ntohs(inet->inet_sport);
3101
3102 seq_printf(f, "%5d: %08X:%04X %08X:%04X"
3103 " %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
3104 bucket, src, srcp, dest, destp, sp->sk_state,
3105 sk_wmem_alloc_get(sp),
3106 udp_rqueue_get(sp),
3107 0, 0L, 0,
3108 from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
3109 0, sock_i_ino(sp),
3110 refcount_read(&sp->sk_refcnt), sp,
3111 atomic_read(&sp->sk_drops));
3112 }
3113
udp4_seq_show(struct seq_file * seq,void * v)3114 int udp4_seq_show(struct seq_file *seq, void *v)
3115 {
3116 seq_setwidth(seq, 127);
3117 if (v == SEQ_START_TOKEN)
3118 seq_puts(seq, " sl local_address rem_address st tx_queue "
3119 "rx_queue tr tm->when retrnsmt uid timeout "
3120 "inode ref pointer drops");
3121 else {
3122 struct udp_iter_state *state = seq->private;
3123
3124 udp4_format_sock(v, seq, state->bucket);
3125 }
3126 seq_pad(seq, '\n');
3127 return 0;
3128 }
3129
3130 #ifdef CONFIG_BPF_SYSCALL
3131 struct bpf_iter__udp {
3132 __bpf_md_ptr(struct bpf_iter_meta *, meta);
3133 __bpf_md_ptr(struct udp_sock *, udp_sk);
3134 uid_t uid __aligned(8);
3135 int bucket __aligned(8);
3136 };
3137
3138 struct bpf_udp_iter_state {
3139 struct udp_iter_state state;
3140 unsigned int cur_sk;
3141 unsigned int end_sk;
3142 unsigned int max_sk;
3143 int offset;
3144 struct sock **batch;
3145 bool st_bucket_done;
3146 };
3147
3148 static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3149 unsigned int new_batch_sz);
bpf_iter_udp_batch(struct seq_file * seq)3150 static struct sock *bpf_iter_udp_batch(struct seq_file *seq)
3151 {
3152 struct bpf_udp_iter_state *iter = seq->private;
3153 struct udp_iter_state *state = &iter->state;
3154 struct net *net = seq_file_net(seq);
3155 int resume_bucket, resume_offset;
3156 struct udp_table *udptable;
3157 unsigned int batch_sks = 0;
3158 bool resized = false;
3159 struct sock *sk;
3160
3161 resume_bucket = state->bucket;
3162 resume_offset = iter->offset;
3163
3164 /* The current batch is done, so advance the bucket. */
3165 if (iter->st_bucket_done)
3166 state->bucket++;
3167
3168 udptable = udp_get_table_seq(seq, net);
3169
3170 again:
3171 /* New batch for the next bucket.
3172 * Iterate over the hash table to find a bucket with sockets matching
3173 * the iterator attributes, and return the first matching socket from
3174 * the bucket. The remaining matched sockets from the bucket are batched
3175 * before releasing the bucket lock. This allows BPF programs that are
3176 * called in seq_show to acquire the bucket lock if needed.
3177 */
3178 iter->cur_sk = 0;
3179 iter->end_sk = 0;
3180 iter->st_bucket_done = false;
3181 batch_sks = 0;
3182
3183 for (; state->bucket <= udptable->mask; state->bucket++) {
3184 struct udp_hslot *hslot2 = &udptable->hash2[state->bucket];
3185
3186 if (hlist_empty(&hslot2->head))
3187 continue;
3188
3189 iter->offset = 0;
3190 spin_lock_bh(&hslot2->lock);
3191 udp_portaddr_for_each_entry(sk, &hslot2->head) {
3192 if (seq_sk_match(seq, sk)) {
3193 /* Resume from the last iterated socket at the
3194 * offset in the bucket before iterator was stopped.
3195 */
3196 if (state->bucket == resume_bucket &&
3197 iter->offset < resume_offset) {
3198 ++iter->offset;
3199 continue;
3200 }
3201 if (iter->end_sk < iter->max_sk) {
3202 sock_hold(sk);
3203 iter->batch[iter->end_sk++] = sk;
3204 }
3205 batch_sks++;
3206 }
3207 }
3208 spin_unlock_bh(&hslot2->lock);
3209
3210 if (iter->end_sk)
3211 break;
3212 }
3213
3214 /* All done: no batch made. */
3215 if (!iter->end_sk)
3216 return NULL;
3217
3218 if (iter->end_sk == batch_sks) {
3219 /* Batching is done for the current bucket; return the first
3220 * socket to be iterated from the batch.
3221 */
3222 iter->st_bucket_done = true;
3223 goto done;
3224 }
3225 if (!resized && !bpf_iter_udp_realloc_batch(iter, batch_sks * 3 / 2)) {
3226 resized = true;
3227 /* After allocating a larger batch, retry one more time to grab
3228 * the whole bucket.
3229 */
3230 goto again;
3231 }
3232 done:
3233 return iter->batch[0];
3234 }
3235
bpf_iter_udp_seq_next(struct seq_file * seq,void * v,loff_t * pos)3236 static void *bpf_iter_udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3237 {
3238 struct bpf_udp_iter_state *iter = seq->private;
3239 struct sock *sk;
3240
3241 /* Whenever seq_next() is called, the iter->cur_sk is
3242 * done with seq_show(), so unref the iter->cur_sk.
3243 */
3244 if (iter->cur_sk < iter->end_sk) {
3245 sock_put(iter->batch[iter->cur_sk++]);
3246 ++iter->offset;
3247 }
3248
3249 /* After updating iter->cur_sk, check if there are more sockets
3250 * available in the current bucket batch.
3251 */
3252 if (iter->cur_sk < iter->end_sk)
3253 sk = iter->batch[iter->cur_sk];
3254 else
3255 /* Prepare a new batch. */
3256 sk = bpf_iter_udp_batch(seq);
3257
3258 ++*pos;
3259 return sk;
3260 }
3261
bpf_iter_udp_seq_start(struct seq_file * seq,loff_t * pos)3262 static void *bpf_iter_udp_seq_start(struct seq_file *seq, loff_t *pos)
3263 {
3264 /* bpf iter does not support lseek, so it always
3265 * continue from where it was stop()-ped.
3266 */
3267 if (*pos)
3268 return bpf_iter_udp_batch(seq);
3269
3270 return SEQ_START_TOKEN;
3271 }
3272
udp_prog_seq_show(struct bpf_prog * prog,struct bpf_iter_meta * meta,struct udp_sock * udp_sk,uid_t uid,int bucket)3273 static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
3274 struct udp_sock *udp_sk, uid_t uid, int bucket)
3275 {
3276 struct bpf_iter__udp ctx;
3277
3278 meta->seq_num--; /* skip SEQ_START_TOKEN */
3279 ctx.meta = meta;
3280 ctx.udp_sk = udp_sk;
3281 ctx.uid = uid;
3282 ctx.bucket = bucket;
3283 return bpf_iter_run_prog(prog, &ctx);
3284 }
3285
bpf_iter_udp_seq_show(struct seq_file * seq,void * v)3286 static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v)
3287 {
3288 struct udp_iter_state *state = seq->private;
3289 struct bpf_iter_meta meta;
3290 struct bpf_prog *prog;
3291 struct sock *sk = v;
3292 uid_t uid;
3293 int ret;
3294
3295 if (v == SEQ_START_TOKEN)
3296 return 0;
3297
3298 lock_sock(sk);
3299
3300 if (unlikely(sk_unhashed(sk))) {
3301 ret = SEQ_SKIP;
3302 goto unlock;
3303 }
3304
3305 uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
3306 meta.seq = seq;
3307 prog = bpf_iter_get_info(&meta, false);
3308 ret = udp_prog_seq_show(prog, &meta, v, uid, state->bucket);
3309
3310 unlock:
3311 release_sock(sk);
3312 return ret;
3313 }
3314
bpf_iter_udp_put_batch(struct bpf_udp_iter_state * iter)3315 static void bpf_iter_udp_put_batch(struct bpf_udp_iter_state *iter)
3316 {
3317 while (iter->cur_sk < iter->end_sk)
3318 sock_put(iter->batch[iter->cur_sk++]);
3319 }
3320
bpf_iter_udp_seq_stop(struct seq_file * seq,void * v)3321 static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v)
3322 {
3323 struct bpf_udp_iter_state *iter = seq->private;
3324 struct bpf_iter_meta meta;
3325 struct bpf_prog *prog;
3326
3327 if (!v) {
3328 meta.seq = seq;
3329 prog = bpf_iter_get_info(&meta, true);
3330 if (prog)
3331 (void)udp_prog_seq_show(prog, &meta, v, 0, 0);
3332 }
3333
3334 if (iter->cur_sk < iter->end_sk) {
3335 bpf_iter_udp_put_batch(iter);
3336 iter->st_bucket_done = false;
3337 }
3338 }
3339
3340 static const struct seq_operations bpf_iter_udp_seq_ops = {
3341 .start = bpf_iter_udp_seq_start,
3342 .next = bpf_iter_udp_seq_next,
3343 .stop = bpf_iter_udp_seq_stop,
3344 .show = bpf_iter_udp_seq_show,
3345 };
3346 #endif
3347
seq_file_family(const struct seq_file * seq)3348 static unsigned short seq_file_family(const struct seq_file *seq)
3349 {
3350 const struct udp_seq_afinfo *afinfo;
3351
3352 #ifdef CONFIG_BPF_SYSCALL
3353 /* BPF iterator: bpf programs to filter sockets. */
3354 if (seq->op == &bpf_iter_udp_seq_ops)
3355 return AF_UNSPEC;
3356 #endif
3357
3358 /* Proc fs iterator */
3359 afinfo = pde_data(file_inode(seq->file));
3360 return afinfo->family;
3361 }
3362
3363 const struct seq_operations udp_seq_ops = {
3364 .start = udp_seq_start,
3365 .next = udp_seq_next,
3366 .stop = udp_seq_stop,
3367 .show = udp4_seq_show,
3368 };
3369 EXPORT_SYMBOL(udp_seq_ops);
3370
3371 static struct udp_seq_afinfo udp4_seq_afinfo = {
3372 .family = AF_INET,
3373 .udp_table = NULL,
3374 };
3375
udp4_proc_init_net(struct net * net)3376 static int __net_init udp4_proc_init_net(struct net *net)
3377 {
3378 if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops,
3379 sizeof(struct udp_iter_state), &udp4_seq_afinfo))
3380 return -ENOMEM;
3381 return 0;
3382 }
3383
udp4_proc_exit_net(struct net * net)3384 static void __net_exit udp4_proc_exit_net(struct net *net)
3385 {
3386 remove_proc_entry("udp", net->proc_net);
3387 }
3388
3389 static struct pernet_operations udp4_net_ops = {
3390 .init = udp4_proc_init_net,
3391 .exit = udp4_proc_exit_net,
3392 };
3393
udp4_proc_init(void)3394 int __init udp4_proc_init(void)
3395 {
3396 return register_pernet_subsys(&udp4_net_ops);
3397 }
3398
udp4_proc_exit(void)3399 void udp4_proc_exit(void)
3400 {
3401 unregister_pernet_subsys(&udp4_net_ops);
3402 }
3403 #endif /* CONFIG_PROC_FS */
3404
3405 static __initdata unsigned long uhash_entries;
set_uhash_entries(char * str)3406 static int __init set_uhash_entries(char *str)
3407 {
3408 ssize_t ret;
3409
3410 if (!str)
3411 return 0;
3412
3413 ret = kstrtoul(str, 0, &uhash_entries);
3414 if (ret)
3415 return 0;
3416
3417 if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
3418 uhash_entries = UDP_HTABLE_SIZE_MIN;
3419 return 1;
3420 }
3421 __setup("uhash_entries=", set_uhash_entries);
3422
udp_table_init(struct udp_table * table,const char * name)3423 void __init udp_table_init(struct udp_table *table, const char *name)
3424 {
3425 unsigned int i;
3426
3427 table->hash = alloc_large_system_hash(name,
3428 2 * sizeof(struct udp_hslot),
3429 uhash_entries,
3430 21, /* one slot per 2 MB */
3431 0,
3432 &table->log,
3433 &table->mask,
3434 UDP_HTABLE_SIZE_MIN,
3435 UDP_HTABLE_SIZE_MAX);
3436
3437 table->hash2 = table->hash + (table->mask + 1);
3438 for (i = 0; i <= table->mask; i++) {
3439 INIT_HLIST_HEAD(&table->hash[i].head);
3440 table->hash[i].count = 0;
3441 spin_lock_init(&table->hash[i].lock);
3442 }
3443 for (i = 0; i <= table->mask; i++) {
3444 INIT_HLIST_HEAD(&table->hash2[i].head);
3445 table->hash2[i].count = 0;
3446 spin_lock_init(&table->hash2[i].lock);
3447 }
3448 }
3449
udp_flow_hashrnd(void)3450 u32 udp_flow_hashrnd(void)
3451 {
3452 static u32 hashrnd __read_mostly;
3453
3454 net_get_random_once(&hashrnd, sizeof(hashrnd));
3455
3456 return hashrnd;
3457 }
3458 EXPORT_SYMBOL(udp_flow_hashrnd);
3459
udp_sysctl_init(struct net * net)3460 static void __net_init udp_sysctl_init(struct net *net)
3461 {
3462 net->ipv4.sysctl_udp_rmem_min = PAGE_SIZE;
3463 net->ipv4.sysctl_udp_wmem_min = PAGE_SIZE;
3464
3465 #ifdef CONFIG_NET_L3_MASTER_DEV
3466 net->ipv4.sysctl_udp_l3mdev_accept = 0;
3467 #endif
3468 }
3469
udp_pernet_table_alloc(unsigned int hash_entries)3470 static struct udp_table __net_init *udp_pernet_table_alloc(unsigned int hash_entries)
3471 {
3472 struct udp_table *udptable;
3473 int i;
3474
3475 udptable = kmalloc(sizeof(*udptable), GFP_KERNEL);
3476 if (!udptable)
3477 goto out;
3478
3479 udptable->hash = vmalloc_huge(hash_entries * 2 * sizeof(struct udp_hslot),
3480 GFP_KERNEL_ACCOUNT);
3481 if (!udptable->hash)
3482 goto free_table;
3483
3484 udptable->hash2 = udptable->hash + hash_entries;
3485 udptable->mask = hash_entries - 1;
3486 udptable->log = ilog2(hash_entries);
3487
3488 for (i = 0; i < hash_entries; i++) {
3489 INIT_HLIST_HEAD(&udptable->hash[i].head);
3490 udptable->hash[i].count = 0;
3491 spin_lock_init(&udptable->hash[i].lock);
3492
3493 INIT_HLIST_HEAD(&udptable->hash2[i].head);
3494 udptable->hash2[i].count = 0;
3495 spin_lock_init(&udptable->hash2[i].lock);
3496 }
3497
3498 return udptable;
3499
3500 free_table:
3501 kfree(udptable);
3502 out:
3503 return NULL;
3504 }
3505
udp_pernet_table_free(struct net * net)3506 static void __net_exit udp_pernet_table_free(struct net *net)
3507 {
3508 struct udp_table *udptable = net->ipv4.udp_table;
3509
3510 if (udptable == &udp_table)
3511 return;
3512
3513 kvfree(udptable->hash);
3514 kfree(udptable);
3515 }
3516
udp_set_table(struct net * net)3517 static void __net_init udp_set_table(struct net *net)
3518 {
3519 struct udp_table *udptable;
3520 unsigned int hash_entries;
3521 struct net *old_net;
3522
3523 if (net_eq(net, &init_net))
3524 goto fallback;
3525
3526 old_net = current->nsproxy->net_ns;
3527 hash_entries = READ_ONCE(old_net->ipv4.sysctl_udp_child_hash_entries);
3528 if (!hash_entries)
3529 goto fallback;
3530
3531 /* Set min to keep the bitmap on stack in udp_lib_get_port() */
3532 if (hash_entries < UDP_HTABLE_SIZE_MIN_PERNET)
3533 hash_entries = UDP_HTABLE_SIZE_MIN_PERNET;
3534 else
3535 hash_entries = roundup_pow_of_two(hash_entries);
3536
3537 udptable = udp_pernet_table_alloc(hash_entries);
3538 if (udptable) {
3539 net->ipv4.udp_table = udptable;
3540 } else {
3541 pr_warn("Failed to allocate UDP hash table (entries: %u) "
3542 "for a netns, fallback to the global one\n",
3543 hash_entries);
3544 fallback:
3545 net->ipv4.udp_table = &udp_table;
3546 }
3547 }
3548
udp_pernet_init(struct net * net)3549 static int __net_init udp_pernet_init(struct net *net)
3550 {
3551 udp_sysctl_init(net);
3552 udp_set_table(net);
3553
3554 return 0;
3555 }
3556
udp_pernet_exit(struct net * net)3557 static void __net_exit udp_pernet_exit(struct net *net)
3558 {
3559 udp_pernet_table_free(net);
3560 }
3561
3562 static struct pernet_operations __net_initdata udp_sysctl_ops = {
3563 .init = udp_pernet_init,
3564 .exit = udp_pernet_exit,
3565 };
3566
3567 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
DEFINE_BPF_ITER_FUNC(udp,struct bpf_iter_meta * meta,struct udp_sock * udp_sk,uid_t uid,int bucket)3568 DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta,
3569 struct udp_sock *udp_sk, uid_t uid, int bucket)
3570
3571 static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter,
3572 unsigned int new_batch_sz)
3573 {
3574 struct sock **new_batch;
3575
3576 new_batch = kvmalloc_array(new_batch_sz, sizeof(*new_batch),
3577 GFP_USER | __GFP_NOWARN);
3578 if (!new_batch)
3579 return -ENOMEM;
3580
3581 bpf_iter_udp_put_batch(iter);
3582 kvfree(iter->batch);
3583 iter->batch = new_batch;
3584 iter->max_sk = new_batch_sz;
3585
3586 return 0;
3587 }
3588
3589 #define INIT_BATCH_SZ 16
3590
bpf_iter_init_udp(void * priv_data,struct bpf_iter_aux_info * aux)3591 static int bpf_iter_init_udp(void *priv_data, struct bpf_iter_aux_info *aux)
3592 {
3593 struct bpf_udp_iter_state *iter = priv_data;
3594 int ret;
3595
3596 ret = bpf_iter_init_seq_net(priv_data, aux);
3597 if (ret)
3598 return ret;
3599
3600 ret = bpf_iter_udp_realloc_batch(iter, INIT_BATCH_SZ);
3601 if (ret)
3602 bpf_iter_fini_seq_net(priv_data);
3603
3604 return ret;
3605 }
3606
bpf_iter_fini_udp(void * priv_data)3607 static void bpf_iter_fini_udp(void *priv_data)
3608 {
3609 struct bpf_udp_iter_state *iter = priv_data;
3610
3611 bpf_iter_fini_seq_net(priv_data);
3612 kvfree(iter->batch);
3613 }
3614
3615 static const struct bpf_iter_seq_info udp_seq_info = {
3616 .seq_ops = &bpf_iter_udp_seq_ops,
3617 .init_seq_private = bpf_iter_init_udp,
3618 .fini_seq_private = bpf_iter_fini_udp,
3619 .seq_priv_size = sizeof(struct bpf_udp_iter_state),
3620 };
3621
3622 static struct bpf_iter_reg udp_reg_info = {
3623 .target = "udp",
3624 .ctx_arg_info_size = 1,
3625 .ctx_arg_info = {
3626 { offsetof(struct bpf_iter__udp, udp_sk),
3627 PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED },
3628 },
3629 .seq_info = &udp_seq_info,
3630 };
3631
bpf_iter_register(void)3632 static void __init bpf_iter_register(void)
3633 {
3634 udp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UDP];
3635 if (bpf_iter_reg_target(&udp_reg_info))
3636 pr_warn("Warning: could not register bpf iterator udp\n");
3637 }
3638 #endif
3639
udp_init(void)3640 void __init udp_init(void)
3641 {
3642 unsigned long limit;
3643 unsigned int i;
3644
3645 udp_table_init(&udp_table, "UDP");
3646 limit = nr_free_buffer_pages() / 8;
3647 limit = max(limit, 128UL);
3648 sysctl_udp_mem[0] = limit / 4 * 3;
3649 sysctl_udp_mem[1] = limit;
3650 sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
3651
3652 /* 16 spinlocks per cpu */
3653 udp_busylocks_log = ilog2(nr_cpu_ids) + 4;
3654 udp_busylocks = kmalloc(sizeof(spinlock_t) << udp_busylocks_log,
3655 GFP_KERNEL);
3656 if (!udp_busylocks)
3657 panic("UDP: failed to alloc udp_busylocks\n");
3658 for (i = 0; i < (1U << udp_busylocks_log); i++)
3659 spin_lock_init(udp_busylocks + i);
3660
3661 if (register_pernet_subsys(&udp_sysctl_ops))
3662 panic("UDP: failed to init sysctl parameters.\n");
3663
3664 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3665 bpf_iter_register();
3666 #endif
3667 }
3668