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