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