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