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 Encapsulation Support 72 * James Chapman : Add L2TP encapsulation type. 73 */ 74 75 #define pr_fmt(fmt) "UDP: " fmt 76 77 #include <linux/bpf-cgroup.h> 78 #include <linux/uaccess.h> 79 #include <asm/ioctls.h> 80 #include <linux/memblock.h> 81 #include <linux/highmem.h> 82 #include <linux/types.h> 83 #include <linux/fcntl.h> 84 #include <linux/module.h> 85 #include <linux/socket.h> 86 #include <linux/sockios.h> 87 #include <linux/igmp.h> 88 #include <linux/inetdevice.h> 89 #include <linux/in.h> 90 #include <linux/errno.h> 91 #include <linux/timer.h> 92 #include <linux/mm.h> 93 #include <linux/inet.h> 94 #include <linux/netdevice.h> 95 #include <linux/slab.h> 96 #include <linux/sock_diag.h> 97 #include <net/tcp_states.h> 98 #include <linux/skbuff.h> 99 #include <linux/proc_fs.h> 100 #include <linux/seq_file.h> 101 #include <net/aligned_data.h> 102 #include <net/net_namespace.h> 103 #include <net/icmp.h> 104 #include <net/inet_common.h> 105 #include <net/inet_hashtables.h> 106 #include <net/ip.h> 107 #include <net/ip_tunnels.h> 108 #include <net/route.h> 109 #include <net/checksum.h> 110 #include <net/gso.h> 111 #include <net/xfrm.h> 112 #include <trace/events/udp.h> 113 #include <linux/static_key.h> 114 #include <linux/btf_ids.h> 115 #include <trace/events/skb.h> 116 #include <net/busy_poll.h> 117 #include <net/sock_reuseport.h> 118 #include <net/addrconf.h> 119 #include <net/udp_tunnel.h> 120 #include <net/gro.h> 121 #include <net/rps.h> 122 123 struct udp_table udp_table __read_mostly; 124 125 long sysctl_udp_mem[3] __read_mostly; 126 127 DEFINE_PER_CPU(int, udp_memory_per_cpu_fw_alloc); 128 EXPORT_PER_CPU_SYMBOL_GPL(udp_memory_per_cpu_fw_alloc); 129 130 #define MAX_UDP_PORTS 65536 131 #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN_PERNET) 132 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 kuid_t uid = sk_uid(sk); 139 struct sock *sk2; 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, sk_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 */ 169 static int udp_lib_lport_inuse2(struct net *net, __u16 num, 170 struct udp_hslot *hslot2, 171 struct sock *sk) 172 { 173 kuid_t uid = sk_uid(sk); 174 struct sock *sk2; 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, sk_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 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 = sk_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, sk_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 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 */ 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 net *net = sock_net(sk); 236 struct udp_table *udptable; 237 int error = -EADDRINUSE; 238 239 udptable = net->ipv4.udp_table; 240 241 if (!snum) { 242 DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN); 243 unsigned short first, last; 244 int low, high, remaining; 245 unsigned int rand; 246 247 inet_sk_get_local_port_range(sk, &low, &high); 248 remaining = (high - low) + 1; 249 250 rand = get_random_u32(); 251 first = reciprocal_scale(rand, remaining) + low; 252 /* 253 * force rand to be an odd multiple of UDP_HTABLE_SIZE 254 */ 255 rand = (rand | 1) * (udptable->mask + 1); 256 last = first + udptable->mask + 1; 257 do { 258 hslot = udp_hashslot(udptable, net, first); 259 bitmap_zero(bitmap, PORTS_PER_CHAIN); 260 spin_lock_bh(&hslot->lock); 261 udp_lib_lport_inuse(net, snum, hslot, bitmap, sk, 262 udptable->log); 263 264 snum = first; 265 /* 266 * Iterate on all possible values of snum for this hash. 267 * Using steps of an odd multiple of UDP_HTABLE_SIZE 268 * give us randomization and full range coverage. 269 */ 270 do { 271 if (low <= snum && snum <= high && 272 !test_bit(snum >> udptable->log, bitmap) && 273 !inet_is_local_reserved_port(net, snum)) 274 goto found; 275 snum += rand; 276 } while (snum != first); 277 spin_unlock_bh(&hslot->lock); 278 cond_resched(); 279 } while (++first != last); 280 goto fail; 281 } else { 282 hslot = udp_hashslot(udptable, net, snum); 283 spin_lock_bh(&hslot->lock); 284 if (inet_use_hash2_on_bind(sk) && hslot->count > 10) { 285 int exist; 286 unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum; 287 288 slot2 &= udptable->mask; 289 hash2_nulladdr &= udptable->mask; 290 291 hslot2 = udp_hashslot2(udptable, slot2); 292 if (hslot->count < hslot2->count) 293 goto scan_primary_hash; 294 295 exist = udp_lib_lport_inuse2(net, snum, hslot2, sk); 296 if (!exist && (hash2_nulladdr != slot2)) { 297 hslot2 = udp_hashslot2(udptable, hash2_nulladdr); 298 exist = udp_lib_lport_inuse2(net, snum, hslot2, 299 sk); 300 } 301 if (exist) 302 goto fail_unlock; 303 else 304 goto found; 305 } 306 scan_primary_hash: 307 if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, 0)) 308 goto fail_unlock; 309 } 310 found: 311 inet_sk(sk)->inet_num = snum; 312 udp_sk(sk)->udp_port_hash = snum; 313 udp_sk(sk)->udp_portaddr_hash ^= snum; 314 if (sk_unhashed(sk)) { 315 if (sk->sk_reuseport && 316 udp_reuseport_add_sock(sk, hslot)) { 317 inet_sk(sk)->inet_num = 0; 318 udp_sk(sk)->udp_port_hash = 0; 319 udp_sk(sk)->udp_portaddr_hash ^= snum; 320 goto fail_unlock; 321 } 322 323 sock_set_flag(sk, SOCK_RCU_FREE); 324 325 sk_add_node_rcu(sk, &hslot->head); 326 hslot->count++; 327 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1); 328 329 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); 330 spin_lock(&hslot2->lock); 331 if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport && 332 sk->sk_family == AF_INET6) 333 hlist_add_tail_rcu(&udp_sk(sk)->udp_portaddr_node, 334 &hslot2->head); 335 else 336 hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node, 337 &hslot2->head); 338 hslot2->count++; 339 spin_unlock(&hslot2->lock); 340 } 341 342 error = 0; 343 fail_unlock: 344 spin_unlock_bh(&hslot->lock); 345 fail: 346 return error; 347 } 348 349 static int udp_v4_get_port(struct sock *sk, unsigned short snum) 350 { 351 unsigned int hash2_nulladdr = 352 ipv4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum); 353 unsigned int hash2_partial = 354 ipv4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0); 355 356 /* precompute partial secondary hash */ 357 udp_sk(sk)->udp_portaddr_hash = hash2_partial; 358 return udp_lib_get_port(sk, snum, hash2_nulladdr); 359 } 360 361 static __always_inline int 362 compute_score(struct sock *sk, const struct net *net, 363 __be32 saddr, __be16 sport, __be32 daddr, 364 unsigned short hnum, int dif, int sdif) 365 { 366 int score; 367 struct inet_sock *inet; 368 bool dev_match; 369 370 if (!net_eq(sock_net(sk), net) || 371 udp_sk(sk)->udp_port_hash != hnum || 372 ipv6_only_sock(sk)) 373 return -1; 374 375 if (sk->sk_rcv_saddr != daddr) 376 return -1; 377 378 score = (sk->sk_family == PF_INET) ? 2 : 1; 379 380 inet = inet_sk(sk); 381 if (inet->inet_daddr) { 382 if (inet->inet_daddr != saddr) 383 return -1; 384 score += 4; 385 } 386 387 if (inet->inet_dport) { 388 if (inet->inet_dport != sport) 389 return -1; 390 score += 4; 391 } 392 393 dev_match = udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, 394 dif, sdif); 395 if (!dev_match) 396 return -1; 397 if (sk->sk_bound_dev_if) 398 score += 4; 399 400 if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id()) 401 score++; 402 return score; 403 } 404 405 u32 udp_ehashfn(const struct net *net, const __be32 laddr, const __u16 lport, 406 const __be32 faddr, const __be16 fport) 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 414 /** 415 * udp4_lib_lookup1() - Simplified lookup using primary hash (destination port) 416 * @net: Network namespace 417 * @saddr: Source address, network order 418 * @sport: Source port, network order 419 * @daddr: Destination address, network order 420 * @hnum: Destination port, host order 421 * @dif: Destination interface index 422 * @sdif: Destination bridge port index, if relevant 423 * @udptable: Set of UDP hash tables 424 * 425 * Simplified lookup to be used as fallback if no sockets are found due to a 426 * potential race between (receive) address change, and lookup happening before 427 * the rehash operation. This function ignores SO_REUSEPORT groups while scoring 428 * result sockets, because if we have one, we don't need the fallback at all. 429 * 430 * Called under rcu_read_lock(). 431 * 432 * Return: socket with highest matching score if any, NULL if none 433 */ 434 static struct sock *udp4_lib_lookup1(const struct net *net, 435 __be32 saddr, __be16 sport, 436 __be32 daddr, unsigned int hnum, 437 int dif, int sdif, 438 const struct udp_table *udptable) 439 { 440 unsigned int slot = udp_hashfn(net, hnum, udptable->mask); 441 struct udp_hslot *hslot = &udptable->hash[slot]; 442 struct sock *sk, *result = NULL; 443 int score, badness = 0; 444 445 sk_for_each_rcu(sk, &hslot->head) { 446 score = compute_score(sk, net, 447 saddr, sport, daddr, hnum, dif, sdif); 448 if (score > badness) { 449 result = sk; 450 badness = score; 451 } 452 } 453 454 return result; 455 } 456 457 /* called with rcu_read_lock() */ 458 static struct sock *udp4_lib_lookup2(const struct net *net, 459 __be32 saddr, __be16 sport, 460 __be32 daddr, unsigned int hnum, 461 int dif, int sdif, 462 struct udp_hslot *hslot2, 463 struct sk_buff *skb) 464 { 465 struct sock *sk, *result; 466 int score, badness; 467 bool need_rescore; 468 469 result = NULL; 470 badness = 0; 471 udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) { 472 need_rescore = false; 473 rescore: 474 score = compute_score(need_rescore ? result : sk, net, saddr, 475 sport, daddr, hnum, dif, sdif); 476 if (score > badness) { 477 badness = score; 478 479 if (need_rescore) 480 continue; 481 482 if (sk->sk_state == TCP_ESTABLISHED) { 483 result = sk; 484 continue; 485 } 486 487 result = inet_lookup_reuseport(net, sk, skb, sizeof(struct udphdr), 488 saddr, sport, daddr, hnum, udp_ehashfn); 489 if (!result) { 490 result = sk; 491 continue; 492 } 493 494 /* Fall back to scoring if group has connections */ 495 if (!reuseport_has_conns(sk)) 496 return result; 497 498 /* Reuseport logic returned an error, keep original score. */ 499 if (IS_ERR(result)) 500 continue; 501 502 /* compute_score is too long of a function to be 503 * inlined twice here, and calling it uninlined 504 * here yields measurable overhead for some 505 * workloads. Work around it by jumping 506 * backwards to rescore 'result'. 507 */ 508 need_rescore = true; 509 goto rescore; 510 } 511 } 512 return result; 513 } 514 515 #if IS_ENABLED(CONFIG_BASE_SMALL) 516 static struct sock *udp4_lib_lookup4(const struct net *net, 517 __be32 saddr, __be16 sport, 518 __be32 daddr, unsigned int hnum, 519 int dif, int sdif, 520 struct udp_table *udptable) 521 { 522 return NULL; 523 } 524 525 static void udp_rehash4(struct udp_table *udptable, struct sock *sk, 526 u16 newhash4) 527 { 528 } 529 530 static void udp_unhash4(struct udp_table *udptable, struct sock *sk) 531 { 532 } 533 #else /* !CONFIG_BASE_SMALL */ 534 static struct sock *udp4_lib_lookup4(const struct net *net, 535 __be32 saddr, __be16 sport, 536 __be32 daddr, unsigned int hnum, 537 int dif, int sdif, 538 struct udp_table *udptable) 539 { 540 const __portpair ports = INET_COMBINED_PORTS(sport, hnum); 541 const struct hlist_nulls_node *node; 542 struct udp_hslot *hslot4; 543 unsigned int hash4, slot; 544 struct udp_sock *up; 545 struct sock *sk; 546 547 hash4 = udp_ehashfn(net, daddr, hnum, saddr, sport); 548 slot = hash4 & udptable->mask; 549 hslot4 = &udptable->hash4[slot]; 550 INET_ADDR_COOKIE(acookie, saddr, daddr); 551 552 begin: 553 /* SLAB_TYPESAFE_BY_RCU not used, so we don't need to touch sk_refcnt */ 554 udp_lrpa_for_each_entry_rcu(up, node, &hslot4->nulls_head) { 555 sk = (struct sock *)up; 556 if (inet_match(net, sk, acookie, ports, dif, sdif)) 557 return sk; 558 } 559 560 /* if the nulls value we got at the end of this lookup is not the 561 * expected one, we must restart lookup. We probably met an item that 562 * was moved to another chain due to rehash. 563 */ 564 if (get_nulls_value(node) != slot) 565 goto begin; 566 567 return NULL; 568 } 569 570 /* udp_rehash4() only checks hslot4, and hash4_cnt is not processed. */ 571 static void udp_rehash4(struct udp_table *udptable, struct sock *sk, 572 u16 newhash4) 573 { 574 struct udp_hslot *hslot4, *nhslot4; 575 576 hslot4 = udp_hashslot4(udptable, udp_sk(sk)->udp_lrpa_hash); 577 nhslot4 = udp_hashslot4(udptable, newhash4); 578 udp_sk(sk)->udp_lrpa_hash = newhash4; 579 580 if (hslot4 != nhslot4) { 581 spin_lock_bh(&hslot4->lock); 582 hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_lrpa_node); 583 hslot4->count--; 584 spin_unlock_bh(&hslot4->lock); 585 586 spin_lock_bh(&nhslot4->lock); 587 hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_lrpa_node, 588 &nhslot4->nulls_head); 589 nhslot4->count++; 590 spin_unlock_bh(&nhslot4->lock); 591 } 592 } 593 594 static void udp_unhash4(struct udp_table *udptable, struct sock *sk) 595 { 596 struct udp_hslot *hslot2, *hslot4; 597 598 if (udp_hashed4(sk)) { 599 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); 600 hslot4 = udp_hashslot4(udptable, udp_sk(sk)->udp_lrpa_hash); 601 602 spin_lock(&hslot4->lock); 603 hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_lrpa_node); 604 hslot4->count--; 605 spin_unlock(&hslot4->lock); 606 607 spin_lock(&hslot2->lock); 608 udp_hash4_dec(hslot2); 609 spin_unlock(&hslot2->lock); 610 } 611 } 612 613 void udp_lib_hash4(struct sock *sk, u16 hash) 614 { 615 struct udp_hslot *hslot, *hslot2, *hslot4; 616 struct net *net = sock_net(sk); 617 struct udp_table *udptable; 618 619 /* Connected udp socket can re-connect to another remote address, which 620 * will be handled by rehash. Thus no need to redo hash4 here. 621 */ 622 if (udp_hashed4(sk)) 623 return; 624 625 udptable = net->ipv4.udp_table; 626 hslot = udp_hashslot(udptable, net, udp_sk(sk)->udp_port_hash); 627 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); 628 hslot4 = udp_hashslot4(udptable, hash); 629 udp_sk(sk)->udp_lrpa_hash = hash; 630 631 spin_lock_bh(&hslot->lock); 632 if (rcu_access_pointer(sk->sk_reuseport_cb)) 633 reuseport_detach_sock(sk); 634 635 spin_lock(&hslot4->lock); 636 hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_lrpa_node, 637 &hslot4->nulls_head); 638 hslot4->count++; 639 spin_unlock(&hslot4->lock); 640 641 spin_lock(&hslot2->lock); 642 udp_hash4_inc(hslot2); 643 spin_unlock(&hslot2->lock); 644 645 spin_unlock_bh(&hslot->lock); 646 } 647 648 /* call with sock lock */ 649 void udp4_hash4(struct sock *sk) 650 { 651 struct net *net = sock_net(sk); 652 unsigned int hash; 653 654 if (sk_unhashed(sk) || sk->sk_rcv_saddr == htonl(INADDR_ANY)) 655 return; 656 657 hash = udp_ehashfn(net, sk->sk_rcv_saddr, sk->sk_num, 658 sk->sk_daddr, sk->sk_dport); 659 660 udp_lib_hash4(sk, hash); 661 } 662 #endif /* CONFIG_BASE_SMALL */ 663 664 /* UDP is nearly always wildcards out the wazoo, it makes no sense to try 665 * harder than this. -DaveM 666 */ 667 struct sock *__udp4_lib_lookup(const struct net *net, __be32 saddr, 668 __be16 sport, __be32 daddr, __be16 dport, 669 int dif, int sdif, struct sk_buff *skb) 670 { 671 struct udp_table *udptable = net->ipv4.udp_table; 672 unsigned short hnum = ntohs(dport); 673 struct udp_hslot *hslot2; 674 struct sock *result, *sk; 675 unsigned int hash2; 676 677 hash2 = ipv4_portaddr_hash(net, daddr, hnum); 678 hslot2 = udp_hashslot2(udptable, hash2); 679 680 if (udp_has_hash4(hslot2)) { 681 result = udp4_lib_lookup4(net, saddr, sport, daddr, hnum, 682 dif, sdif, udptable); 683 if (result) /* udp4_lib_lookup4 return sk or NULL */ 684 return result; 685 } 686 687 /* Lookup connected or non-wildcard socket */ 688 result = udp4_lib_lookup2(net, saddr, sport, 689 daddr, hnum, dif, sdif, 690 hslot2, skb); 691 if (!IS_ERR_OR_NULL(result) && result->sk_state == TCP_ESTABLISHED) 692 goto done; 693 694 /* Lookup redirect from BPF */ 695 if (static_branch_unlikely(&bpf_sk_lookup_enabled)) { 696 sk = inet_lookup_run_sk_lookup(net, IPPROTO_UDP, skb, sizeof(struct udphdr), 697 saddr, sport, daddr, hnum, dif, 698 udp_ehashfn); 699 if (sk) { 700 result = sk; 701 goto done; 702 } 703 } 704 705 /* Got non-wildcard socket or error on first lookup */ 706 if (result) 707 goto done; 708 709 /* Lookup wildcard sockets */ 710 hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum); 711 hslot2 = udp_hashslot2(udptable, hash2); 712 713 result = udp4_lib_lookup2(net, saddr, sport, 714 htonl(INADDR_ANY), hnum, dif, sdif, 715 hslot2, skb); 716 if (!IS_ERR_OR_NULL(result)) 717 goto done; 718 719 /* Primary hash (destination port) lookup as fallback for this race: 720 * 1. __ip4_datagram_connect() sets sk_rcv_saddr 721 * 2. lookup (this function): new sk_rcv_saddr, hashes not updated yet 722 * 3. rehash operation updating _secondary and four-tuple_ hashes 723 * The primary hash doesn't need an update after 1., so, thanks to this 724 * further step, 1. and 3. don't need to be atomic against the lookup. 725 */ 726 result = udp4_lib_lookup1(net, saddr, sport, daddr, hnum, dif, sdif, 727 udptable); 728 729 done: 730 if (IS_ERR(result)) 731 return NULL; 732 return result; 733 } 734 EXPORT_SYMBOL_GPL(__udp4_lib_lookup); 735 736 static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb, 737 __be16 sport, __be16 dport) 738 { 739 const struct iphdr *iph = ip_hdr(skb); 740 741 return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport, 742 iph->daddr, dport, inet_iif(skb), 743 inet_sdif(skb), skb); 744 } 745 746 struct sock *udp4_lib_lookup_skb(const struct sk_buff *skb, 747 __be16 sport, __be16 dport) 748 { 749 const u16 offset = NAPI_GRO_CB(skb)->network_offsets[skb->encapsulation]; 750 const struct iphdr *iph = (struct iphdr *)(skb->data + offset); 751 int iif, sdif; 752 753 inet_get_iif_sdif(skb, &iif, &sdif); 754 755 return __udp4_lib_lookup(dev_net(skb->dev), iph->saddr, sport, 756 iph->daddr, dport, iif, sdif, NULL); 757 } 758 759 /* Must be called under rcu_read_lock(). 760 * Does increment socket refcount. 761 */ 762 #if IS_ENABLED(CONFIG_NF_TPROXY_IPV4) || IS_ENABLED(CONFIG_NF_SOCKET_IPV4) 763 struct sock *udp4_lib_lookup(const struct net *net, __be32 saddr, __be16 sport, 764 __be32 daddr, __be16 dport, int dif) 765 { 766 struct sock *sk; 767 768 sk = __udp4_lib_lookup(net, saddr, sport, daddr, dport, dif, 0, NULL); 769 if (sk && !refcount_inc_not_zero(&sk->sk_refcnt)) 770 sk = NULL; 771 return sk; 772 } 773 EXPORT_SYMBOL_GPL(udp4_lib_lookup); 774 #endif 775 776 static inline bool __udp_is_mcast_sock(struct net *net, const struct sock *sk, 777 __be16 loc_port, __be32 loc_addr, 778 __be16 rmt_port, __be32 rmt_addr, 779 int dif, int sdif, unsigned short hnum) 780 { 781 const struct inet_sock *inet = inet_sk(sk); 782 783 if (!net_eq(sock_net(sk), net) || 784 udp_sk(sk)->udp_port_hash != hnum || 785 (inet->inet_daddr && inet->inet_daddr != rmt_addr) || 786 (inet->inet_dport != rmt_port && inet->inet_dport) || 787 (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) || 788 ipv6_only_sock(sk) || 789 !udp_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif)) 790 return false; 791 if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif, sdif)) 792 return false; 793 return true; 794 } 795 796 DEFINE_STATIC_KEY_FALSE(udp_encap_needed_key); 797 798 #if IS_ENABLED(CONFIG_IPV6) 799 DEFINE_STATIC_KEY_FALSE(udpv6_encap_needed_key); 800 #endif 801 802 void udp_encap_enable(void) 803 { 804 static_branch_inc(&udp_encap_needed_key); 805 } 806 EXPORT_SYMBOL(udp_encap_enable); 807 808 void udp_encap_disable(void) 809 { 810 static_branch_dec(&udp_encap_needed_key); 811 } 812 EXPORT_SYMBOL(udp_encap_disable); 813 814 /* Handler for tunnels with arbitrary destination ports: no socket lookup, go 815 * through error handlers in encapsulations looking for a match. 816 */ 817 static int __udp4_lib_err_encap_no_sk(struct sk_buff *skb, u32 info) 818 { 819 int i; 820 821 for (i = 0; i < MAX_IPTUN_ENCAP_OPS; i++) { 822 int (*handler)(struct sk_buff *skb, u32 info); 823 const struct ip_tunnel_encap_ops *encap; 824 825 encap = rcu_dereference(iptun_encaps[i]); 826 if (!encap) 827 continue; 828 handler = encap->err_handler; 829 if (handler && !handler(skb, info)) 830 return 0; 831 } 832 833 return -ENOENT; 834 } 835 836 /* Try to match ICMP errors to UDP tunnels by looking up a socket without 837 * reversing source and destination port: this will match tunnels that force the 838 * same destination port on both endpoints (e.g. VXLAN, GENEVE). Note that 839 * lwtunnels might actually break this assumption by being configured with 840 * different destination ports on endpoints, in this case we won't be able to 841 * trace ICMP messages back to them. 842 * 843 * If this doesn't match any socket, probe tunnels with arbitrary destination 844 * ports (e.g. FoU, GUE): there, the receiving socket is useless, as the port 845 * we've sent packets to won't necessarily match the local destination port. 846 * 847 * Then ask the tunnel implementation to match the error against a valid 848 * association. 849 * 850 * Return an error if we can't find a match, the socket if we need further 851 * processing, zero otherwise. 852 */ 853 static struct sock *__udp4_lib_err_encap(struct net *net, 854 const struct iphdr *iph, 855 struct udphdr *uh, 856 struct sock *sk, 857 struct sk_buff *skb, u32 info) 858 { 859 int (*lookup)(struct sock *sk, struct sk_buff *skb); 860 int network_offset, transport_offset; 861 struct udp_sock *up; 862 863 network_offset = skb_network_offset(skb); 864 transport_offset = skb_transport_offset(skb); 865 866 /* Network header needs to point to the outer IPv4 header inside ICMP */ 867 skb_reset_network_header(skb); 868 869 /* Transport header needs to point to the UDP header */ 870 skb_set_transport_header(skb, iph->ihl << 2); 871 872 if (sk) { 873 up = udp_sk(sk); 874 875 lookup = READ_ONCE(up->encap_err_lookup); 876 if (lookup && lookup(sk, skb)) 877 sk = NULL; 878 879 goto out; 880 } 881 882 sk = __udp4_lib_lookup(net, iph->daddr, uh->source, 883 iph->saddr, uh->dest, skb->dev->ifindex, 0, NULL); 884 if (sk) { 885 up = udp_sk(sk); 886 887 lookup = READ_ONCE(up->encap_err_lookup); 888 if (!lookup || lookup(sk, skb)) 889 sk = NULL; 890 } 891 892 out: 893 if (!sk) 894 sk = ERR_PTR(__udp4_lib_err_encap_no_sk(skb, info)); 895 896 skb_set_transport_header(skb, transport_offset); 897 skb_set_network_header(skb, network_offset); 898 899 return sk; 900 } 901 902 /* 903 * This routine is called by the ICMP module when it gets some 904 * sort of error condition. If err < 0 then the socket should 905 * be closed and the error returned to the user. If err > 0 906 * it's just the icmp type << 8 | icmp code. 907 * Header points to the ip header of the error packet. We move 908 * on past this. Then (as it used to claim before adjustment) 909 * header points to the first 8 bytes of the udp header. We need 910 * to find the appropriate port. 911 */ 912 int udp_err(struct sk_buff *skb, u32 info) 913 { 914 const struct iphdr *iph = (const struct iphdr *)skb->data; 915 const int type = icmp_hdr(skb)->type; 916 const int code = icmp_hdr(skb)->code; 917 struct net *net = dev_net(skb->dev); 918 struct inet_sock *inet; 919 bool tunnel = false; 920 struct udphdr *uh; 921 struct sock *sk; 922 int harderr; 923 int err; 924 925 uh = (struct udphdr *)(skb->data + (iph->ihl << 2)); 926 sk = __udp4_lib_lookup(net, iph->daddr, uh->dest, 927 iph->saddr, uh->source, skb->dev->ifindex, 928 inet_sdif(skb), NULL); 929 930 if (!sk || READ_ONCE(udp_sk(sk)->encap_type)) { 931 /* No socket for error: try tunnels before discarding */ 932 if (static_branch_unlikely(&udp_encap_needed_key)) { 933 sk = __udp4_lib_err_encap(net, iph, uh, sk, skb, info); 934 if (!sk) 935 return 0; 936 } else 937 sk = ERR_PTR(-ENOENT); 938 939 if (IS_ERR(sk)) { 940 __ICMP_INC_STATS(net, ICMP_MIB_INERRORS); 941 return PTR_ERR(sk); 942 } 943 944 tunnel = true; 945 } 946 947 err = 0; 948 harderr = 0; 949 inet = inet_sk(sk); 950 951 switch (type) { 952 default: 953 case ICMP_TIME_EXCEEDED: 954 err = EHOSTUNREACH; 955 break; 956 case ICMP_SOURCE_QUENCH: 957 goto out; 958 case ICMP_PARAMETERPROB: 959 err = EPROTO; 960 harderr = 1; 961 break; 962 case ICMP_DEST_UNREACH: 963 if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */ 964 ipv4_sk_update_pmtu(skb, sk, info); 965 if (READ_ONCE(inet->pmtudisc) != IP_PMTUDISC_DONT) { 966 err = EMSGSIZE; 967 harderr = 1; 968 break; 969 } 970 goto out; 971 } 972 err = EHOSTUNREACH; 973 if (code <= NR_ICMP_UNREACH) { 974 harderr = icmp_err_convert[code].fatal; 975 err = icmp_err_convert[code].errno; 976 } 977 break; 978 case ICMP_REDIRECT: 979 ipv4_sk_redirect(skb, sk); 980 goto out; 981 } 982 983 /* 984 * RFC1122: OK. Passes ICMP errors back to application, as per 985 * 4.1.3.3. 986 */ 987 if (tunnel) { 988 /* ...not for tunnels though: we don't have a sending socket */ 989 if (udp_sk(sk)->encap_err_rcv) 990 udp_sk(sk)->encap_err_rcv(sk, skb, err, uh->dest, info, 991 (u8 *)(uh+1)); 992 goto out; 993 } 994 if (!inet_test_bit(RECVERR, sk)) { 995 if (!harderr || sk->sk_state != TCP_ESTABLISHED) 996 goto out; 997 } else 998 ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1)); 999 1000 sk->sk_err = err; 1001 sk_error_report(sk); 1002 out: 1003 return 0; 1004 } 1005 1006 /* 1007 * Throw away all pending data and cancel the corking. Socket is locked. 1008 */ 1009 void udp_flush_pending_frames(struct sock *sk) 1010 { 1011 struct udp_sock *up = udp_sk(sk); 1012 1013 if (up->pending) { 1014 up->len = 0; 1015 WRITE_ONCE(up->pending, 0); 1016 ip_flush_pending_frames(sk); 1017 } 1018 } 1019 1020 /** 1021 * udp4_hwcsum - handle outgoing HW checksumming 1022 * @skb: sk_buff containing the filled-in UDP header 1023 * (checksum field must be zeroed out) 1024 * @src: source IP address 1025 * @dst: destination IP address 1026 */ 1027 void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst) 1028 { 1029 struct udphdr *uh = udp_hdr(skb); 1030 int offset = skb_transport_offset(skb); 1031 int len = skb->len - offset; 1032 int hlen = len; 1033 __wsum csum = 0; 1034 1035 if (!skb_has_frag_list(skb)) { 1036 /* 1037 * Only one fragment on the socket. 1038 */ 1039 skb->csum_start = skb_transport_header(skb) - skb->head; 1040 skb->csum_offset = offsetof(struct udphdr, check); 1041 uh->check = ~csum_tcpudp_magic(src, dst, len, 1042 IPPROTO_UDP, 0); 1043 } else { 1044 struct sk_buff *frags; 1045 1046 /* 1047 * HW-checksum won't work as there are two or more 1048 * fragments on the socket so that all csums of sk_buffs 1049 * should be together 1050 */ 1051 skb_walk_frags(skb, frags) { 1052 csum = csum_add(csum, frags->csum); 1053 hlen -= frags->len; 1054 } 1055 1056 csum = skb_checksum(skb, offset, hlen, csum); 1057 skb->ip_summed = CHECKSUM_NONE; 1058 1059 uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum); 1060 if (uh->check == 0) 1061 uh->check = CSUM_MANGLED_0; 1062 } 1063 } 1064 EXPORT_SYMBOL_GPL(udp4_hwcsum); 1065 1066 /* Function to set UDP checksum for an IPv4 UDP packet. This is intended 1067 * for the simple case like when setting the checksum for a UDP tunnel. 1068 */ 1069 void udp_set_csum(bool nocheck, struct sk_buff *skb, 1070 __be32 saddr, __be32 daddr, int len) 1071 { 1072 struct udphdr *uh = udp_hdr(skb); 1073 1074 if (nocheck) { 1075 uh->check = 0; 1076 } else if (skb_is_gso(skb)) { 1077 uh->check = ~udp_v4_check(len, saddr, daddr, 0); 1078 } else if (skb->ip_summed == CHECKSUM_PARTIAL) { 1079 uh->check = 0; 1080 uh->check = udp_v4_check(len, saddr, daddr, lco_csum(skb)); 1081 if (uh->check == 0) 1082 uh->check = CSUM_MANGLED_0; 1083 } else { 1084 skb->ip_summed = CHECKSUM_PARTIAL; 1085 skb->csum_start = skb_transport_header(skb) - skb->head; 1086 skb->csum_offset = offsetof(struct udphdr, check); 1087 uh->check = ~udp_v4_check(len, saddr, daddr, 0); 1088 } 1089 } 1090 EXPORT_SYMBOL(udp_set_csum); 1091 1092 static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4, 1093 struct inet_cork *cork) 1094 { 1095 struct sock *sk = skb->sk; 1096 int offset, len, datalen; 1097 struct udphdr *uh; 1098 int err; 1099 1100 offset = skb_transport_offset(skb); 1101 len = skb->len - offset; 1102 datalen = len - sizeof(*uh); 1103 1104 /* 1105 * Create a UDP header 1106 */ 1107 uh = udp_hdr(skb); 1108 uh->source = inet_sk(sk)->inet_sport; 1109 uh->dest = fl4->fl4_dport; 1110 uh->len = htons(len); 1111 uh->check = 0; 1112 1113 if (cork->gso_size) { 1114 const int hlen = skb_network_header_len(skb) + 1115 sizeof(struct udphdr); 1116 1117 if (hlen + min(datalen, cork->gso_size) > cork->fragsize) { 1118 kfree_skb(skb); 1119 return -EMSGSIZE; 1120 } 1121 if (datalen > cork->gso_size * UDP_MAX_SEGMENTS) { 1122 kfree_skb(skb); 1123 return -EINVAL; 1124 } 1125 if (sk->sk_no_check_tx) { 1126 kfree_skb(skb); 1127 return -EINVAL; 1128 } 1129 if (dst_xfrm(skb_dst(skb))) { 1130 kfree_skb(skb); 1131 return -EIO; 1132 } 1133 1134 if (datalen > cork->gso_size) { 1135 skb_shinfo(skb)->gso_size = cork->gso_size; 1136 skb_shinfo(skb)->gso_type = SKB_GSO_UDP_L4; 1137 skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(datalen, 1138 cork->gso_size); 1139 1140 /* Don't checksum the payload, skb will get segmented */ 1141 goto csum_partial; 1142 } 1143 } 1144 1145 if (sk->sk_no_check_tx) { /* UDP csum off */ 1146 skb->ip_summed = CHECKSUM_NONE; 1147 goto send; 1148 } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */ 1149 csum_partial: 1150 udp4_hwcsum(skb, fl4->saddr, fl4->daddr); 1151 goto send; 1152 } 1153 1154 /* add protocol-dependent pseudo-header */ 1155 uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len, 1156 IPPROTO_UDP, udp_csum(skb)); 1157 if (uh->check == 0) 1158 uh->check = CSUM_MANGLED_0; 1159 1160 send: 1161 err = ip_send_skb(sock_net(sk), skb); 1162 if (unlikely(err)) { 1163 if (err == -ENOBUFS && 1164 !inet_test_bit(RECVERR, sk)) { 1165 UDP_INC_STATS(sock_net(sk), UDP_MIB_SNDBUFERRORS); 1166 err = 0; 1167 } 1168 } else { 1169 UDP_INC_STATS(sock_net(sk), UDP_MIB_OUTDATAGRAMS); 1170 } 1171 return err; 1172 } 1173 1174 /* 1175 * Push out all pending data as one UDP datagram. Socket is locked. 1176 */ 1177 int udp_push_pending_frames(struct sock *sk) 1178 { 1179 struct udp_sock *up = udp_sk(sk); 1180 struct inet_sock *inet = inet_sk(sk); 1181 struct flowi4 *fl4 = &inet->cork.fl.u.ip4; 1182 struct sk_buff *skb; 1183 int err = 0; 1184 1185 skb = ip_finish_skb(sk, fl4); 1186 if (!skb) 1187 goto out; 1188 1189 err = udp_send_skb(skb, fl4, &inet->cork.base); 1190 1191 out: 1192 up->len = 0; 1193 WRITE_ONCE(up->pending, 0); 1194 return err; 1195 } 1196 1197 static int __udp_cmsg_send(struct cmsghdr *cmsg, u16 *gso_size) 1198 { 1199 switch (cmsg->cmsg_type) { 1200 case UDP_SEGMENT: 1201 if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u16))) 1202 return -EINVAL; 1203 *gso_size = *(__u16 *)CMSG_DATA(cmsg); 1204 return 0; 1205 default: 1206 return -EINVAL; 1207 } 1208 } 1209 1210 int udp_cmsg_send(struct sock *sk, struct msghdr *msg, u16 *gso_size) 1211 { 1212 struct cmsghdr *cmsg; 1213 bool need_ip = false; 1214 int err; 1215 1216 for_each_cmsghdr(cmsg, msg) { 1217 if (!CMSG_OK(msg, cmsg)) 1218 return -EINVAL; 1219 1220 if (cmsg->cmsg_level != SOL_UDP) { 1221 need_ip = true; 1222 continue; 1223 } 1224 1225 err = __udp_cmsg_send(cmsg, gso_size); 1226 if (err) 1227 return err; 1228 } 1229 1230 return need_ip; 1231 } 1232 1233 int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) 1234 { 1235 int corkreq = udp_test_bit(CORK, sk) || msg->msg_flags & MSG_MORE; 1236 DEFINE_RAW_FLEX(struct ip_options_rcu, opt_copy, opt.__data, 1237 IP_OPTIONS_DATA_FIXED_SIZE); 1238 DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name); 1239 int ulen = len, free = 0, connected = 0; 1240 struct inet_sock *inet = inet_sk(sk); 1241 struct udp_sock *up = udp_sk(sk); 1242 __be32 daddr, faddr, saddr; 1243 struct rtable *rt = NULL; 1244 struct flowi4 fl4_stack; 1245 struct ipcm_cookie ipc; 1246 struct sk_buff *skb; 1247 struct flowi4 *fl4; 1248 __be16 dport; 1249 int uc_index; 1250 u8 scope; 1251 int err; 1252 1253 if (len > 0xFFFF) 1254 return -EMSGSIZE; 1255 1256 /* 1257 * Check the flags. 1258 */ 1259 1260 if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */ 1261 return -EOPNOTSUPP; 1262 1263 fl4 = &inet->cork.fl.u.ip4; 1264 if (READ_ONCE(up->pending)) { 1265 /* 1266 * There are pending frames. 1267 * The socket lock must be held while it's corked. 1268 */ 1269 lock_sock(sk); 1270 if (likely(up->pending)) { 1271 if (unlikely(up->pending != AF_INET)) { 1272 release_sock(sk); 1273 return -EINVAL; 1274 } 1275 goto do_append_data; 1276 } 1277 release_sock(sk); 1278 } 1279 ulen += sizeof(struct udphdr); 1280 1281 /* 1282 * Get and verify the address. 1283 */ 1284 if (usin) { 1285 if (msg->msg_namelen < sizeof(*usin)) 1286 return -EINVAL; 1287 if (usin->sin_family != AF_INET) { 1288 if (usin->sin_family != AF_UNSPEC) 1289 return -EAFNOSUPPORT; 1290 } 1291 1292 daddr = usin->sin_addr.s_addr; 1293 dport = usin->sin_port; 1294 if (dport == 0) 1295 return -EINVAL; 1296 } else { 1297 if (sk->sk_state != TCP_ESTABLISHED) 1298 return -EDESTADDRREQ; 1299 daddr = inet->inet_daddr; 1300 dport = inet->inet_dport; 1301 /* Open fast path for connected socket. 1302 Route will not be used, if at least one option is set. 1303 */ 1304 connected = 1; 1305 } 1306 1307 ipcm_init_sk(&ipc, inet); 1308 ipc.gso_size = READ_ONCE(up->gso_size); 1309 1310 if (msg->msg_controllen) { 1311 err = udp_cmsg_send(sk, msg, &ipc.gso_size); 1312 if (err > 0) { 1313 err = ip_cmsg_send(sk, msg, &ipc, 1314 sk->sk_family == AF_INET6); 1315 connected = 0; 1316 } 1317 if (unlikely(err < 0)) { 1318 kfree(ipc.opt); 1319 return err; 1320 } 1321 if (ipc.opt) 1322 free = 1; 1323 } 1324 if (!ipc.opt) { 1325 struct ip_options_rcu *inet_opt; 1326 1327 rcu_read_lock(); 1328 inet_opt = rcu_dereference(inet->inet_opt); 1329 if (inet_opt) { 1330 memcpy(opt_copy, inet_opt, 1331 sizeof(*inet_opt) + inet_opt->opt.optlen); 1332 ipc.opt = opt_copy; 1333 } 1334 rcu_read_unlock(); 1335 } 1336 1337 if (cgroup_bpf_enabled(CGROUP_UDP4_SENDMSG) && !connected) { 1338 err = BPF_CGROUP_RUN_PROG_UDP4_SENDMSG_LOCK(sk, 1339 (struct sockaddr *)usin, 1340 &msg->msg_namelen, 1341 &ipc.addr); 1342 if (err) 1343 goto out_free; 1344 if (usin) { 1345 if (usin->sin_port == 0) { 1346 /* BPF program set invalid port. Reject it. */ 1347 err = -EINVAL; 1348 goto out_free; 1349 } 1350 daddr = usin->sin_addr.s_addr; 1351 dport = usin->sin_port; 1352 } 1353 } 1354 1355 saddr = ipc.addr; 1356 ipc.addr = faddr = daddr; 1357 1358 if (ipc.opt && ipc.opt->opt.srr) { 1359 if (!daddr) { 1360 err = -EINVAL; 1361 goto out_free; 1362 } 1363 faddr = ipc.opt->opt.faddr; 1364 connected = 0; 1365 } 1366 scope = ip_sendmsg_scope(inet, &ipc, msg); 1367 if (scope == RT_SCOPE_LINK) 1368 connected = 0; 1369 1370 uc_index = READ_ONCE(inet->uc_index); 1371 if (ipv4_is_multicast(daddr)) { 1372 if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif)) 1373 ipc.oif = READ_ONCE(inet->mc_index); 1374 if (!saddr) 1375 saddr = READ_ONCE(inet->mc_addr); 1376 connected = 0; 1377 } else if (!ipc.oif) { 1378 ipc.oif = uc_index; 1379 } else if (ipv4_is_lbcast(daddr) && uc_index) { 1380 /* oif is set, packet is to local broadcast and 1381 * uc_index is set. oif is most likely set 1382 * by sk_bound_dev_if. If uc_index != oif check if the 1383 * oif is an L3 master and uc_index is an L3 slave. 1384 * If so, we want to allow the send using the uc_index. 1385 */ 1386 if (ipc.oif != uc_index && 1387 ipc.oif == l3mdev_master_ifindex_by_index(sock_net(sk), 1388 uc_index)) { 1389 ipc.oif = uc_index; 1390 } 1391 } 1392 1393 if (connected) 1394 rt = dst_rtable(sk_dst_check(sk, 0)); 1395 1396 if (!rt) { 1397 struct net *net = sock_net(sk); 1398 __u8 flow_flags = inet_sk_flowi_flags(sk); 1399 1400 fl4 = &fl4_stack; 1401 1402 flowi4_init_output(fl4, ipc.oif, ipc.sockc.mark, 1403 ipc.tos & INET_DSCP_MASK, scope, 1404 IPPROTO_UDP, flow_flags, faddr, saddr, 1405 dport, inet->inet_sport, 1406 sk_uid(sk)); 1407 1408 security_sk_classify_flow(sk, flowi4_to_flowi_common(fl4)); 1409 rt = ip_route_output_flow(net, fl4, sk); 1410 if (IS_ERR(rt)) { 1411 err = PTR_ERR(rt); 1412 rt = NULL; 1413 if (err == -ENETUNREACH) 1414 IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES); 1415 goto out; 1416 } 1417 1418 err = -EACCES; 1419 if ((rt->rt_flags & RTCF_BROADCAST) && 1420 !sock_flag(sk, SOCK_BROADCAST)) 1421 goto out; 1422 if (connected) 1423 sk_dst_set(sk, dst_clone(&rt->dst)); 1424 } 1425 1426 if (msg->msg_flags&MSG_CONFIRM) 1427 goto do_confirm; 1428 back_from_confirm: 1429 1430 saddr = fl4->saddr; 1431 if (!ipc.addr) 1432 daddr = ipc.addr = fl4->daddr; 1433 1434 /* Lockless fast path for the non-corking case. */ 1435 if (!corkreq) { 1436 struct inet_cork cork; 1437 1438 skb = ip_make_skb(sk, fl4, ip_generic_getfrag, msg, ulen, 1439 sizeof(struct udphdr), &ipc, &rt, 1440 &cork, msg->msg_flags); 1441 err = PTR_ERR(skb); 1442 if (!IS_ERR_OR_NULL(skb)) 1443 err = udp_send_skb(skb, fl4, &cork); 1444 goto out; 1445 } 1446 1447 lock_sock(sk); 1448 if (unlikely(up->pending)) { 1449 /* The socket is already corked while preparing it. */ 1450 /* ... which is an evident application bug. --ANK */ 1451 release_sock(sk); 1452 1453 net_dbg_ratelimited("socket already corked\n"); 1454 err = -EINVAL; 1455 goto out; 1456 } 1457 /* 1458 * Now cork the socket to pend data. 1459 */ 1460 fl4 = &inet->cork.fl.u.ip4; 1461 fl4->daddr = daddr; 1462 fl4->saddr = saddr; 1463 fl4->fl4_dport = dport; 1464 fl4->fl4_sport = inet->inet_sport; 1465 WRITE_ONCE(up->pending, AF_INET); 1466 1467 do_append_data: 1468 up->len += ulen; 1469 err = ip_append_data(sk, fl4, ip_generic_getfrag, msg, ulen, 1470 sizeof(struct udphdr), &ipc, &rt, 1471 corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags); 1472 if (err) 1473 udp_flush_pending_frames(sk); 1474 else if (!corkreq) 1475 err = udp_push_pending_frames(sk); 1476 else if (unlikely(skb_queue_empty(&sk->sk_write_queue))) 1477 WRITE_ONCE(up->pending, 0); 1478 release_sock(sk); 1479 1480 out: 1481 ip_rt_put(rt); 1482 out_free: 1483 if (free) 1484 kfree(ipc.opt); 1485 if (!err) 1486 return len; 1487 /* 1488 * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting 1489 * ENOBUFS might not be good (it's not tunable per se), but otherwise 1490 * we don't have a good statistic (IpOutDiscards but it can be too many 1491 * things). We could add another new stat but at least for now that 1492 * seems like overkill. 1493 */ 1494 if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) 1495 UDP_INC_STATS(sock_net(sk), UDP_MIB_SNDBUFERRORS); 1496 1497 return err; 1498 1499 do_confirm: 1500 if (msg->msg_flags & MSG_PROBE) 1501 dst_confirm_neigh(&rt->dst, &fl4->daddr); 1502 if (!(msg->msg_flags&MSG_PROBE) || len) 1503 goto back_from_confirm; 1504 err = 0; 1505 goto out; 1506 } 1507 EXPORT_SYMBOL(udp_sendmsg); 1508 1509 void udp_splice_eof(struct socket *sock) 1510 { 1511 struct sock *sk = sock->sk; 1512 struct udp_sock *up = udp_sk(sk); 1513 1514 if (!READ_ONCE(up->pending) || udp_test_bit(CORK, sk)) 1515 return; 1516 1517 lock_sock(sk); 1518 if (up->pending && !udp_test_bit(CORK, sk)) 1519 udp_push_pending_frames(sk); 1520 release_sock(sk); 1521 } 1522 1523 #define UDP_SKB_IS_STATELESS 0x80000000 1524 1525 /* all head states (dst, sk, nf conntrack) except skb extensions are 1526 * cleared by udp_rcv(). 1527 * 1528 * We need to preserve secpath, if present, to eventually process 1529 * IP_CMSG_PASSSEC at recvmsg() time. 1530 * 1531 * Other extensions can be cleared. 1532 */ 1533 static bool udp_try_make_stateless(struct sk_buff *skb) 1534 { 1535 if (!skb_has_extensions(skb)) 1536 return true; 1537 1538 if (!secpath_exists(skb)) { 1539 skb_ext_reset(skb); 1540 return true; 1541 } 1542 1543 return false; 1544 } 1545 1546 static void udp_set_dev_scratch(struct sk_buff *skb) 1547 { 1548 struct udp_dev_scratch *scratch = udp_skb_scratch(skb); 1549 1550 BUILD_BUG_ON(sizeof(struct udp_dev_scratch) > sizeof(long)); 1551 scratch->_tsize_state = skb->truesize; 1552 #if BITS_PER_LONG == 64 1553 scratch->len = skb->len; 1554 scratch->csum_unnecessary = !!skb_csum_unnecessary(skb); 1555 scratch->is_linear = !skb_is_nonlinear(skb); 1556 #endif 1557 if (udp_try_make_stateless(skb)) 1558 scratch->_tsize_state |= UDP_SKB_IS_STATELESS; 1559 } 1560 1561 static void udp_skb_csum_unnecessary_set(struct sk_buff *skb) 1562 { 1563 /* We come here after udp_lib_checksum_complete() returned 0. 1564 * This means that __skb_checksum_complete() might have 1565 * set skb->csum_valid to 1. 1566 * On 64bit platforms, we can set csum_unnecessary 1567 * to true, but only if the skb is not shared. 1568 */ 1569 #if BITS_PER_LONG == 64 1570 if (!skb_shared(skb)) 1571 udp_skb_scratch(skb)->csum_unnecessary = true; 1572 #endif 1573 } 1574 1575 static int udp_skb_truesize(struct sk_buff *skb) 1576 { 1577 return udp_skb_scratch(skb)->_tsize_state & ~UDP_SKB_IS_STATELESS; 1578 } 1579 1580 static bool udp_skb_has_head_state(struct sk_buff *skb) 1581 { 1582 return !(udp_skb_scratch(skb)->_tsize_state & UDP_SKB_IS_STATELESS); 1583 } 1584 1585 /* fully reclaim rmem/fwd memory allocated for skb */ 1586 static void udp_rmem_release(struct sock *sk, unsigned int size, 1587 int partial, bool rx_queue_lock_held) 1588 { 1589 struct udp_sock *up = udp_sk(sk); 1590 struct sk_buff_head *sk_queue; 1591 unsigned int amt; 1592 1593 if (likely(partial)) { 1594 up->forward_deficit += size; 1595 size = up->forward_deficit; 1596 if (size < READ_ONCE(up->forward_threshold) && 1597 !skb_queue_empty(&up->reader_queue)) 1598 return; 1599 } else { 1600 size += up->forward_deficit; 1601 } 1602 up->forward_deficit = 0; 1603 1604 /* acquire the sk_receive_queue for fwd allocated memory scheduling, 1605 * if the called don't held it already 1606 */ 1607 sk_queue = &sk->sk_receive_queue; 1608 if (!rx_queue_lock_held) 1609 spin_lock(&sk_queue->lock); 1610 1611 amt = (size + sk->sk_forward_alloc - partial) & ~(PAGE_SIZE - 1); 1612 sk_forward_alloc_add(sk, size - amt); 1613 1614 if (amt) 1615 __sk_mem_reduce_allocated(sk, amt >> PAGE_SHIFT); 1616 1617 atomic_sub(size, &sk->sk_rmem_alloc); 1618 1619 /* this can save us from acquiring the rx queue lock on next receive */ 1620 skb_queue_splice_tail_init(sk_queue, &up->reader_queue); 1621 1622 if (!rx_queue_lock_held) 1623 spin_unlock(&sk_queue->lock); 1624 } 1625 1626 /* Note: called with reader_queue.lock held. 1627 * Instead of using skb->truesize here, find a copy of it in skb->dev_scratch 1628 * This avoids a cache line miss while receive_queue lock is held. 1629 * Look at __udp_enqueue_schedule_skb() to find where this copy is done. 1630 */ 1631 void udp_skb_destructor(struct sock *sk, struct sk_buff *skb) 1632 { 1633 prefetch(&skb->data); 1634 udp_rmem_release(sk, udp_skb_truesize(skb), 1, false); 1635 } 1636 1637 /* as above, but the caller held the rx queue lock, too */ 1638 static void udp_skb_dtor_locked(struct sock *sk, struct sk_buff *skb) 1639 { 1640 prefetch(&skb->data); 1641 udp_rmem_release(sk, udp_skb_truesize(skb), 1, true); 1642 } 1643 1644 static int udp_rmem_schedule(struct sock *sk, int size) 1645 { 1646 int delta; 1647 1648 delta = size - sk->sk_forward_alloc; 1649 if (delta > 0 && !__sk_mem_schedule(sk, delta, SK_MEM_RECV)) 1650 return -ENOBUFS; 1651 1652 return 0; 1653 } 1654 1655 int __udp_enqueue_schedule_skb(struct sock *sk, struct sk_buff *skb) 1656 { 1657 struct sk_buff_head *list = &sk->sk_receive_queue; 1658 struct udp_prod_queue *udp_prod_queue; 1659 struct sk_buff *next, *to_drop = NULL; 1660 struct llist_node *ll_list; 1661 unsigned int rmem, rcvbuf; 1662 int size, err = -ENOMEM; 1663 int total_size = 0; 1664 int q_size = 0; 1665 int dropcount; 1666 int nb = 0; 1667 1668 rmem = atomic_read(&sk->sk_rmem_alloc); 1669 rcvbuf = READ_ONCE(sk->sk_rcvbuf); 1670 size = skb->truesize; 1671 1672 udp_prod_queue = &udp_sk(sk)->udp_prod_queue[numa_node_id()]; 1673 1674 rmem += atomic_read(&udp_prod_queue->rmem_alloc); 1675 1676 /* Immediately drop when the receive queue is full. 1677 * Cast to unsigned int performs the boundary check for INT_MAX. 1678 */ 1679 if (rmem + size > rcvbuf) { 1680 if (rcvbuf > INT_MAX >> 1) 1681 goto drop; 1682 1683 /* Accept the packet if queue is empty. */ 1684 if (rmem) 1685 goto drop; 1686 } 1687 1688 /* Under mem pressure, it might be helpful to help udp_recvmsg() 1689 * having linear skbs : 1690 * - Reduce memory overhead and thus increase receive queue capacity 1691 * - Less cache line misses at copyout() time 1692 * - Less work at consume_skb() (less alien page frag freeing) 1693 */ 1694 if (rmem > (rcvbuf >> 1)) { 1695 skb_condense(skb); 1696 size = skb->truesize; 1697 } 1698 1699 udp_set_dev_scratch(skb); 1700 1701 atomic_add(size, &udp_prod_queue->rmem_alloc); 1702 1703 if (!llist_add(&skb->ll_node, &udp_prod_queue->ll_root)) 1704 return 0; 1705 1706 dropcount = sock_flag(sk, SOCK_RXQ_OVFL) ? sk_drops_read(sk) : 0; 1707 1708 spin_lock(&list->lock); 1709 1710 ll_list = llist_del_all(&udp_prod_queue->ll_root); 1711 1712 ll_list = llist_reverse_order(ll_list); 1713 1714 llist_for_each_entry_safe(skb, next, ll_list, ll_node) { 1715 size = udp_skb_truesize(skb); 1716 total_size += size; 1717 err = udp_rmem_schedule(sk, size); 1718 if (unlikely(err)) { 1719 /* Free the skbs outside of locked section. */ 1720 skb->next = to_drop; 1721 to_drop = skb; 1722 continue; 1723 } 1724 1725 q_size += size; 1726 sk_forward_alloc_add(sk, -size); 1727 1728 /* no need to setup a destructor, we will explicitly release the 1729 * forward allocated memory on dequeue 1730 */ 1731 SOCK_SKB_CB(skb)->dropcount = dropcount; 1732 nb++; 1733 __skb_queue_tail(list, skb); 1734 } 1735 1736 atomic_add(q_size, &sk->sk_rmem_alloc); 1737 1738 spin_unlock(&list->lock); 1739 1740 if (!sock_flag(sk, SOCK_DEAD)) { 1741 /* Multiple threads might be blocked in recvmsg(), 1742 * using prepare_to_wait_exclusive(). 1743 */ 1744 while (nb) { 1745 INDIRECT_CALL_1(READ_ONCE(sk->sk_data_ready), 1746 sock_def_readable, sk); 1747 nb--; 1748 } 1749 } 1750 1751 if (unlikely(to_drop)) { 1752 int err_ipv4 = 0; 1753 int err_ipv6 = 0; 1754 1755 for (nb = 0; to_drop != NULL; nb++) { 1756 skb = to_drop; 1757 if (skb->protocol == htons(ETH_P_IP)) 1758 err_ipv4++; 1759 else 1760 err_ipv6++; 1761 to_drop = skb->next; 1762 skb_mark_not_on_list(skb); 1763 sk_skb_reason_drop(sk, skb, SKB_DROP_REASON_PROTO_MEM); 1764 } 1765 numa_drop_add(&udp_sk(sk)->drop_counters, nb); 1766 if (err_ipv4 > 0) { 1767 SNMP_ADD_STATS(__UDPX_MIB(sk, true), UDP_MIB_MEMERRORS, 1768 err_ipv4); 1769 SNMP_ADD_STATS(__UDPX_MIB(sk, true), UDP_MIB_INERRORS, 1770 err_ipv4); 1771 } 1772 if (err_ipv6 > 0) { 1773 SNMP_ADD_STATS(__UDPX_MIB(sk, false), UDP_MIB_MEMERRORS, 1774 err_ipv6); 1775 SNMP_ADD_STATS(__UDPX_MIB(sk, false), UDP_MIB_INERRORS, 1776 err_ipv6); 1777 } 1778 } 1779 1780 atomic_sub(total_size, &udp_prod_queue->rmem_alloc); 1781 1782 return 0; 1783 1784 drop: 1785 udp_drops_inc(sk); 1786 return err; 1787 } 1788 1789 void udp_destruct_common(struct sock *sk) 1790 { 1791 /* reclaim completely the forward allocated memory */ 1792 struct udp_sock *up = udp_sk(sk); 1793 unsigned int total = 0; 1794 struct sk_buff *skb; 1795 1796 skb_queue_splice_tail_init(&sk->sk_receive_queue, &up->reader_queue); 1797 while ((skb = __skb_dequeue(&up->reader_queue)) != NULL) { 1798 total += skb->truesize; 1799 kfree_skb(skb); 1800 } 1801 udp_rmem_release(sk, total, 0, true); 1802 kfree(up->udp_prod_queue); 1803 } 1804 1805 static void udp_destruct_sock(struct sock *sk) 1806 { 1807 udp_destruct_common(sk); 1808 inet_sock_destruct(sk); 1809 } 1810 1811 static int udp_init_sock(struct sock *sk) 1812 { 1813 int res = udp_lib_init_sock(sk); 1814 1815 sk->sk_destruct = udp_destruct_sock; 1816 set_bit(SOCK_SUPPORT_ZC, &sk->sk_socket->flags); 1817 return res; 1818 } 1819 1820 void skb_consume_udp(struct sock *sk, struct sk_buff *skb, int len) 1821 { 1822 if (unlikely(READ_ONCE(udp_sk(sk)->peeking_with_offset))) 1823 sk_peek_offset_bwd(sk, len); 1824 1825 if (!skb_shared(skb)) { 1826 skb_orphan(skb); 1827 skb_attempt_defer_free(skb); 1828 return; 1829 } 1830 1831 if (!skb_unref(skb)) 1832 return; 1833 1834 /* In the more common cases we cleared the head states previously, 1835 * see __udp_queue_rcv_skb(). 1836 */ 1837 if (unlikely(udp_skb_has_head_state(skb))) 1838 skb_release_head_state(skb); 1839 __consume_stateless_skb(skb); 1840 } 1841 1842 static struct sk_buff *__first_packet_length(struct sock *sk, 1843 struct sk_buff_head *rcvq, 1844 unsigned int *total) 1845 { 1846 struct sk_buff *skb; 1847 1848 while ((skb = skb_peek(rcvq)) != NULL) { 1849 if (udp_lib_checksum_complete(skb)) { 1850 struct net *net = sock_net(sk); 1851 1852 __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS); 1853 __UDP_INC_STATS(net, UDP_MIB_INERRORS); 1854 udp_drops_inc(sk); 1855 __skb_unlink(skb, rcvq); 1856 *total += skb->truesize; 1857 kfree_skb_reason(skb, SKB_DROP_REASON_UDP_CSUM); 1858 } else { 1859 udp_skb_csum_unnecessary_set(skb); 1860 break; 1861 } 1862 } 1863 return skb; 1864 } 1865 1866 /** 1867 * first_packet_length - return length of first packet in receive queue 1868 * @sk: socket 1869 * 1870 * Drops all bad checksum frames, until a valid one is found. 1871 * Returns the length of found skb, or -1 if none is found. 1872 */ 1873 static int first_packet_length(struct sock *sk) 1874 { 1875 struct sk_buff_head *rcvq = &udp_sk(sk)->reader_queue; 1876 struct sk_buff_head *sk_queue = &sk->sk_receive_queue; 1877 unsigned int total = 0; 1878 struct sk_buff *skb; 1879 int res; 1880 1881 spin_lock_bh(&rcvq->lock); 1882 skb = __first_packet_length(sk, rcvq, &total); 1883 if (!skb && !skb_queue_empty_lockless(sk_queue)) { 1884 spin_lock(&sk_queue->lock); 1885 skb_queue_splice_tail_init(sk_queue, rcvq); 1886 spin_unlock(&sk_queue->lock); 1887 1888 skb = __first_packet_length(sk, rcvq, &total); 1889 } 1890 res = skb ? skb->len : -1; 1891 if (total) 1892 udp_rmem_release(sk, total, 1, false); 1893 spin_unlock_bh(&rcvq->lock); 1894 return res; 1895 } 1896 1897 /* 1898 * IOCTL requests applicable to the UDP protocol 1899 */ 1900 1901 int udp_ioctl(struct sock *sk, int cmd, int *karg) 1902 { 1903 switch (cmd) { 1904 case SIOCOUTQ: 1905 { 1906 *karg = sk_wmem_alloc_get(sk); 1907 return 0; 1908 } 1909 1910 case SIOCINQ: 1911 { 1912 *karg = max_t(int, 0, first_packet_length(sk)); 1913 return 0; 1914 } 1915 1916 default: 1917 return -ENOIOCTLCMD; 1918 } 1919 1920 return 0; 1921 } 1922 1923 struct sk_buff *__skb_recv_udp(struct sock *sk, unsigned int flags, 1924 int *off, int *err) 1925 { 1926 struct sk_buff_head *sk_queue = &sk->sk_receive_queue; 1927 struct sk_buff_head *queue; 1928 struct sk_buff *last; 1929 long timeo; 1930 int error; 1931 1932 queue = &udp_sk(sk)->reader_queue; 1933 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); 1934 do { 1935 struct sk_buff *skb; 1936 1937 error = sock_error(sk); 1938 if (error) 1939 break; 1940 1941 error = -EAGAIN; 1942 do { 1943 spin_lock_bh(&queue->lock); 1944 skb = __skb_try_recv_from_queue(queue, flags, off, err, 1945 &last); 1946 if (skb) { 1947 if (!(flags & MSG_PEEK)) 1948 udp_skb_destructor(sk, skb); 1949 spin_unlock_bh(&queue->lock); 1950 return skb; 1951 } 1952 1953 if (skb_queue_empty_lockless(sk_queue)) { 1954 spin_unlock_bh(&queue->lock); 1955 goto busy_check; 1956 } 1957 1958 /* refill the reader queue and walk it again 1959 * keep both queues locked to avoid re-acquiring 1960 * the sk_receive_queue lock if fwd memory scheduling 1961 * is needed. 1962 */ 1963 spin_lock(&sk_queue->lock); 1964 skb_queue_splice_tail_init(sk_queue, queue); 1965 1966 skb = __skb_try_recv_from_queue(queue, flags, off, err, 1967 &last); 1968 if (skb && !(flags & MSG_PEEK)) 1969 udp_skb_dtor_locked(sk, skb); 1970 spin_unlock(&sk_queue->lock); 1971 spin_unlock_bh(&queue->lock); 1972 if (skb) 1973 return skb; 1974 1975 busy_check: 1976 if (!sk_can_busy_loop(sk)) 1977 break; 1978 1979 sk_busy_loop(sk, flags & MSG_DONTWAIT); 1980 } while (!skb_queue_empty_lockless(sk_queue)); 1981 1982 /* sk_queue is empty, reader_queue may contain peeked packets */ 1983 } while (timeo && 1984 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue, 1985 &error, &timeo, 1986 (struct sk_buff *)sk_queue)); 1987 1988 *err = error; 1989 return NULL; 1990 } 1991 EXPORT_SYMBOL(__skb_recv_udp); 1992 1993 int udp_read_skb(struct sock *sk, skb_read_actor_t recv_actor) 1994 { 1995 struct sk_buff *skb; 1996 int err; 1997 1998 try_again: 1999 skb = skb_recv_udp(sk, MSG_DONTWAIT, &err); 2000 if (!skb) 2001 return err; 2002 2003 if (udp_lib_checksum_complete(skb)) { 2004 struct net *net = sock_net(sk); 2005 2006 __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS); 2007 __UDP_INC_STATS(net, UDP_MIB_INERRORS); 2008 udp_drops_inc(sk); 2009 kfree_skb_reason(skb, SKB_DROP_REASON_UDP_CSUM); 2010 goto try_again; 2011 } 2012 2013 WARN_ON_ONCE(!skb_set_owner_sk_safe(skb, sk)); 2014 2015 /* 2016 * skb->dev still aliases the UDP rx dev_scratch (its charge was freed 2017 * on dequeue above); a sockmap verdict program may deref it via 2018 * bpf_sk_lookup_*(), so clear it -> bpf_skc_lookup() uses skb->sk 2019 */ 2020 skb->dev = NULL; 2021 2022 return recv_actor(sk, skb); 2023 } 2024 2025 /* 2026 * This should be easy, if there is something there we 2027 * return it, otherwise we block. 2028 */ 2029 2030 INDIRECT_CALLABLE_SCOPE 2031 int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int flags) 2032 { 2033 DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name); 2034 int off, err, peeking = flags & MSG_PEEK; 2035 struct inet_sock *inet = inet_sk(sk); 2036 struct net *net = sock_net(sk); 2037 bool checksum_valid = false; 2038 unsigned int ulen, copied; 2039 struct sk_buff *skb; 2040 2041 if (flags & MSG_ERRQUEUE) 2042 return ip_recv_error(sk, msg, len); 2043 2044 try_again: 2045 off = sk_peek_offset(sk, flags); 2046 skb = __skb_recv_udp(sk, flags, &off, &err); 2047 if (!skb) 2048 return err; 2049 2050 ulen = udp_skb_len(skb); 2051 copied = len; 2052 if (copied > ulen - off) 2053 copied = ulen - off; 2054 else if (copied < ulen) 2055 msg->msg_flags |= MSG_TRUNC; 2056 2057 /* If checksum is needed at all, try to do it while copying the 2058 * data. If the data is truncated, do it before the copy. 2059 */ 2060 if (copied < ulen || peeking) { 2061 checksum_valid = udp_skb_csum_unnecessary(skb) || 2062 !__udp_lib_checksum_complete(skb); 2063 if (!checksum_valid) 2064 goto csum_copy_err; 2065 } 2066 2067 if (checksum_valid || udp_skb_csum_unnecessary(skb)) { 2068 if (udp_skb_is_linear(skb)) 2069 err = copy_linear_skb(skb, copied, off, &msg->msg_iter); 2070 else 2071 err = skb_copy_datagram_msg(skb, off, msg, copied); 2072 } else { 2073 err = skb_copy_and_csum_datagram_msg(skb, off, msg); 2074 2075 if (err == -EINVAL) 2076 goto csum_copy_err; 2077 } 2078 2079 if (unlikely(err)) { 2080 if (!peeking) { 2081 udp_drops_inc(sk); 2082 UDP_INC_STATS(net, UDP_MIB_INERRORS); 2083 } 2084 kfree_skb(skb); 2085 return err; 2086 } 2087 2088 if (!peeking) 2089 UDP_INC_STATS(net, UDP_MIB_INDATAGRAMS); 2090 2091 sock_recv_cmsgs(msg, sk, skb); 2092 2093 /* Copy the address. */ 2094 if (sin) { 2095 sin->sin_family = AF_INET; 2096 sin->sin_port = udp_hdr(skb)->source; 2097 sin->sin_addr.s_addr = ip_hdr(skb)->saddr; 2098 memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); 2099 msg->msg_namelen = sizeof(*sin); 2100 2101 BPF_CGROUP_RUN_PROG_UDP4_RECVMSG_LOCK(sk, 2102 (struct sockaddr *)sin, 2103 &msg->msg_namelen); 2104 } 2105 2106 if (udp_test_bit(GRO_ENABLED, sk)) 2107 udp_cmsg_recv(msg, sk, skb); 2108 2109 if (inet_cmsg_flags(inet)) 2110 ip_cmsg_recv_offset(msg, sk, skb, sizeof(struct udphdr), off); 2111 2112 err = copied; 2113 if (flags & MSG_TRUNC) 2114 err = ulen; 2115 2116 skb_consume_udp(sk, skb, peeking ? -err : err); 2117 return err; 2118 2119 csum_copy_err: 2120 if (!__sk_queue_drop_skb(sk, &udp_sk(sk)->reader_queue, skb, flags, 2121 udp_skb_destructor)) { 2122 UDP_INC_STATS(net, UDP_MIB_CSUMERRORS); 2123 UDP_INC_STATS(net, UDP_MIB_INERRORS); 2124 } 2125 kfree_skb_reason(skb, SKB_DROP_REASON_UDP_CSUM); 2126 2127 /* starting over for a new packet, but check if we need to yield */ 2128 cond_resched(); 2129 msg->msg_flags &= ~MSG_TRUNC; 2130 goto try_again; 2131 } 2132 2133 int udp_pre_connect(struct sock *sk, struct sockaddr_unsized *uaddr, 2134 int addr_len) 2135 { 2136 /* This check is replicated from __ip4_datagram_connect() and 2137 * intended to prevent BPF program called below from accessing bytes 2138 * that are out of the bound specified by user in addr_len. 2139 */ 2140 if (addr_len < sizeof(struct sockaddr_in)) 2141 return -EINVAL; 2142 2143 return BPF_CGROUP_RUN_PROG_INET4_CONNECT_LOCK(sk, uaddr, &addr_len); 2144 } 2145 2146 static int udp_connect(struct sock *sk, struct sockaddr_unsized *uaddr, 2147 int addr_len) 2148 { 2149 int res; 2150 2151 lock_sock(sk); 2152 res = __ip4_datagram_connect(sk, uaddr, addr_len); 2153 if (!res) 2154 udp4_hash4(sk); 2155 release_sock(sk); 2156 return res; 2157 } 2158 2159 int __udp_disconnect(struct sock *sk, int flags) 2160 { 2161 struct inet_sock *inet = inet_sk(sk); 2162 /* 2163 * 1003.1g - break association. 2164 */ 2165 2166 sk->sk_state = TCP_CLOSE; 2167 inet->inet_daddr = 0; 2168 inet->inet_dport = 0; 2169 sock_rps_reset_rxhash(sk); 2170 sk->sk_bound_dev_if = 0; 2171 if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) { 2172 inet_reset_saddr(sk); 2173 if (sk->sk_prot->rehash && 2174 (sk->sk_userlocks & SOCK_BINDPORT_LOCK)) 2175 sk->sk_prot->rehash(sk); 2176 } 2177 2178 if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) { 2179 sk->sk_prot->unhash(sk); 2180 inet->inet_sport = 0; 2181 } 2182 sk_dst_reset(sk); 2183 return 0; 2184 } 2185 EXPORT_SYMBOL(__udp_disconnect); 2186 2187 int udp_disconnect(struct sock *sk, int flags) 2188 { 2189 lock_sock(sk); 2190 __udp_disconnect(sk, flags); 2191 release_sock(sk); 2192 return 0; 2193 } 2194 2195 void udp_lib_unhash(struct sock *sk) 2196 { 2197 if (sk_hashed(sk)) { 2198 struct udp_hslot *hslot, *hslot2; 2199 struct net *net = sock_net(sk); 2200 struct udp_table *udptable; 2201 2202 sock_rps_delete_flow(sk); 2203 udptable = net->ipv4.udp_table; 2204 hslot = udp_hashslot(udptable, net, udp_sk(sk)->udp_port_hash); 2205 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); 2206 2207 spin_lock_bh(&hslot->lock); 2208 if (rcu_access_pointer(sk->sk_reuseport_cb)) 2209 reuseport_detach_sock(sk); 2210 if (sk_del_node_init_rcu(sk)) { 2211 hslot->count--; 2212 inet_sk(sk)->inet_num = 0; 2213 sock_prot_inuse_add(net, sk->sk_prot, -1); 2214 2215 spin_lock(&hslot2->lock); 2216 hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node); 2217 hslot2->count--; 2218 spin_unlock(&hslot2->lock); 2219 2220 udp_unhash4(udptable, sk); 2221 } 2222 spin_unlock_bh(&hslot->lock); 2223 } 2224 } 2225 2226 /* 2227 * inet_rcv_saddr was changed, we must rehash secondary hash 2228 */ 2229 void udp_lib_rehash(struct sock *sk, u16 newhash, u16 newhash4) 2230 { 2231 if (sk_hashed(sk)) { 2232 struct udp_hslot *hslot, *hslot2, *nhslot2; 2233 struct net *net = sock_net(sk); 2234 struct udp_table *udptable; 2235 2236 udptable = net->ipv4.udp_table; 2237 hslot = udp_hashslot(udptable, net, udp_sk(sk)->udp_port_hash); 2238 hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); 2239 nhslot2 = udp_hashslot2(udptable, newhash); 2240 2241 if (hslot2 != nhslot2 || 2242 rcu_access_pointer(sk->sk_reuseport_cb)) { 2243 /* we must lock primary chain too */ 2244 spin_lock_bh(&hslot->lock); 2245 if (rcu_access_pointer(sk->sk_reuseport_cb)) 2246 reuseport_detach_sock(sk); 2247 2248 if (hslot2 != nhslot2) { 2249 spin_lock(&hslot2->lock); 2250 hlist_del_init_rcu(&udp_sk(sk)->udp_portaddr_node); 2251 hslot2->count--; 2252 spin_unlock(&hslot2->lock); 2253 2254 spin_lock(&nhslot2->lock); 2255 hlist_add_head_rcu(&udp_sk(sk)->udp_portaddr_node, 2256 &nhslot2->head); 2257 nhslot2->count++; 2258 spin_unlock(&nhslot2->lock); 2259 } 2260 2261 spin_unlock_bh(&hslot->lock); 2262 } 2263 2264 /* Now process hash4 if necessary: 2265 * (1) update hslot4; 2266 * (2) update hslot2->hash4_cnt. 2267 * Note that hslot2/hslot4 should be checked separately, as 2268 * either of them may change with the other unchanged. 2269 */ 2270 if (udp_hashed4(sk)) { 2271 spin_lock_bh(&hslot->lock); 2272 2273 if (inet_rcv_saddr_any(sk)) { 2274 udp_unhash4(udptable, sk); 2275 } else { 2276 udp_rehash4(udptable, sk, newhash4); 2277 if (hslot2 != nhslot2) { 2278 spin_lock(&hslot2->lock); 2279 udp_hash4_dec(hslot2); 2280 spin_unlock(&hslot2->lock); 2281 2282 spin_lock(&nhslot2->lock); 2283 udp_hash4_inc(nhslot2); 2284 spin_unlock(&nhslot2->lock); 2285 } 2286 } 2287 2288 spin_unlock_bh(&hslot->lock); 2289 } 2290 2291 udp_sk(sk)->udp_portaddr_hash = newhash; 2292 } 2293 } 2294 2295 static void udp_v4_rehash(struct sock *sk) 2296 { 2297 u16 new_hash = ipv4_portaddr_hash(sock_net(sk), 2298 inet_sk(sk)->inet_rcv_saddr, 2299 inet_sk(sk)->inet_num); 2300 u16 new_hash4 = udp_ehashfn(sock_net(sk), 2301 sk->sk_rcv_saddr, sk->sk_num, 2302 sk->sk_daddr, sk->sk_dport); 2303 2304 udp_lib_rehash(sk, new_hash, new_hash4); 2305 } 2306 2307 static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) 2308 { 2309 int rc; 2310 2311 if (inet_sk(sk)->inet_daddr) { 2312 sock_rps_save_rxhash(sk, skb); 2313 sk_mark_napi_id(sk, skb); 2314 sk_incoming_cpu_update(sk); 2315 } else { 2316 sk_mark_napi_id_once(sk, skb); 2317 } 2318 2319 rc = __udp_enqueue_schedule_skb(sk, skb); 2320 if (rc < 0) { 2321 struct net *net = sock_net(sk); 2322 int drop_reason; 2323 2324 /* Note that an ENOMEM error is charged twice */ 2325 if (rc == -ENOMEM) { 2326 UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS); 2327 drop_reason = SKB_DROP_REASON_SOCKET_RCVBUFF; 2328 } else { 2329 UDP_INC_STATS(net, UDP_MIB_MEMERRORS); 2330 drop_reason = SKB_DROP_REASON_PROTO_MEM; 2331 } 2332 UDP_INC_STATS(net, UDP_MIB_INERRORS); 2333 trace_udp_fail_queue_rcv_skb(rc, sk, skb); 2334 sk_skb_reason_drop(sk, skb, drop_reason); 2335 return -1; 2336 } 2337 2338 return 0; 2339 } 2340 2341 /* returns: 2342 * -1: error 2343 * 0: success 2344 * >0: "udp encap" protocol resubmission 2345 * 2346 * Note that in the success and error cases, the skb is assumed to 2347 * have either been requeued or freed. 2348 */ 2349 static int udp_queue_rcv_one_skb(struct sock *sk, struct sk_buff *skb) 2350 { 2351 enum skb_drop_reason drop_reason = SKB_DROP_REASON_NOT_SPECIFIED; 2352 struct udp_sock *up = udp_sk(sk); 2353 struct net *net = sock_net(sk); 2354 2355 /* 2356 * Charge it to the socket, dropping if the queue is full. 2357 */ 2358 if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) { 2359 drop_reason = SKB_DROP_REASON_XFRM_POLICY; 2360 goto drop; 2361 } 2362 nf_reset_ct(skb); 2363 2364 if (static_branch_unlikely(&udp_encap_needed_key) && 2365 READ_ONCE(up->encap_type)) { 2366 int (*encap_rcv)(struct sock *sk, struct sk_buff *skb); 2367 2368 /* 2369 * This is an encapsulation socket so pass the skb to 2370 * the socket's udp_encap_rcv() hook. Otherwise, just 2371 * fall through and pass this up the UDP socket. 2372 * up->encap_rcv() returns the following value: 2373 * =0 if skb was successfully passed to the encap 2374 * handler or was discarded by it. 2375 * >0 if skb should be passed on to UDP. 2376 * <0 if skb should be resubmitted as proto -N 2377 */ 2378 2379 /* if we're overly short, let UDP handle it */ 2380 encap_rcv = READ_ONCE(up->encap_rcv); 2381 if (encap_rcv) { 2382 int ret; 2383 2384 /* Verify checksum before giving to encap */ 2385 if (udp_lib_checksum_complete(skb)) 2386 goto csum_error; 2387 2388 ret = encap_rcv(sk, skb); 2389 if (ret <= 0) { 2390 __UDP_INC_STATS(net, UDP_MIB_INDATAGRAMS); 2391 return -ret; 2392 } 2393 } 2394 2395 /* FALLTHROUGH -- it's a UDP Packet */ 2396 } 2397 2398 prefetch(&sk->sk_rmem_alloc); 2399 if (rcu_access_pointer(sk->sk_filter) && 2400 udp_lib_checksum_complete(skb)) 2401 goto csum_error; 2402 2403 drop_reason = sk_filter_trim_cap(sk, skb, sizeof(struct udphdr)); 2404 if (drop_reason) 2405 goto drop; 2406 2407 udp_csum_pull_header(skb); 2408 2409 ipv4_pktinfo_prepare(sk, skb, true); 2410 return __udp_queue_rcv_skb(sk, skb); 2411 2412 csum_error: 2413 drop_reason = SKB_DROP_REASON_UDP_CSUM; 2414 __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS); 2415 drop: 2416 __UDP_INC_STATS(net, UDP_MIB_INERRORS); 2417 udp_drops_inc(sk); 2418 sk_skb_reason_drop(sk, skb, drop_reason); 2419 return -1; 2420 } 2421 2422 static int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) 2423 { 2424 struct sk_buff *next, *segs; 2425 int ret; 2426 2427 if (likely(!udp_unexpected_gso(sk, skb))) 2428 return udp_queue_rcv_one_skb(sk, skb); 2429 2430 BUILD_BUG_ON(sizeof(struct udp_skb_cb) > SKB_GSO_CB_OFFSET); 2431 __skb_push(skb, -skb_mac_offset(skb)); 2432 segs = udp_rcv_segment(sk, skb, true); 2433 skb_list_walk_safe(segs, skb, next) { 2434 __skb_pull(skb, skb_transport_offset(skb)); 2435 2436 udp_post_segment_fix_csum(skb); 2437 ret = udp_queue_rcv_one_skb(sk, skb); 2438 if (ret > 0) 2439 ip_protocol_deliver_rcu(dev_net(skb->dev), skb, ret); 2440 } 2441 return 0; 2442 } 2443 2444 /* For TCP sockets, sk_rx_dst is protected by socket lock 2445 * For UDP, we use xchg() to guard against concurrent changes. 2446 */ 2447 bool udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst) 2448 { 2449 struct dst_entry *old; 2450 2451 if (dst_hold_safe(dst)) { 2452 old = unrcu_pointer(xchg(&sk->sk_rx_dst, RCU_INITIALIZER(dst))); 2453 dst_release(old); 2454 return old != dst; 2455 } 2456 return false; 2457 } 2458 2459 /* 2460 * Multicasts and broadcasts go to each listener. 2461 * 2462 * Note: called only from the BH handler context. 2463 */ 2464 static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb, 2465 struct udphdr *uh, 2466 __be32 saddr, __be32 daddr) 2467 { 2468 struct udp_table *udptable = net->ipv4.udp_table; 2469 unsigned int hash2, hash2_any, offset; 2470 unsigned short hnum = ntohs(uh->dest); 2471 struct sock *sk, *first = NULL; 2472 int dif = skb->dev->ifindex; 2473 int sdif = inet_sdif(skb); 2474 struct hlist_node *node; 2475 struct udp_hslot *hslot; 2476 struct sk_buff *nskb; 2477 bool use_hash2; 2478 2479 hash2_any = 0; 2480 hash2 = 0; 2481 hslot = udp_hashslot(udptable, net, hnum); 2482 use_hash2 = hslot->count > 10; 2483 offset = offsetof(typeof(*sk), sk_node); 2484 2485 if (use_hash2) { 2486 hash2_any = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum) & 2487 udptable->mask; 2488 hash2 = ipv4_portaddr_hash(net, daddr, hnum) & udptable->mask; 2489 start_lookup: 2490 hslot = &udptable->hash2[hash2].hslot; 2491 offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node); 2492 } 2493 2494 sk_for_each_entry_offset_rcu(sk, node, &hslot->head, offset) { 2495 if (!__udp_is_mcast_sock(net, sk, uh->dest, daddr, 2496 uh->source, saddr, dif, sdif, hnum)) 2497 continue; 2498 2499 if (!first) { 2500 first = sk; 2501 continue; 2502 } 2503 nskb = skb_clone(skb, GFP_ATOMIC); 2504 2505 if (unlikely(!nskb)) { 2506 udp_drops_inc(sk); 2507 __UDP_INC_STATS(net, UDP_MIB_RCVBUFERRORS); 2508 __UDP_INC_STATS(net, UDP_MIB_INERRORS); 2509 continue; 2510 } 2511 if (udp_queue_rcv_skb(sk, nskb) > 0) 2512 consume_skb(nskb); 2513 } 2514 2515 /* Also lookup *:port if we are using hash2 and haven't done so yet. */ 2516 if (use_hash2 && hash2 != hash2_any) { 2517 hash2 = hash2_any; 2518 goto start_lookup; 2519 } 2520 2521 if (first) { 2522 if (udp_queue_rcv_skb(first, skb) > 0) 2523 consume_skb(skb); 2524 } else { 2525 kfree_skb(skb); 2526 __UDP_INC_STATS(net, UDP_MIB_IGNOREDMULTI); 2527 } 2528 return 0; 2529 } 2530 2531 /* Initialize UDP checksum. If exited with zero value (success), 2532 * CHECKSUM_UNNECESSARY means, that no more checks are required. 2533 * Otherwise, csum completion requires checksumming packet body, 2534 * including udp header and folding it to skb->csum. 2535 */ 2536 static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh) 2537 { 2538 int err; 2539 2540 /* Note, we are only interested in != 0 or == 0, thus the 2541 * force to int. 2542 */ 2543 err = (__force int)skb_checksum_init_zero_check(skb, IPPROTO_UDP, uh->check, 2544 inet_compute_pseudo); 2545 if (err) 2546 return err; 2547 2548 if (skb->ip_summed == CHECKSUM_COMPLETE && !skb->csum_valid) { 2549 /* If SW calculated the value, we know it's bad */ 2550 if (skb->csum_complete_sw) 2551 return 1; 2552 2553 /* HW says the value is bad. Let's validate that. 2554 * skb->csum is no longer the full packet checksum, 2555 * so don't treat it as such. 2556 */ 2557 skb_checksum_complete_unset(skb); 2558 } 2559 2560 return 0; 2561 } 2562 2563 /* wrapper for udp_queue_rcv_skb taking care of csum conversion and 2564 * return code conversion for ip layer consumption 2565 */ 2566 static int udp_unicast_rcv_skb(struct sock *sk, struct sk_buff *skb, 2567 struct udphdr *uh) 2568 { 2569 int ret; 2570 2571 if (inet_get_convert_csum(sk) && uh->check) 2572 skb_checksum_try_convert(skb, IPPROTO_UDP, inet_compute_pseudo); 2573 2574 ret = udp_queue_rcv_skb(sk, skb); 2575 2576 /* a return value > 0 means to resubmit the input, but 2577 * it wants the return to be -protocol, or 0 2578 */ 2579 if (ret > 0) 2580 return -ret; 2581 return 0; 2582 } 2583 2584 /* 2585 * All we need to do is get the socket, and then do a checksum. 2586 */ 2587 2588 int udp_rcv(struct sk_buff *skb) 2589 { 2590 struct rtable *rt = skb_rtable(skb); 2591 struct net *net = dev_net(skb->dev); 2592 struct sock *sk = NULL; 2593 unsigned short ulen; 2594 __be32 saddr, daddr; 2595 struct udphdr *uh; 2596 bool refcounted; 2597 int drop_reason; 2598 2599 drop_reason = SKB_DROP_REASON_NOT_SPECIFIED; 2600 2601 /* 2602 * Validate the packet. 2603 */ 2604 if (!pskb_may_pull(skb, sizeof(struct udphdr))) 2605 goto drop; /* No space for header. */ 2606 2607 uh = udp_hdr(skb); 2608 ulen = ntohs(uh->len); 2609 saddr = ip_hdr(skb)->saddr; 2610 daddr = ip_hdr(skb)->daddr; 2611 2612 if (ulen > skb->len) 2613 goto short_packet; 2614 2615 if (ulen < sizeof(*uh)) 2616 goto short_packet; 2617 2618 if (ulen < skb->len) { 2619 if (pskb_trim_rcsum(skb, ulen)) 2620 goto short_packet; 2621 2622 uh = udp_hdr(skb); 2623 } 2624 2625 if (udp4_csum_init(skb, uh)) 2626 goto csum_error; 2627 2628 sk = inet_steal_sock(net, skb, sizeof(struct udphdr), saddr, uh->source, daddr, uh->dest, 2629 &refcounted, udp_ehashfn); 2630 if (IS_ERR(sk)) 2631 goto no_sk; 2632 2633 if (sk) { 2634 struct dst_entry *dst = skb_dst(skb); 2635 int ret; 2636 2637 if (unlikely(rcu_dereference(sk->sk_rx_dst) != dst)) 2638 udp_sk_rx_dst_set(sk, dst); 2639 2640 ret = udp_unicast_rcv_skb(sk, skb, uh); 2641 if (refcounted) 2642 sock_put(sk); 2643 return ret; 2644 } 2645 2646 if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST)) 2647 return __udp4_lib_mcast_deliver(net, skb, uh, saddr, daddr); 2648 2649 sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest); 2650 if (sk) 2651 return udp_unicast_rcv_skb(sk, skb, uh); 2652 no_sk: 2653 if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) 2654 goto drop; 2655 nf_reset_ct(skb); 2656 2657 /* No socket. Drop packet silently, if checksum is wrong */ 2658 if (udp_lib_checksum_complete(skb)) 2659 goto csum_error; 2660 2661 drop_reason = SKB_DROP_REASON_NO_SOCKET; 2662 __UDP_INC_STATS(net, UDP_MIB_NOPORTS); 2663 icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0); 2664 2665 /* 2666 * Hmm. We got an UDP packet to a port to which we 2667 * don't wanna listen. Ignore it. 2668 */ 2669 sk_skb_reason_drop(sk, skb, drop_reason); 2670 return 0; 2671 2672 short_packet: 2673 drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL; 2674 net_dbg_ratelimited("UDP: short packet: From %pI4:%u %d/%d to %pI4:%u\n", 2675 &saddr, ntohs(uh->source), 2676 ulen, skb->len, 2677 &daddr, ntohs(uh->dest)); 2678 goto drop; 2679 2680 csum_error: 2681 /* 2682 * RFC1122: OK. Discards the bad packet silently (as far as 2683 * the network is concerned, anyway) as per 4.1.3.4 (MUST). 2684 */ 2685 drop_reason = SKB_DROP_REASON_UDP_CSUM; 2686 net_dbg_ratelimited("UDP: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n", 2687 &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest), 2688 ulen); 2689 __UDP_INC_STATS(net, UDP_MIB_CSUMERRORS); 2690 drop: 2691 __UDP_INC_STATS(net, UDP_MIB_INERRORS); 2692 sk_skb_reason_drop(sk, skb, drop_reason); 2693 return 0; 2694 } 2695 2696 /* We can only early demux multicast if there is a single matching socket. 2697 * If more than one socket found returns NULL 2698 */ 2699 static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net, 2700 __be16 loc_port, __be32 loc_addr, 2701 __be16 rmt_port, __be32 rmt_addr, 2702 int dif, int sdif) 2703 { 2704 struct udp_table *udptable = net->ipv4.udp_table; 2705 unsigned short hnum = ntohs(loc_port); 2706 struct sock *sk, *result; 2707 struct udp_hslot *hslot; 2708 unsigned int slot; 2709 2710 slot = udp_hashfn(net, hnum, udptable->mask); 2711 hslot = &udptable->hash[slot]; 2712 2713 /* Do not bother scanning a too big list */ 2714 if (hslot->count > 10) 2715 return NULL; 2716 2717 result = NULL; 2718 sk_for_each_rcu(sk, &hslot->head) { 2719 if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr, 2720 rmt_port, rmt_addr, dif, sdif, hnum)) { 2721 if (result) 2722 return NULL; 2723 result = sk; 2724 } 2725 } 2726 2727 return result; 2728 } 2729 2730 /* For unicast we should only early demux connected sockets or we can 2731 * break forwarding setups. The chains here can be long so only check 2732 * if the first socket is an exact match and if not move on. 2733 */ 2734 static struct sock *__udp4_lib_demux_lookup(struct net *net, 2735 __be16 loc_port, __be32 loc_addr, 2736 __be16 rmt_port, __be32 rmt_addr, 2737 int dif, int sdif) 2738 { 2739 struct udp_table *udptable = net->ipv4.udp_table; 2740 INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr); 2741 unsigned short hnum = ntohs(loc_port); 2742 struct udp_hslot *hslot2; 2743 unsigned int hash2; 2744 __portpair ports; 2745 struct sock *sk; 2746 2747 hash2 = ipv4_portaddr_hash(net, loc_addr, hnum); 2748 hslot2 = udp_hashslot2(udptable, hash2); 2749 ports = INET_COMBINED_PORTS(rmt_port, hnum); 2750 2751 udp_portaddr_for_each_entry_rcu(sk, &hslot2->head) { 2752 if (inet_match(net, sk, acookie, ports, dif, sdif)) 2753 return sk; 2754 /* Only check first socket in chain */ 2755 break; 2756 } 2757 return NULL; 2758 } 2759 2760 enum skb_drop_reason udp_v4_early_demux(struct sk_buff *skb) 2761 { 2762 struct net *net = dev_net(skb->dev); 2763 struct in_device *in_dev = NULL; 2764 const struct iphdr *iph; 2765 const struct udphdr *uh; 2766 struct sock *sk = NULL; 2767 struct dst_entry *dst; 2768 int dif = skb->dev->ifindex; 2769 int sdif = inet_sdif(skb); 2770 int ours; 2771 2772 /* validate the packet */ 2773 if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr))) 2774 return SKB_NOT_DROPPED_YET; 2775 2776 iph = ip_hdr(skb); 2777 uh = udp_hdr(skb); 2778 2779 if (skb->pkt_type == PACKET_MULTICAST) { 2780 in_dev = __in_dev_get_rcu(skb->dev); 2781 2782 if (!in_dev) 2783 return SKB_NOT_DROPPED_YET; 2784 2785 ours = ip_check_mc_rcu(in_dev, iph->daddr, iph->saddr, 2786 iph->protocol); 2787 if (!ours) 2788 return SKB_NOT_DROPPED_YET; 2789 2790 sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr, 2791 uh->source, iph->saddr, 2792 dif, sdif); 2793 } else if (skb->pkt_type == PACKET_HOST) { 2794 sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr, 2795 uh->source, iph->saddr, dif, sdif); 2796 } 2797 2798 if (!sk) 2799 return SKB_NOT_DROPPED_YET; 2800 2801 skb->sk = sk; 2802 DEBUG_NET_WARN_ON_ONCE(sk_is_refcounted(sk)); 2803 skb->destructor = sock_pfree; 2804 dst = rcu_dereference(sk->sk_rx_dst); 2805 2806 if (dst) 2807 dst = dst_check(dst, 0); 2808 if (dst) { 2809 u32 itag = 0; 2810 2811 /* set noref for now. 2812 * any place which wants to hold dst has to call 2813 * dst_hold_safe() 2814 */ 2815 skb_dst_set_noref(skb, dst); 2816 2817 /* for unconnected multicast sockets we need to validate 2818 * the source on each packet 2819 */ 2820 if (!inet_sk(sk)->inet_daddr && in_dev) 2821 return ip_mc_validate_source(skb, iph->daddr, 2822 iph->saddr, 2823 ip4h_dscp(iph), 2824 skb->dev, in_dev, &itag); 2825 } 2826 return SKB_NOT_DROPPED_YET; 2827 } 2828 2829 static void udp_destroy_sock(struct sock *sk) 2830 { 2831 struct udp_sock *up = udp_sk(sk); 2832 bool slow = lock_sock_fast(sk); 2833 2834 /* protects from races with udp_abort() */ 2835 sock_set_flag(sk, SOCK_DEAD); 2836 udp_flush_pending_frames(sk); 2837 unlock_sock_fast(sk, slow); 2838 if (static_branch_unlikely(&udp_encap_needed_key)) { 2839 if (up->encap_type) { 2840 void (*encap_destroy)(struct sock *sk); 2841 encap_destroy = READ_ONCE(up->encap_destroy); 2842 if (encap_destroy) 2843 encap_destroy(sk); 2844 } 2845 if (udp_test_bit(ENCAP_ENABLED, sk)) { 2846 static_branch_dec(&udp_encap_needed_key); 2847 udp_tunnel_cleanup_gro(sk); 2848 } 2849 } 2850 } 2851 2852 typedef struct sk_buff *(*udp_gro_receive_t)(struct sock *sk, 2853 struct list_head *head, 2854 struct sk_buff *skb); 2855 2856 static void set_xfrm_gro_udp_encap_rcv(__u16 encap_type, unsigned short family, 2857 struct sock *sk) 2858 { 2859 #ifdef CONFIG_XFRM 2860 udp_gro_receive_t new_gro_receive; 2861 2862 if (udp_test_bit(GRO_ENABLED, sk) && encap_type == UDP_ENCAP_ESPINUDP) { 2863 if (IS_ENABLED(CONFIG_IPV6) && family == AF_INET6) 2864 new_gro_receive = xfrm6_gro_udp_encap_rcv; 2865 else 2866 new_gro_receive = xfrm4_gro_udp_encap_rcv; 2867 2868 if (udp_sk(sk)->gro_receive != new_gro_receive) { 2869 /* 2870 * With IPV6_ADDRFORM the gro callback could change 2871 * after being set, unregister the old one, if valid. 2872 */ 2873 if (udp_sk(sk)->gro_receive) 2874 udp_tunnel_update_gro_rcv(sk, false); 2875 2876 WRITE_ONCE(udp_sk(sk)->gro_receive, new_gro_receive); 2877 udp_tunnel_update_gro_rcv(sk, true); 2878 } 2879 } 2880 #endif 2881 } 2882 2883 /* 2884 * Socket option code for UDP 2885 */ 2886 int udp_lib_setsockopt(struct sock *sk, int level, int optname, 2887 sockptr_t optval, unsigned int optlen, 2888 int (*push_pending_frames)(struct sock *)) 2889 { 2890 struct udp_sock *up = udp_sk(sk); 2891 int val, valbool; 2892 int err = 0; 2893 2894 if (level == SOL_SOCKET) { 2895 err = sk_setsockopt(sk, level, optname, optval, optlen); 2896 2897 if (optname == SO_RCVBUF || optname == SO_RCVBUFFORCE) { 2898 sockopt_lock_sock(sk); 2899 /* paired with READ_ONCE in udp_rmem_release() */ 2900 WRITE_ONCE(up->forward_threshold, sk->sk_rcvbuf >> 2); 2901 sockopt_release_sock(sk); 2902 } 2903 return err; 2904 } 2905 2906 if (optlen < sizeof(int)) 2907 return -EINVAL; 2908 2909 if (copy_from_sockptr(&val, optval, sizeof(val))) 2910 return -EFAULT; 2911 2912 valbool = val ? 1 : 0; 2913 2914 switch (optname) { 2915 case UDP_CORK: 2916 if (val != 0) { 2917 udp_set_bit(CORK, sk); 2918 } else { 2919 udp_clear_bit(CORK, sk); 2920 lock_sock(sk); 2921 push_pending_frames(sk); 2922 release_sock(sk); 2923 } 2924 break; 2925 2926 case UDP_ENCAP: 2927 sockopt_lock_sock(sk); 2928 switch (val) { 2929 case 0: 2930 #ifdef CONFIG_XFRM 2931 case UDP_ENCAP_ESPINUDP: 2932 set_xfrm_gro_udp_encap_rcv(val, sk->sk_family, sk); 2933 #if IS_ENABLED(CONFIG_IPV6) 2934 if (sk->sk_family == AF_INET6) 2935 WRITE_ONCE(up->encap_rcv, 2936 xfrm6_udp_encap_rcv); 2937 else 2938 #endif 2939 WRITE_ONCE(up->encap_rcv, 2940 xfrm4_udp_encap_rcv); 2941 #endif 2942 fallthrough; 2943 case UDP_ENCAP_L2TPINUDP: 2944 WRITE_ONCE(up->encap_type, val); 2945 udp_tunnel_encap_enable(sk); 2946 break; 2947 default: 2948 err = -ENOPROTOOPT; 2949 break; 2950 } 2951 sockopt_release_sock(sk); 2952 break; 2953 2954 case UDP_NO_CHECK6_TX: 2955 udp_set_no_check6_tx(sk, valbool); 2956 break; 2957 2958 case UDP_NO_CHECK6_RX: 2959 udp_set_no_check6_rx(sk, valbool); 2960 break; 2961 2962 case UDP_SEGMENT: 2963 if (val < 0 || val > USHRT_MAX) 2964 return -EINVAL; 2965 WRITE_ONCE(up->gso_size, val); 2966 break; 2967 2968 case UDP_GRO: 2969 sockopt_lock_sock(sk); 2970 /* when enabling GRO, accept the related GSO packet type */ 2971 if (valbool) 2972 udp_tunnel_encap_enable(sk); 2973 udp_assign_bit(GRO_ENABLED, sk, valbool); 2974 udp_assign_bit(ACCEPT_L4, sk, valbool); 2975 set_xfrm_gro_udp_encap_rcv(up->encap_type, sk->sk_family, sk); 2976 sockopt_release_sock(sk); 2977 break; 2978 2979 default: 2980 err = -ENOPROTOOPT; 2981 break; 2982 } 2983 2984 return err; 2985 } 2986 2987 static int udp_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval, 2988 unsigned int optlen) 2989 { 2990 if (level == SOL_UDP || level == SOL_SOCKET) 2991 return udp_lib_setsockopt(sk, level, optname, 2992 optval, optlen, 2993 udp_push_pending_frames); 2994 return ip_setsockopt(sk, level, optname, optval, optlen); 2995 } 2996 2997 int udp_lib_getsockopt(struct sock *sk, int level, int optname, 2998 char __user *optval, int __user *optlen) 2999 { 3000 struct udp_sock *up = udp_sk(sk); 3001 int val, len; 3002 3003 if (get_user(len, optlen)) 3004 return -EFAULT; 3005 3006 if (len < 0) 3007 return -EINVAL; 3008 3009 len = min_t(unsigned int, len, sizeof(int)); 3010 3011 switch (optname) { 3012 case UDP_CORK: 3013 val = udp_test_bit(CORK, sk); 3014 break; 3015 3016 case UDP_ENCAP: 3017 val = READ_ONCE(up->encap_type); 3018 break; 3019 3020 case UDP_NO_CHECK6_TX: 3021 val = udp_get_no_check6_tx(sk); 3022 break; 3023 3024 case UDP_NO_CHECK6_RX: 3025 val = udp_get_no_check6_rx(sk); 3026 break; 3027 3028 case UDP_SEGMENT: 3029 val = READ_ONCE(up->gso_size); 3030 break; 3031 3032 case UDP_GRO: 3033 val = udp_test_bit(GRO_ENABLED, sk); 3034 break; 3035 3036 default: 3037 return -ENOPROTOOPT; 3038 } 3039 3040 if (put_user(len, optlen)) 3041 return -EFAULT; 3042 if (copy_to_user(optval, &val, len)) 3043 return -EFAULT; 3044 return 0; 3045 } 3046 3047 static int udp_getsockopt(struct sock *sk, int level, int optname, 3048 char __user *optval, int __user *optlen) 3049 { 3050 if (level == SOL_UDP) 3051 return udp_lib_getsockopt(sk, level, optname, optval, optlen); 3052 return ip_getsockopt(sk, level, optname, optval, optlen); 3053 } 3054 3055 /** 3056 * udp_poll - wait for a UDP event. 3057 * @file: - file struct 3058 * @sock: - socket 3059 * @wait: - poll table 3060 * 3061 * This is same as datagram poll, except for the special case of 3062 * blocking sockets. If application is using a blocking fd 3063 * and a packet with checksum error is in the queue; 3064 * then it could get return from select indicating data available 3065 * but then block when reading it. Add special case code 3066 * to work around these arguably broken applications. 3067 */ 3068 __poll_t udp_poll(struct file *file, struct socket *sock, poll_table *wait) 3069 { 3070 __poll_t mask = datagram_poll(file, sock, wait); 3071 struct sock *sk = sock->sk; 3072 3073 if (!skb_queue_empty_lockless(&udp_sk(sk)->reader_queue)) 3074 mask |= EPOLLIN | EPOLLRDNORM; 3075 3076 /* Check for false positives due to checksum errors */ 3077 if ((mask & EPOLLRDNORM) && !(file->f_flags & O_NONBLOCK) && 3078 !(sk->sk_shutdown & RCV_SHUTDOWN) && first_packet_length(sk) == -1) 3079 mask &= ~(EPOLLIN | EPOLLRDNORM); 3080 3081 /* psock ingress_msg queue should not contain any bad checksum frames */ 3082 if (sk_is_readable(sk)) 3083 mask |= EPOLLIN | EPOLLRDNORM; 3084 return mask; 3085 3086 } 3087 3088 int udp_abort(struct sock *sk, int err) 3089 { 3090 if (!has_current_bpf_ctx()) 3091 lock_sock(sk); 3092 3093 /* udp{v6}_destroy_sock() sets it under the sk lock, avoid racing 3094 * with close() 3095 */ 3096 if (sock_flag(sk, SOCK_DEAD)) 3097 goto out; 3098 3099 sk->sk_err = err; 3100 sk_error_report(sk); 3101 __udp_disconnect(sk, 0); 3102 3103 out: 3104 if (!has_current_bpf_ctx()) 3105 release_sock(sk); 3106 3107 return 0; 3108 } 3109 3110 struct proto udp_prot = { 3111 .name = "UDP", 3112 .owner = THIS_MODULE, 3113 .close = udp_lib_close, 3114 .pre_connect = udp_pre_connect, 3115 .connect = udp_connect, 3116 .disconnect = udp_disconnect, 3117 .ioctl = udp_ioctl, 3118 .init = udp_init_sock, 3119 .destroy = udp_destroy_sock, 3120 .setsockopt = udp_setsockopt, 3121 .getsockopt = udp_getsockopt, 3122 .sendmsg = udp_sendmsg, 3123 .recvmsg = udp_recvmsg, 3124 .splice_eof = udp_splice_eof, 3125 .release_cb = ip4_datagram_release_cb, 3126 .hash = udp_lib_hash, 3127 .unhash = udp_lib_unhash, 3128 .rehash = udp_v4_rehash, 3129 .get_port = udp_v4_get_port, 3130 .put_port = udp_lib_unhash, 3131 #ifdef CONFIG_BPF_SYSCALL 3132 .psock_update_sk_prot = udp_bpf_update_proto, 3133 #endif 3134 .memory_allocated = &net_aligned_data.udp_memory_allocated, 3135 .per_cpu_fw_alloc = &udp_memory_per_cpu_fw_alloc, 3136 3137 .sysctl_mem = sysctl_udp_mem, 3138 .sysctl_wmem_offset = offsetof(struct net, ipv4.sysctl_udp_wmem_min), 3139 .sysctl_rmem_offset = offsetof(struct net, ipv4.sysctl_udp_rmem_min), 3140 .obj_size = sizeof(struct udp_sock), 3141 .diag_destroy = udp_abort, 3142 }; 3143 EXPORT_SYMBOL(udp_prot); 3144 3145 /* ------------------------------------------------------------------------ */ 3146 #ifdef CONFIG_PROC_FS 3147 3148 static unsigned short seq_file_family(const struct seq_file *seq); 3149 static bool seq_sk_match(struct seq_file *seq, const struct sock *sk) 3150 { 3151 unsigned short family = seq_file_family(seq); 3152 3153 /* AF_UNSPEC is used as a match all */ 3154 return ((family == AF_UNSPEC || family == sk->sk_family) && 3155 net_eq(sock_net(sk), seq_file_net(seq))); 3156 } 3157 3158 #ifdef CONFIG_BPF_SYSCALL 3159 static const struct seq_operations bpf_iter_udp_seq_ops; 3160 #endif 3161 3162 static struct sock *udp_get_first(struct seq_file *seq, int start) 3163 { 3164 struct udp_iter_state *state = seq->private; 3165 struct net *net = seq_file_net(seq); 3166 struct udp_table *udptable; 3167 struct sock *sk; 3168 3169 udptable = net->ipv4.udp_table; 3170 3171 for (state->bucket = start; state->bucket <= udptable->mask; 3172 ++state->bucket) { 3173 struct udp_hslot *hslot = &udptable->hash[state->bucket]; 3174 3175 if (hlist_empty(&hslot->head)) 3176 continue; 3177 3178 spin_lock_bh(&hslot->lock); 3179 sk_for_each(sk, &hslot->head) { 3180 if (seq_sk_match(seq, sk)) 3181 goto found; 3182 } 3183 spin_unlock_bh(&hslot->lock); 3184 } 3185 sk = NULL; 3186 found: 3187 return sk; 3188 } 3189 3190 static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk) 3191 { 3192 struct udp_iter_state *state = seq->private; 3193 struct net *net = seq_file_net(seq); 3194 struct udp_table *udptable; 3195 3196 do { 3197 sk = sk_next(sk); 3198 } while (sk && !seq_sk_match(seq, sk)); 3199 3200 if (!sk) { 3201 udptable = net->ipv4.udp_table; 3202 3203 if (state->bucket <= udptable->mask) 3204 spin_unlock_bh(&udptable->hash[state->bucket].lock); 3205 3206 return udp_get_first(seq, state->bucket + 1); 3207 } 3208 return sk; 3209 } 3210 3211 static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos) 3212 { 3213 struct sock *sk = udp_get_first(seq, 0); 3214 3215 if (sk) 3216 while (pos && (sk = udp_get_next(seq, sk)) != NULL) 3217 --pos; 3218 return pos ? NULL : sk; 3219 } 3220 3221 void *udp_seq_start(struct seq_file *seq, loff_t *pos) 3222 { 3223 struct udp_iter_state *state = seq->private; 3224 state->bucket = MAX_UDP_PORTS; 3225 3226 return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN; 3227 } 3228 3229 void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos) 3230 { 3231 struct sock *sk; 3232 3233 if (v == SEQ_START_TOKEN) 3234 sk = udp_get_idx(seq, 0); 3235 else 3236 sk = udp_get_next(seq, v); 3237 3238 ++*pos; 3239 return sk; 3240 } 3241 3242 void udp_seq_stop(struct seq_file *seq, void *v) 3243 { 3244 struct udp_iter_state *state = seq->private; 3245 struct udp_table *udptable; 3246 3247 udptable = seq_file_net(seq)->ipv4.udp_table; 3248 3249 if (state->bucket <= udptable->mask) 3250 spin_unlock_bh(&udptable->hash[state->bucket].lock); 3251 } 3252 3253 /* ------------------------------------------------------------------------ */ 3254 static void udp4_format_sock(struct sock *sp, struct seq_file *f, 3255 int bucket) 3256 { 3257 struct inet_sock *inet = inet_sk(sp); 3258 __be32 dest = inet->inet_daddr; 3259 __be32 src = inet->inet_rcv_saddr; 3260 __u16 destp = ntohs(inet->inet_dport); 3261 __u16 srcp = ntohs(inet->inet_sport); 3262 3263 seq_printf(f, "%5d: %08X:%04X %08X:%04X" 3264 " %02X %08X:%08X %02X:%08lX %08X %5u %8d %llu %d %pK %u", 3265 bucket, src, srcp, dest, destp, sp->sk_state, 3266 sk_wmem_alloc_get(sp), 3267 udp_rqueue_get(sp), 3268 0, 0L, 0, 3269 from_kuid_munged(seq_user_ns(f), sk_uid(sp)), 3270 0, sock_i_ino(sp), 3271 refcount_read(&sp->sk_refcnt), sp, 3272 sk_drops_read(sp)); 3273 } 3274 3275 static int udp4_seq_show(struct seq_file *seq, void *v) 3276 { 3277 seq_setwidth(seq, 127); 3278 if (v == SEQ_START_TOKEN) 3279 seq_puts(seq, " sl local_address rem_address st tx_queue " 3280 "rx_queue tr tm->when retrnsmt uid timeout " 3281 "inode ref pointer drops"); 3282 else { 3283 struct udp_iter_state *state = seq->private; 3284 3285 udp4_format_sock(v, seq, state->bucket); 3286 } 3287 seq_pad(seq, '\n'); 3288 return 0; 3289 } 3290 3291 #ifdef CONFIG_BPF_SYSCALL 3292 struct bpf_iter__udp { 3293 __bpf_md_ptr(struct bpf_iter_meta *, meta); 3294 __bpf_md_ptr(struct udp_sock *, udp_sk); 3295 uid_t uid __aligned(8); 3296 int bucket __aligned(8); 3297 }; 3298 3299 union bpf_udp_iter_batch_item { 3300 struct sock *sk; 3301 __u64 cookie; 3302 }; 3303 3304 struct bpf_udp_iter_state { 3305 struct udp_iter_state state; 3306 unsigned int cur_sk; 3307 unsigned int end_sk; 3308 unsigned int max_sk; 3309 union bpf_udp_iter_batch_item *batch; 3310 }; 3311 3312 static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter, 3313 unsigned int new_batch_sz, gfp_t flags); 3314 static struct sock *bpf_iter_udp_resume(struct sock *first_sk, 3315 union bpf_udp_iter_batch_item *cookies, 3316 int n_cookies) 3317 { 3318 struct sock *sk = NULL; 3319 int i; 3320 3321 for (i = 0; i < n_cookies; i++) { 3322 sk = first_sk; 3323 udp_portaddr_for_each_entry_from(sk) 3324 if (cookies[i].cookie == atomic64_read(&sk->sk_cookie)) 3325 goto done; 3326 } 3327 done: 3328 return sk; 3329 } 3330 3331 static struct sock *bpf_iter_udp_batch(struct seq_file *seq) 3332 { 3333 struct bpf_udp_iter_state *iter = seq->private; 3334 struct udp_iter_state *state = &iter->state; 3335 unsigned int find_cookie, end_cookie; 3336 struct net *net = seq_file_net(seq); 3337 struct udp_table *udptable; 3338 unsigned int batch_sks = 0; 3339 int resume_bucket; 3340 int resizes = 0; 3341 struct sock *sk; 3342 int err = 0; 3343 3344 resume_bucket = state->bucket; 3345 3346 /* The current batch is done, so advance the bucket. */ 3347 if (iter->cur_sk == iter->end_sk) 3348 state->bucket++; 3349 3350 udptable = net->ipv4.udp_table; 3351 3352 again: 3353 /* New batch for the next bucket. 3354 * Iterate over the hash table to find a bucket with sockets matching 3355 * the iterator attributes, and return the first matching socket from 3356 * the bucket. The remaining matched sockets from the bucket are batched 3357 * before releasing the bucket lock. This allows BPF programs that are 3358 * called in seq_show to acquire the bucket lock if needed. 3359 */ 3360 find_cookie = iter->cur_sk; 3361 end_cookie = iter->end_sk; 3362 iter->cur_sk = 0; 3363 iter->end_sk = 0; 3364 batch_sks = 0; 3365 3366 for (; state->bucket <= udptable->mask; state->bucket++) { 3367 struct udp_hslot *hslot2 = &udptable->hash2[state->bucket].hslot; 3368 3369 if (hlist_empty(&hslot2->head)) 3370 goto next_bucket; 3371 3372 spin_lock_bh(&hslot2->lock); 3373 sk = hlist_entry_safe(hslot2->head.first, struct sock, 3374 __sk_common.skc_portaddr_node); 3375 /* Resume from the first (in iteration order) unseen socket from 3376 * the last batch that still exists in resume_bucket. Most of 3377 * the time this will just be where the last iteration left off 3378 * in resume_bucket unless that socket disappeared between 3379 * reads. 3380 */ 3381 if (state->bucket == resume_bucket) 3382 sk = bpf_iter_udp_resume(sk, &iter->batch[find_cookie], 3383 end_cookie - find_cookie); 3384 fill_batch: 3385 udp_portaddr_for_each_entry_from(sk) { 3386 if (seq_sk_match(seq, sk)) { 3387 if (iter->end_sk < iter->max_sk) { 3388 sock_hold(sk); 3389 iter->batch[iter->end_sk++].sk = sk; 3390 } 3391 batch_sks++; 3392 } 3393 } 3394 3395 /* Allocate a larger batch and try again. */ 3396 if (unlikely(resizes <= 1 && iter->end_sk && 3397 iter->end_sk != batch_sks)) { 3398 resizes++; 3399 3400 /* First, try with GFP_USER to maximize the chances of 3401 * grabbing more memory. 3402 */ 3403 if (resizes == 1) { 3404 spin_unlock_bh(&hslot2->lock); 3405 err = bpf_iter_udp_realloc_batch(iter, 3406 batch_sks * 3 / 2, 3407 GFP_USER); 3408 if (err) 3409 return ERR_PTR(err); 3410 /* Start over. */ 3411 goto again; 3412 } 3413 3414 /* Next, hold onto the lock, so the bucket doesn't 3415 * change while we get the rest of the sockets. 3416 */ 3417 err = bpf_iter_udp_realloc_batch(iter, batch_sks, 3418 GFP_NOWAIT); 3419 if (err) { 3420 spin_unlock_bh(&hslot2->lock); 3421 return ERR_PTR(err); 3422 } 3423 3424 /* Pick up where we left off. */ 3425 sk = iter->batch[iter->end_sk - 1].sk; 3426 sk = hlist_entry_safe(sk->__sk_common.skc_portaddr_node.next, 3427 struct sock, 3428 __sk_common.skc_portaddr_node); 3429 batch_sks = iter->end_sk; 3430 goto fill_batch; 3431 } 3432 3433 spin_unlock_bh(&hslot2->lock); 3434 3435 if (iter->end_sk) 3436 break; 3437 next_bucket: 3438 resizes = 0; 3439 } 3440 3441 WARN_ON_ONCE(iter->end_sk != batch_sks); 3442 return iter->end_sk ? iter->batch[0].sk : NULL; 3443 } 3444 3445 static void *bpf_iter_udp_seq_next(struct seq_file *seq, void *v, loff_t *pos) 3446 { 3447 struct bpf_udp_iter_state *iter = seq->private; 3448 struct sock *sk; 3449 3450 /* Whenever seq_next() is called, the iter->cur_sk is 3451 * done with seq_show(), so unref the iter->cur_sk. 3452 */ 3453 if (iter->cur_sk < iter->end_sk) 3454 sock_put(iter->batch[iter->cur_sk++].sk); 3455 3456 /* After updating iter->cur_sk, check if there are more sockets 3457 * available in the current bucket batch. 3458 */ 3459 if (iter->cur_sk < iter->end_sk) 3460 sk = iter->batch[iter->cur_sk].sk; 3461 else 3462 /* Prepare a new batch. */ 3463 sk = bpf_iter_udp_batch(seq); 3464 3465 ++*pos; 3466 return sk; 3467 } 3468 3469 static void *bpf_iter_udp_seq_start(struct seq_file *seq, loff_t *pos) 3470 { 3471 /* bpf iter does not support lseek, so it always 3472 * continue from where it was stop()-ped. 3473 */ 3474 if (*pos) 3475 return bpf_iter_udp_batch(seq); 3476 3477 return SEQ_START_TOKEN; 3478 } 3479 3480 static int udp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta, 3481 struct udp_sock *udp_sk, uid_t uid, int bucket) 3482 { 3483 struct bpf_iter__udp ctx; 3484 3485 meta->seq_num--; /* skip SEQ_START_TOKEN */ 3486 ctx.meta = meta; 3487 ctx.udp_sk = udp_sk; 3488 ctx.uid = uid; 3489 ctx.bucket = bucket; 3490 return bpf_iter_run_prog(prog, &ctx); 3491 } 3492 3493 static int bpf_iter_udp_seq_show(struct seq_file *seq, void *v) 3494 { 3495 struct udp_iter_state *state = seq->private; 3496 struct bpf_iter_meta meta; 3497 struct bpf_prog *prog; 3498 struct sock *sk = v; 3499 uid_t uid; 3500 int ret; 3501 3502 if (v == SEQ_START_TOKEN) 3503 return 0; 3504 3505 lock_sock(sk); 3506 3507 if (unlikely(sk_unhashed(sk))) { 3508 ret = SEQ_SKIP; 3509 goto unlock; 3510 } 3511 3512 uid = from_kuid_munged(seq_user_ns(seq), sk_uid(sk)); 3513 meta.seq = seq; 3514 prog = bpf_iter_get_info(&meta, false); 3515 ret = udp_prog_seq_show(prog, &meta, v, uid, state->bucket); 3516 3517 unlock: 3518 release_sock(sk); 3519 return ret; 3520 } 3521 3522 static void bpf_iter_udp_put_batch(struct bpf_udp_iter_state *iter) 3523 { 3524 union bpf_udp_iter_batch_item *item; 3525 unsigned int cur_sk = iter->cur_sk; 3526 __u64 cookie; 3527 3528 /* Remember the cookies of the sockets we haven't seen yet, so we can 3529 * pick up where we left off next time around. 3530 */ 3531 while (cur_sk < iter->end_sk) { 3532 item = &iter->batch[cur_sk++]; 3533 cookie = sock_gen_cookie(item->sk); 3534 sock_put(item->sk); 3535 item->cookie = cookie; 3536 } 3537 } 3538 3539 static void bpf_iter_udp_seq_stop(struct seq_file *seq, void *v) 3540 { 3541 struct bpf_udp_iter_state *iter = seq->private; 3542 struct bpf_iter_meta meta; 3543 struct bpf_prog *prog; 3544 3545 if (!v) { 3546 meta.seq = seq; 3547 prog = bpf_iter_get_info(&meta, true); 3548 if (prog) 3549 (void)udp_prog_seq_show(prog, &meta, v, 0, 0); 3550 } 3551 3552 if (iter->cur_sk < iter->end_sk) 3553 bpf_iter_udp_put_batch(iter); 3554 } 3555 3556 static const struct seq_operations bpf_iter_udp_seq_ops = { 3557 .start = bpf_iter_udp_seq_start, 3558 .next = bpf_iter_udp_seq_next, 3559 .stop = bpf_iter_udp_seq_stop, 3560 .show = bpf_iter_udp_seq_show, 3561 }; 3562 #endif 3563 3564 static unsigned short seq_file_family(const struct seq_file *seq) 3565 { 3566 const struct udp_seq_afinfo *afinfo; 3567 3568 #ifdef CONFIG_BPF_SYSCALL 3569 /* BPF iterator: bpf programs to filter sockets. */ 3570 if (seq->op == &bpf_iter_udp_seq_ops) 3571 return AF_UNSPEC; 3572 #endif 3573 3574 /* Proc fs iterator */ 3575 afinfo = pde_data(file_inode(seq->file)); 3576 return afinfo->family; 3577 } 3578 3579 static const struct seq_operations udp_seq_ops = { 3580 .start = udp_seq_start, 3581 .next = udp_seq_next, 3582 .stop = udp_seq_stop, 3583 .show = udp4_seq_show, 3584 }; 3585 3586 static struct udp_seq_afinfo udp4_seq_afinfo = { 3587 .family = AF_INET, 3588 }; 3589 3590 static int __net_init udp4_proc_init_net(struct net *net) 3591 { 3592 if (!proc_create_net_data("udp", 0444, net->proc_net, &udp_seq_ops, 3593 sizeof(struct udp_iter_state), &udp4_seq_afinfo)) 3594 return -ENOMEM; 3595 return 0; 3596 } 3597 3598 static void __net_exit udp4_proc_exit_net(struct net *net) 3599 { 3600 remove_proc_entry("udp", net->proc_net); 3601 } 3602 3603 static struct pernet_operations udp4_net_ops = { 3604 .init = udp4_proc_init_net, 3605 .exit = udp4_proc_exit_net, 3606 }; 3607 3608 int __init udp4_proc_init(void) 3609 { 3610 return register_pernet_subsys(&udp4_net_ops); 3611 } 3612 3613 void udp4_proc_exit(void) 3614 { 3615 unregister_pernet_subsys(&udp4_net_ops); 3616 } 3617 #endif /* CONFIG_PROC_FS */ 3618 3619 static __initdata unsigned long uhash_entries; 3620 static int __init set_uhash_entries(char *str) 3621 { 3622 ssize_t ret; 3623 3624 if (!str) 3625 return 0; 3626 3627 ret = kstrtoul(str, 0, &uhash_entries); 3628 if (ret) 3629 return 0; 3630 3631 if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN) 3632 uhash_entries = UDP_HTABLE_SIZE_MIN; 3633 return 1; 3634 } 3635 __setup("uhash_entries=", set_uhash_entries); 3636 3637 static void __init udp_table_init(struct udp_table *table, const char *name) 3638 { 3639 unsigned int i, slot_size; 3640 3641 slot_size = sizeof(struct udp_hslot) + sizeof(struct udp_hslot_main) + 3642 udp_hash4_slot_size(); 3643 table->hash = alloc_large_system_hash(name, 3644 slot_size, 3645 uhash_entries, 3646 21, /* one slot per 2 MB */ 3647 0, 3648 &table->log, 3649 &table->mask, 3650 UDP_HTABLE_SIZE_MIN, 3651 UDP_HTABLE_SIZE_MAX); 3652 3653 table->hash2 = (void *)(table->hash + (table->mask + 1)); 3654 for (i = 0; i <= table->mask; i++) { 3655 INIT_HLIST_HEAD(&table->hash[i].head); 3656 table->hash[i].count = 0; 3657 spin_lock_init(&table->hash[i].lock); 3658 } 3659 for (i = 0; i <= table->mask; i++) { 3660 INIT_HLIST_HEAD(&table->hash2[i].hslot.head); 3661 table->hash2[i].hslot.count = 0; 3662 spin_lock_init(&table->hash2[i].hslot.lock); 3663 } 3664 udp_table_hash4_init(table); 3665 } 3666 3667 u32 udp_flow_hashrnd(void) 3668 { 3669 static u32 hashrnd __read_mostly; 3670 3671 net_get_random_once(&hashrnd, sizeof(hashrnd)); 3672 3673 return hashrnd; 3674 } 3675 EXPORT_SYMBOL(udp_flow_hashrnd); 3676 3677 static void __net_init udp_sysctl_init(struct net *net) 3678 { 3679 net->ipv4.sysctl_udp_rmem_min = PAGE_SIZE; 3680 net->ipv4.sysctl_udp_wmem_min = PAGE_SIZE; 3681 3682 #ifdef CONFIG_NET_L3_MASTER_DEV 3683 net->ipv4.sysctl_udp_l3mdev_accept = 0; 3684 #endif 3685 } 3686 3687 static struct udp_table __net_init *udp_pernet_table_alloc(unsigned int hash_entries) 3688 { 3689 struct udp_table *udptable; 3690 unsigned int slot_size; 3691 int i; 3692 3693 udptable = kmalloc_obj(*udptable); 3694 if (!udptable) 3695 goto out; 3696 3697 slot_size = sizeof(struct udp_hslot) + sizeof(struct udp_hslot_main) + 3698 udp_hash4_slot_size(); 3699 udptable->hash = vmalloc_huge(hash_entries * slot_size, 3700 GFP_KERNEL_ACCOUNT); 3701 if (!udptable->hash) 3702 goto free_table; 3703 3704 udptable->hash2 = (void *)(udptable->hash + hash_entries); 3705 udptable->mask = hash_entries - 1; 3706 udptable->log = ilog2(hash_entries); 3707 3708 for (i = 0; i < hash_entries; i++) { 3709 INIT_HLIST_HEAD(&udptable->hash[i].head); 3710 udptable->hash[i].count = 0; 3711 spin_lock_init(&udptable->hash[i].lock); 3712 3713 INIT_HLIST_HEAD(&udptable->hash2[i].hslot.head); 3714 udptable->hash2[i].hslot.count = 0; 3715 spin_lock_init(&udptable->hash2[i].hslot.lock); 3716 } 3717 udp_table_hash4_init(udptable); 3718 3719 return udptable; 3720 3721 free_table: 3722 kfree(udptable); 3723 out: 3724 return NULL; 3725 } 3726 3727 static void __net_exit udp_pernet_table_free(struct net *net) 3728 { 3729 struct udp_table *udptable = net->ipv4.udp_table; 3730 3731 if (udptable == &udp_table) 3732 return; 3733 3734 kvfree(udptable->hash); 3735 kfree(udptable); 3736 } 3737 3738 static void __net_init udp_set_table(struct net *net) 3739 { 3740 struct udp_table *udptable; 3741 unsigned int hash_entries; 3742 struct net *old_net; 3743 3744 if (net_eq(net, &init_net)) 3745 goto fallback; 3746 3747 old_net = current->nsproxy->net_ns; 3748 hash_entries = READ_ONCE(old_net->ipv4.sysctl_udp_child_hash_entries); 3749 if (!hash_entries) 3750 goto fallback; 3751 3752 /* Set min to keep the bitmap on stack in udp_lib_get_port() */ 3753 if (hash_entries < UDP_HTABLE_SIZE_MIN_PERNET) 3754 hash_entries = UDP_HTABLE_SIZE_MIN_PERNET; 3755 else 3756 hash_entries = roundup_pow_of_two(hash_entries); 3757 3758 udptable = udp_pernet_table_alloc(hash_entries); 3759 if (udptable) { 3760 net->ipv4.udp_table = udptable; 3761 } else { 3762 pr_warn("Failed to allocate UDP hash table (entries: %u) " 3763 "for a netns, fallback to the global one\n", 3764 hash_entries); 3765 fallback: 3766 net->ipv4.udp_table = &udp_table; 3767 } 3768 } 3769 3770 static int __net_init udp_pernet_init(struct net *net) 3771 { 3772 #if IS_ENABLED(CONFIG_NET_UDP_TUNNEL) 3773 int i; 3774 3775 /* No tunnel is configured */ 3776 for (i = 0; i < ARRAY_SIZE(net->ipv4.udp_tunnel_gro); ++i) { 3777 INIT_HLIST_HEAD(&net->ipv4.udp_tunnel_gro[i].list); 3778 RCU_INIT_POINTER(net->ipv4.udp_tunnel_gro[i].sk, NULL); 3779 } 3780 #endif 3781 udp_sysctl_init(net); 3782 udp_set_table(net); 3783 3784 return 0; 3785 } 3786 3787 static void __net_exit udp_pernet_exit(struct net *net) 3788 { 3789 udp_pernet_table_free(net); 3790 } 3791 3792 static struct pernet_operations __net_initdata udp_sysctl_ops = { 3793 .init = udp_pernet_init, 3794 .exit = udp_pernet_exit, 3795 }; 3796 3797 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS) 3798 DEFINE_BPF_ITER_FUNC(udp, struct bpf_iter_meta *meta, 3799 struct udp_sock *udp_sk, uid_t uid, int bucket) 3800 3801 static int bpf_iter_udp_realloc_batch(struct bpf_udp_iter_state *iter, 3802 unsigned int new_batch_sz, gfp_t flags) 3803 { 3804 union bpf_udp_iter_batch_item *new_batch; 3805 3806 new_batch = kvmalloc_objs(*new_batch, new_batch_sz, 3807 flags | __GFP_NOWARN); 3808 if (!new_batch) 3809 return -ENOMEM; 3810 3811 if (flags != GFP_NOWAIT) 3812 bpf_iter_udp_put_batch(iter); 3813 3814 memcpy(new_batch, iter->batch, sizeof(*iter->batch) * iter->end_sk); 3815 kvfree(iter->batch); 3816 iter->batch = new_batch; 3817 iter->max_sk = new_batch_sz; 3818 3819 return 0; 3820 } 3821 3822 #define INIT_BATCH_SZ 16 3823 3824 static int bpf_iter_init_udp(void *priv_data, struct bpf_iter_aux_info *aux) 3825 { 3826 struct bpf_udp_iter_state *iter = priv_data; 3827 int ret; 3828 3829 ret = bpf_iter_init_seq_net(priv_data, aux); 3830 if (ret) 3831 return ret; 3832 3833 ret = bpf_iter_udp_realloc_batch(iter, INIT_BATCH_SZ, GFP_USER); 3834 if (ret) 3835 bpf_iter_fini_seq_net(priv_data); 3836 3837 iter->state.bucket = -1; 3838 3839 return ret; 3840 } 3841 3842 static void bpf_iter_fini_udp(void *priv_data) 3843 { 3844 struct bpf_udp_iter_state *iter = priv_data; 3845 3846 bpf_iter_fini_seq_net(priv_data); 3847 kvfree(iter->batch); 3848 } 3849 3850 static const struct bpf_iter_seq_info udp_seq_info = { 3851 .seq_ops = &bpf_iter_udp_seq_ops, 3852 .init_seq_private = bpf_iter_init_udp, 3853 .fini_seq_private = bpf_iter_fini_udp, 3854 .seq_priv_size = sizeof(struct bpf_udp_iter_state), 3855 }; 3856 3857 static struct bpf_iter_reg udp_reg_info = { 3858 .target = "udp", 3859 .ctx_arg_info_size = 1, 3860 .ctx_arg_info = { 3861 { offsetof(struct bpf_iter__udp, udp_sk), 3862 PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED }, 3863 }, 3864 .seq_info = &udp_seq_info, 3865 }; 3866 3867 static void __init bpf_iter_register(void) 3868 { 3869 udp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UDP]; 3870 if (bpf_iter_reg_target(&udp_reg_info)) 3871 pr_warn("Warning: could not register bpf iterator udp\n"); 3872 } 3873 #endif 3874 3875 void __init udp_init(void) 3876 { 3877 unsigned long limit; 3878 3879 udp_table_init(&udp_table, "UDP"); 3880 limit = nr_free_buffer_pages() / 8; 3881 limit = max(limit, 128UL); 3882 sysctl_udp_mem[0] = limit / 4 * 3; 3883 sysctl_udp_mem[1] = limit; 3884 sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2; 3885 3886 if (register_pernet_subsys(&udp_sysctl_ops)) 3887 panic("UDP: failed to init sysctl parameters.\n"); 3888 3889 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS) 3890 bpf_iter_register(); 3891 #endif 3892 } 3893