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