PageRenderTime 76ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/net/ipv4/udp.c

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