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