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