udp.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353
  1. /*
  2. * INET An implementation of the TCP/IP protocol suite for the LINUX
  3. * operating system. INET is implemented using the BSD Socket
  4. * interface as the means of communication with the user level.
  5. *
  6. * The User Datagram Protocol (UDP).
  7. *
  8. * Authors: Ross Biro
  9. * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  10. * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
  11. * Alan Cox, <alan@lxorguk.ukuu.org.uk>
  12. * Hirokazu Takahashi, <taka@valinux.co.jp>
  13. *
  14. * Fixes:
  15. * Alan Cox : verify_area() calls
  16. * Alan Cox : stopped close while in use off icmp
  17. * messages. Not a fix but a botch that
  18. * for udp at least is 'valid'.
  19. * Alan Cox : Fixed icmp handling properly
  20. * Alan Cox : Correct error for oversized datagrams
  21. * Alan Cox : Tidied select() semantics.
  22. * Alan Cox : udp_err() fixed properly, also now
  23. * select and read wake correctly on errors
  24. * Alan Cox : udp_send verify_area moved to avoid mem leak
  25. * Alan Cox : UDP can count its memory
  26. * Alan Cox : send to an unknown connection causes
  27. * an ECONNREFUSED off the icmp, but
  28. * does NOT close.
  29. * Alan Cox : Switched to new sk_buff handlers. No more backlog!
  30. * Alan Cox : Using generic datagram code. Even smaller and the PEEK
  31. * bug no longer crashes it.
  32. * Fred Van Kempen : Net2e support for sk->broadcast.
  33. * Alan Cox : Uses skb_free_datagram
  34. * Alan Cox : Added get/set sockopt support.
  35. * Alan Cox : Broadcasting without option set returns EACCES.
  36. * Alan Cox : No wakeup calls. Instead we now use the callbacks.
  37. * Alan Cox : Use ip_tos and ip_ttl
  38. * Alan Cox : SNMP Mibs
  39. * Alan Cox : MSG_DONTROUTE, and 0.0.0.0 support.
  40. * Matt Dillon : UDP length checks.
  41. * Alan Cox : Smarter af_inet used properly.
  42. * Alan Cox : Use new kernel side addressing.
  43. * Alan Cox : Incorrect return on truncated datagram receive.
  44. * Arnt Gulbrandsen : New udp_send and stuff
  45. * Alan Cox : Cache last socket
  46. * Alan Cox : Route cache
  47. * Jon Peatfield : Minor efficiency fix to sendto().
  48. * Mike Shaver : RFC1122 checks.
  49. * Alan Cox : Nonblocking error fix.
  50. * Willy Konynenberg : Transparent proxying support.
  51. * Mike McLagan : Routing by source
  52. * David S. Miller : New socket lookup architecture.
  53. * Last socket cache retained as it
  54. * does have a high hit rate.
  55. * Olaf Kirch : Don't linearise iovec on sendmsg.
  56. * Andi Kleen : Some cleanups, cache destination entry
  57. * for connect.
  58. * Vitaly E. Lavrov : Transparent proxy revived after year coma.
  59. * Melvin Smith : Check msg_name not msg_namelen in sendto(),
  60. * return ENOTCONN for unconnected sockets (POSIX)
  61. * Janos Farkas : don't deliver multi/broadcasts to a different
  62. * bound-to-device socket
  63. * Hirokazu Takahashi : HW checksumming for outgoing UDP
  64. * datagrams.
  65. * Hirokazu Takahashi : sendfile() on UDP works now.
  66. * Arnaldo C. Melo : convert /proc/net/udp to seq_file
  67. * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which
  68. * Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind
  69. * a single port at the same time.
  70. * Derek Atkins <derek@ihtfp.com>: Add Encapulation Support
  71. * James Chapman : Add L2TP encapsulation type.
  72. *
  73. *
  74. * This program is free software; you can redistribute it and/or
  75. * modify it under the terms of the GNU General Public License
  76. * as published by the Free Software Foundation; either version
  77. * 2 of the License, or (at your option) any later version.
  78. */
  79. #define pr_fmt(fmt) "UDP: " fmt
  80. #include <asm/uaccess.h>
  81. #include <asm/ioctls.h>
  82. #include <linux/bootmem.h>
  83. #include <linux/highmem.h>
  84. #include <linux/swap.h>
  85. #include <linux/types.h>
  86. #include <linux/fcntl.h>
  87. #include <linux/module.h>
  88. #include <linux/socket.h>
  89. #include <linux/sockios.h>
  90. #include <linux/igmp.h>
  91. #include <linux/in.h>
  92. #include <linux/errno.h>
  93. #include <linux/timer.h>
  94. #include <linux/mm.h>
  95. #include <linux/inet.h>
  96. #include <linux/netdevice.h>
  97. #include <linux/slab.h>
  98. #include <net/tcp_states.h>
  99. #include <linux/skbuff.h>
  100. #include <linux/proc_fs.h>
  101. #include <linux/seq_file.h>
  102. #include <net/net_namespace.h>
  103. #include <net/icmp.h>
  104. #include <net/route.h>
  105. #include <net/checksum.h>
  106. #include <net/xfrm.h>
  107. #include <trace/events/udp.h>
  108. #include <linux/static_key.h>
  109. #include <trace/events/skb.h>
  110. #include <net/busy_poll.h>
  111. #include "udp_impl.h"
  112. struct udp_table udp_table __read_mostly;
  113. EXPORT_SYMBOL(udp_table);
  114. long sysctl_udp_mem[3] __read_mostly;
  115. EXPORT_SYMBOL(sysctl_udp_mem);
  116. int sysctl_udp_rmem_min __read_mostly;
  117. EXPORT_SYMBOL(sysctl_udp_rmem_min);
  118. int sysctl_udp_wmem_min __read_mostly;
  119. EXPORT_SYMBOL(sysctl_udp_wmem_min);
  120. atomic_long_t udp_memory_allocated;
  121. EXPORT_SYMBOL(udp_memory_allocated);
  122. #define MAX_UDP_PORTS 65536
  123. #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN)
  124. static int udp_lib_lport_inuse(struct net *net, __u16 num,
  125. const struct udp_hslot *hslot,
  126. unsigned long *bitmap,
  127. struct sock *sk,
  128. int (*saddr_comp)(const struct sock *sk1,
  129. const struct sock *sk2),
  130. unsigned int log)
  131. {
  132. struct sock *sk2;
  133. struct hlist_nulls_node *node;
  134. kuid_t uid = sock_i_uid(sk);
  135. sk_nulls_for_each(sk2, node, &hslot->head)
  136. if (net_eq(sock_net(sk2), net) &&
  137. sk2 != sk &&
  138. (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
  139. (!sk2->sk_reuse || !sk->sk_reuse) &&
  140. (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
  141. sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
  142. (!sk2->sk_reuseport || !sk->sk_reuseport ||
  143. !uid_eq(uid, sock_i_uid(sk2))) &&
  144. (*saddr_comp)(sk, sk2)) {
  145. if (bitmap)
  146. __set_bit(udp_sk(sk2)->udp_port_hash >> log,
  147. bitmap);
  148. else
  149. return 1;
  150. }
  151. return 0;
  152. }
  153. /*
  154. * Note: we still hold spinlock of primary hash chain, so no other writer
  155. * can insert/delete a socket with local_port == num
  156. */
  157. static int udp_lib_lport_inuse2(struct net *net, __u16 num,
  158. struct udp_hslot *hslot2,
  159. struct sock *sk,
  160. int (*saddr_comp)(const struct sock *sk1,
  161. const struct sock *sk2))
  162. {
  163. struct sock *sk2;
  164. struct hlist_nulls_node *node;
  165. kuid_t uid = sock_i_uid(sk);
  166. int res = 0;
  167. spin_lock(&hslot2->lock);
  168. udp_portaddr_for_each_entry(sk2, node, &hslot2->head)
  169. if (net_eq(sock_net(sk2), net) &&
  170. sk2 != sk &&
  171. (udp_sk(sk2)->udp_port_hash == num) &&
  172. (!sk2->sk_reuse || !sk->sk_reuse) &&
  173. (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
  174. sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
  175. (!sk2->sk_reuseport || !sk->sk_reuseport ||
  176. !uid_eq(uid, sock_i_uid(sk2))) &&
  177. (*saddr_comp)(sk, sk2)) {
  178. res = 1;
  179. break;
  180. }
  181. spin_unlock(&hslot2->lock);
  182. return res;
  183. }
  184. /**
  185. * udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6
  186. *
  187. * @sk: socket struct in question
  188. * @snum: port number to look up
  189. * @saddr_comp: AF-dependent comparison of bound local IP addresses
  190. * @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
  191. * with NULL address
  192. */
  193. int udp_lib_get_port(struct sock *sk, unsigned short snum,
  194. int (*saddr_comp)(const struct sock *sk1,
  195. const struct sock *sk2),
  196. unsigned int hash2_nulladdr)
  197. {
  198. struct udp_hslot *hslot, *hslot2;
  199. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  200. int error = 1;
  201. struct net *net = sock_net(sk);
  202. if (!snum) {
  203. int low, high, remaining;
  204. unsigned int rand;
  205. unsigned short first, last;
  206. DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
  207. inet_get_local_port_range(&low, &high);
  208. remaining = (high - low) + 1;
  209. rand = net_random();
  210. first = (((u64)rand * remaining) >> 32) + low;
  211. /*
  212. * force rand to be an odd multiple of UDP_HTABLE_SIZE
  213. */
  214. rand = (rand | 1) * (udptable->mask + 1);
  215. last = first + udptable->mask + 1;
  216. do {
  217. hslot = udp_hashslot(udptable, net, first);
  218. bitmap_zero(bitmap, PORTS_PER_CHAIN);
  219. spin_lock_bh(&hslot->lock);
  220. udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
  221. saddr_comp, udptable->log);
  222. snum = first;
  223. /*
  224. * Iterate on all possible values of snum for this hash.
  225. * Using steps of an odd multiple of UDP_HTABLE_SIZE
  226. * give us randomization and full range coverage.
  227. */
  228. do {
  229. if (low <= snum && snum <= high &&
  230. !test_bit(snum >> udptable->log, bitmap) &&
  231. !inet_is_reserved_local_port(snum))
  232. goto found;
  233. snum += rand;
  234. } while (snum != first);
  235. spin_unlock_bh(&hslot->lock);
  236. } while (++first != last);
  237. goto fail;
  238. } else {
  239. hslot = udp_hashslot(udptable, net, snum);
  240. spin_lock_bh(&hslot->lock);
  241. if (hslot->count > 10) {
  242. int exist;
  243. unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
  244. slot2 &= udptable->mask;
  245. hash2_nulladdr &= udptable->mask;
  246. hslot2 = udp_hashslot2(udptable, slot2);
  247. if (hslot->count < hslot2->count)
  248. goto scan_primary_hash;
  249. exist = udp_lib_lport_inuse2(net, snum, hslot2,
  250. sk, saddr_comp);
  251. if (!exist && (hash2_nulladdr != slot2)) {
  252. hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
  253. exist = udp_lib_lport_inuse2(net, snum, hslot2,
  254. sk, saddr_comp);
  255. }
  256. if (exist)
  257. goto fail_unlock;
  258. else
  259. goto found;
  260. }
  261. scan_primary_hash:
  262. if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk,
  263. saddr_comp, 0))
  264. goto fail_unlock;
  265. }
  266. found:
  267. inet_sk(sk)->inet_num = snum;
  268. udp_sk(sk)->udp_port_hash = snum;
  269. udp_sk(sk)->udp_portaddr_hash ^= snum;
  270. if (sk_unhashed(sk)) {
  271. sk_nulls_add_node_rcu(sk, &hslot->head);
  272. hslot->count++;
  273. sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
  274. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  275. spin_lock(&hslot2->lock);
  276. hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
  277. &hslot2->head);
  278. hslot2->count++;
  279. spin_unlock(&hslot2->lock);
  280. }
  281. error = 0;
  282. fail_unlock:
  283. spin_unlock_bh(&hslot->lock);
  284. fail:
  285. return error;
  286. }
  287. EXPORT_SYMBOL(udp_lib_get_port);
  288. static int ipv4_rcv_saddr_equal(const struct sock *sk1, const struct sock *sk2)
  289. {
  290. struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2);
  291. return (!ipv6_only_sock(sk2) &&
  292. (!inet1->inet_rcv_saddr || !inet2->inet_rcv_saddr ||
  293. inet1->inet_rcv_saddr == inet2->inet_rcv_saddr));
  294. }
  295. static unsigned int udp4_portaddr_hash(struct net *net, __be32 saddr,
  296. unsigned int port)
  297. {
  298. return jhash_1word((__force u32)saddr, net_hash_mix(net)) ^ port;
  299. }
  300. int udp_v4_get_port(struct sock *sk, unsigned short snum)
  301. {
  302. unsigned int hash2_nulladdr =
  303. udp4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
  304. unsigned int hash2_partial =
  305. udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
  306. /* precompute partial secondary hash */
  307. udp_sk(sk)->udp_portaddr_hash = hash2_partial;
  308. return udp_lib_get_port(sk, snum, ipv4_rcv_saddr_equal, hash2_nulladdr);
  309. }
  310. static inline int compute_score(struct sock *sk, struct net *net, __be32 saddr,
  311. unsigned short hnum,
  312. __be16 sport, __be32 daddr, __be16 dport, int dif)
  313. {
  314. int score = -1;
  315. if (net_eq(sock_net(sk), net) && udp_sk(sk)->udp_port_hash == hnum &&
  316. !ipv6_only_sock(sk)) {
  317. struct inet_sock *inet = inet_sk(sk);
  318. score = (sk->sk_family == PF_INET ? 2 : 1);
  319. if (inet->inet_rcv_saddr) {
  320. if (inet->inet_rcv_saddr != daddr)
  321. return -1;
  322. score += 4;
  323. }
  324. if (inet->inet_daddr) {
  325. if (inet->inet_daddr != saddr)
  326. return -1;
  327. score += 4;
  328. }
  329. if (inet->inet_dport) {
  330. if (inet->inet_dport != sport)
  331. return -1;
  332. score += 4;
  333. }
  334. if (sk->sk_bound_dev_if) {
  335. if (sk->sk_bound_dev_if != dif)
  336. return -1;
  337. score += 4;
  338. }
  339. }
  340. return score;
  341. }
  342. /*
  343. * In this second variant, we check (daddr, dport) matches (inet_rcv_sadd, inet_num)
  344. */
  345. static inline int compute_score2(struct sock *sk, struct net *net,
  346. __be32 saddr, __be16 sport,
  347. __be32 daddr, unsigned int hnum, int dif)
  348. {
  349. int score = -1;
  350. if (net_eq(sock_net(sk), net) && !ipv6_only_sock(sk)) {
  351. struct inet_sock *inet = inet_sk(sk);
  352. if (inet->inet_rcv_saddr != daddr)
  353. return -1;
  354. if (inet->inet_num != hnum)
  355. return -1;
  356. score = (sk->sk_family == PF_INET ? 2 : 1);
  357. if (inet->inet_daddr) {
  358. if (inet->inet_daddr != saddr)
  359. return -1;
  360. score += 4;
  361. }
  362. if (inet->inet_dport) {
  363. if (inet->inet_dport != sport)
  364. return -1;
  365. score += 4;
  366. }
  367. if (sk->sk_bound_dev_if) {
  368. if (sk->sk_bound_dev_if != dif)
  369. return -1;
  370. score += 4;
  371. }
  372. }
  373. return score;
  374. }
  375. /* called with read_rcu_lock() */
  376. static struct sock *udp4_lib_lookup2(struct net *net,
  377. __be32 saddr, __be16 sport,
  378. __be32 daddr, unsigned int hnum, int dif,
  379. struct udp_hslot *hslot2, unsigned int slot2)
  380. {
  381. struct sock *sk, *result;
  382. struct hlist_nulls_node *node;
  383. int score, badness, matches = 0, reuseport = 0;
  384. u32 hash = 0;
  385. begin:
  386. result = NULL;
  387. badness = 0;
  388. udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) {
  389. score = compute_score2(sk, net, saddr, sport,
  390. daddr, hnum, dif);
  391. if (score > badness) {
  392. result = sk;
  393. badness = score;
  394. reuseport = sk->sk_reuseport;
  395. if (reuseport) {
  396. hash = inet_ehashfn(net, daddr, hnum,
  397. saddr, sport);
  398. matches = 1;
  399. }
  400. } else if (score == badness && reuseport) {
  401. matches++;
  402. if (((u64)hash * matches) >> 32 == 0)
  403. result = sk;
  404. hash = next_pseudo_random32(hash);
  405. }
  406. }
  407. /*
  408. * if the nulls value we got at the end of this lookup is
  409. * not the expected one, we must restart lookup.
  410. * We probably met an item that was moved to another chain.
  411. */
  412. if (get_nulls_value(node) != slot2)
  413. goto begin;
  414. if (result) {
  415. if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2)))
  416. result = NULL;
  417. else if (unlikely(compute_score2(result, net, saddr, sport,
  418. daddr, hnum, dif) < badness)) {
  419. sock_put(result);
  420. goto begin;
  421. }
  422. }
  423. return result;
  424. }
  425. /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
  426. * harder than this. -DaveM
  427. */
  428. struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
  429. __be16 sport, __be32 daddr, __be16 dport,
  430. int dif, struct udp_table *udptable)
  431. {
  432. struct sock *sk, *result;
  433. struct hlist_nulls_node *node;
  434. unsigned short hnum = ntohs(dport);
  435. unsigned int hash2, slot2, slot = udp_hashfn(net, hnum, udptable->mask);
  436. struct udp_hslot *hslot2, *hslot = &udptable->hash[slot];
  437. int score, badness, matches = 0, reuseport = 0;
  438. u32 hash = 0;
  439. rcu_read_lock();
  440. if (hslot->count > 10) {
  441. hash2 = udp4_portaddr_hash(net, daddr, hnum);
  442. slot2 = hash2 & udptable->mask;
  443. hslot2 = &udptable->hash2[slot2];
  444. if (hslot->count < hslot2->count)
  445. goto begin;
  446. result = udp4_lib_lookup2(net, saddr, sport,
  447. daddr, hnum, dif,
  448. hslot2, slot2);
  449. if (!result) {
  450. hash2 = udp4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
  451. slot2 = hash2 & udptable->mask;
  452. hslot2 = &udptable->hash2[slot2];
  453. if (hslot->count < hslot2->count)
  454. goto begin;
  455. result = udp4_lib_lookup2(net, saddr, sport,
  456. htonl(INADDR_ANY), hnum, dif,
  457. hslot2, slot2);
  458. }
  459. rcu_read_unlock();
  460. return result;
  461. }
  462. begin:
  463. result = NULL;
  464. badness = 0;
  465. sk_nulls_for_each_rcu(sk, node, &hslot->head) {
  466. score = compute_score(sk, net, saddr, hnum, sport,
  467. daddr, dport, dif);
  468. if (score > badness) {
  469. result = sk;
  470. badness = score;
  471. reuseport = sk->sk_reuseport;
  472. if (reuseport) {
  473. hash = inet_ehashfn(net, daddr, hnum,
  474. saddr, sport);
  475. matches = 1;
  476. }
  477. } else if (score == badness && reuseport) {
  478. matches++;
  479. if (((u64)hash * matches) >> 32 == 0)
  480. result = sk;
  481. hash = next_pseudo_random32(hash);
  482. }
  483. }
  484. /*
  485. * if the nulls value we got at the end of this lookup is
  486. * not the expected one, we must restart lookup.
  487. * We probably met an item that was moved to another chain.
  488. */
  489. if (get_nulls_value(node) != slot)
  490. goto begin;
  491. if (result) {
  492. if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2)))
  493. result = NULL;
  494. else if (unlikely(compute_score(result, net, saddr, hnum, sport,
  495. daddr, dport, dif) < badness)) {
  496. sock_put(result);
  497. goto begin;
  498. }
  499. }
  500. rcu_read_unlock();
  501. return result;
  502. }
  503. EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
  504. static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
  505. __be16 sport, __be16 dport,
  506. struct udp_table *udptable)
  507. {
  508. struct sock *sk;
  509. const struct iphdr *iph = ip_hdr(skb);
  510. if (unlikely(sk = skb_steal_sock(skb)))
  511. return sk;
  512. else
  513. return __udp4_lib_lookup(dev_net(skb_dst(skb)->dev), iph->saddr, sport,
  514. iph->daddr, dport, inet_iif(skb),
  515. udptable);
  516. }
  517. struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
  518. __be32 daddr, __be16 dport, int dif)
  519. {
  520. return __udp4_lib_lookup(net, saddr, sport, daddr, dport, dif, &udp_table);
  521. }
  522. EXPORT_SYMBOL_GPL(udp4_lib_lookup);
  523. static inline struct sock *udp_v4_mcast_next(struct net *net, struct sock *sk,
  524. __be16 loc_port, __be32 loc_addr,
  525. __be16 rmt_port, __be32 rmt_addr,
  526. int dif)
  527. {
  528. struct hlist_nulls_node *node;
  529. struct sock *s = sk;
  530. unsigned short hnum = ntohs(loc_port);
  531. sk_nulls_for_each_from(s, node) {
  532. struct inet_sock *inet = inet_sk(s);
  533. if (!net_eq(sock_net(s), net) ||
  534. udp_sk(s)->udp_port_hash != hnum ||
  535. (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
  536. (inet->inet_dport != rmt_port && inet->inet_dport) ||
  537. (inet->inet_rcv_saddr &&
  538. inet->inet_rcv_saddr != loc_addr) ||
  539. ipv6_only_sock(s) ||
  540. (s->sk_bound_dev_if && s->sk_bound_dev_if != dif))
  541. continue;
  542. if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif))
  543. continue;
  544. goto found;
  545. }
  546. s = NULL;
  547. found:
  548. return s;
  549. }
  550. /*
  551. * This routine is called by the ICMP module when it gets some
  552. * sort of error condition. If err < 0 then the socket should
  553. * be closed and the error returned to the user. If err > 0
  554. * it's just the icmp type << 8 | icmp code.
  555. * Header points to the ip header of the error packet. We move
  556. * on past this. Then (as it used to claim before adjustment)
  557. * header points to the first 8 bytes of the udp header. We need
  558. * to find the appropriate port.
  559. */
  560. void __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
  561. {
  562. struct inet_sock *inet;
  563. const struct iphdr *iph = (const struct iphdr *)skb->data;
  564. struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
  565. const int type = icmp_hdr(skb)->type;
  566. const int code = icmp_hdr(skb)->code;
  567. struct sock *sk;
  568. int harderr;
  569. int err;
  570. struct net *net = dev_net(skb->dev);
  571. sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
  572. iph->saddr, uh->source, skb->dev->ifindex, udptable);
  573. if (sk == NULL) {
  574. ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS);
  575. return; /* No socket for error */
  576. }
  577. err = 0;
  578. harderr = 0;
  579. inet = inet_sk(sk);
  580. switch (type) {
  581. default:
  582. case ICMP_TIME_EXCEEDED:
  583. err = EHOSTUNREACH;
  584. break;
  585. case ICMP_SOURCE_QUENCH:
  586. goto out;
  587. case ICMP_PARAMETERPROB:
  588. err = EPROTO;
  589. harderr = 1;
  590. break;
  591. case ICMP_DEST_UNREACH:
  592. if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
  593. ipv4_sk_update_pmtu(skb, sk, info);
  594. if (inet->pmtudisc != IP_PMTUDISC_DONT) {
  595. err = EMSGSIZE;
  596. harderr = 1;
  597. break;
  598. }
  599. goto out;
  600. }
  601. err = EHOSTUNREACH;
  602. if (code <= NR_ICMP_UNREACH) {
  603. harderr = icmp_err_convert[code].fatal;
  604. err = icmp_err_convert[code].errno;
  605. }
  606. break;
  607. case ICMP_REDIRECT:
  608. ipv4_sk_redirect(skb, sk);
  609. break;
  610. }
  611. /*
  612. * RFC1122: OK. Passes ICMP errors back to application, as per
  613. * 4.1.3.3.
  614. */
  615. if (!inet->recverr) {
  616. if (!harderr || sk->sk_state != TCP_ESTABLISHED)
  617. goto out;
  618. } else
  619. ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
  620. sk->sk_err = err;
  621. sk->sk_error_report(sk);
  622. out:
  623. sock_put(sk);
  624. }
  625. void udp_err(struct sk_buff *skb, u32 info)
  626. {
  627. __udp4_lib_err(skb, info, &udp_table);
  628. }
  629. /*
  630. * Throw away all pending data and cancel the corking. Socket is locked.
  631. */
  632. void udp_flush_pending_frames(struct sock *sk)
  633. {
  634. struct udp_sock *up = udp_sk(sk);
  635. if (up->pending) {
  636. up->len = 0;
  637. up->pending = 0;
  638. ip_flush_pending_frames(sk);
  639. }
  640. }
  641. EXPORT_SYMBOL(udp_flush_pending_frames);
  642. /**
  643. * udp4_hwcsum - handle outgoing HW checksumming
  644. * @skb: sk_buff containing the filled-in UDP header
  645. * (checksum field must be zeroed out)
  646. * @src: source IP address
  647. * @dst: destination IP address
  648. */
  649. static void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
  650. {
  651. struct udphdr *uh = udp_hdr(skb);
  652. struct sk_buff *frags = skb_shinfo(skb)->frag_list;
  653. int offset = skb_transport_offset(skb);
  654. int len = skb->len - offset;
  655. int hlen = len;
  656. __wsum csum = 0;
  657. if (!frags) {
  658. /*
  659. * Only one fragment on the socket.
  660. */
  661. skb->csum_start = skb_transport_header(skb) - skb->head;
  662. skb->csum_offset = offsetof(struct udphdr, check);
  663. uh->check = ~csum_tcpudp_magic(src, dst, len,
  664. IPPROTO_UDP, 0);
  665. } else {
  666. /*
  667. * HW-checksum won't work as there are two or more
  668. * fragments on the socket so that all csums of sk_buffs
  669. * should be together
  670. */
  671. do {
  672. csum = csum_add(csum, frags->csum);
  673. hlen -= frags->len;
  674. } while ((frags = frags->next));
  675. csum = skb_checksum(skb, offset, hlen, csum);
  676. skb->ip_summed = CHECKSUM_NONE;
  677. uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
  678. if (uh->check == 0)
  679. uh->check = CSUM_MANGLED_0;
  680. }
  681. }
  682. static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4)
  683. {
  684. struct sock *sk = skb->sk;
  685. struct inet_sock *inet = inet_sk(sk);
  686. struct udphdr *uh;
  687. int err = 0;
  688. int is_udplite = IS_UDPLITE(sk);
  689. int offset = skb_transport_offset(skb);
  690. int len = skb->len - offset;
  691. __wsum csum = 0;
  692. /*
  693. * Create a UDP header
  694. */
  695. uh = udp_hdr(skb);
  696. uh->source = inet->inet_sport;
  697. uh->dest = fl4->fl4_dport;
  698. uh->len = htons(len);
  699. uh->check = 0;
  700. if (is_udplite) /* UDP-Lite */
  701. csum = udplite_csum(skb);
  702. else if (sk->sk_no_check == UDP_CSUM_NOXMIT) { /* UDP csum disabled */
  703. skb->ip_summed = CHECKSUM_NONE;
  704. goto send;
  705. } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
  706. udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
  707. goto send;
  708. } else
  709. csum = udp_csum(skb);
  710. /* add protocol-dependent pseudo-header */
  711. uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
  712. sk->sk_protocol, csum);
  713. if (uh->check == 0)
  714. uh->check = CSUM_MANGLED_0;
  715. send:
  716. err = ip_send_skb(sock_net(sk), skb);
  717. if (err) {
  718. if (err == -ENOBUFS && !inet->recverr) {
  719. UDP_INC_STATS_USER(sock_net(sk),
  720. UDP_MIB_SNDBUFERRORS, is_udplite);
  721. err = 0;
  722. }
  723. } else
  724. UDP_INC_STATS_USER(sock_net(sk),
  725. UDP_MIB_OUTDATAGRAMS, is_udplite);
  726. return err;
  727. }
  728. /*
  729. * Push out all pending data as one UDP datagram. Socket is locked.
  730. */
  731. int udp_push_pending_frames(struct sock *sk)
  732. {
  733. struct udp_sock *up = udp_sk(sk);
  734. struct inet_sock *inet = inet_sk(sk);
  735. struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
  736. struct sk_buff *skb;
  737. int err = 0;
  738. skb = ip_finish_skb(sk, fl4);
  739. if (!skb)
  740. goto out;
  741. err = udp_send_skb(skb, fl4);
  742. out:
  743. up->len = 0;
  744. up->pending = 0;
  745. return err;
  746. }
  747. EXPORT_SYMBOL(udp_push_pending_frames);
  748. int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
  749. size_t len)
  750. {
  751. struct inet_sock *inet = inet_sk(sk);
  752. struct udp_sock *up = udp_sk(sk);
  753. struct flowi4 fl4_stack;
  754. struct flowi4 *fl4;
  755. int ulen = len;
  756. struct ipcm_cookie ipc;
  757. struct rtable *rt = NULL;
  758. int free = 0;
  759. int connected = 0;
  760. __be32 daddr, faddr, saddr;
  761. __be16 dport;
  762. u8 tos;
  763. int err, is_udplite = IS_UDPLITE(sk);
  764. int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
  765. int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
  766. struct sk_buff *skb;
  767. struct ip_options_data opt_copy;
  768. if (len > 0xFFFF)
  769. return -EMSGSIZE;
  770. /*
  771. * Check the flags.
  772. */
  773. if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
  774. return -EOPNOTSUPP;
  775. ipc.opt = NULL;
  776. ipc.tx_flags = 0;
  777. getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
  778. fl4 = &inet->cork.fl.u.ip4;
  779. if (up->pending) {
  780. /*
  781. * There are pending frames.
  782. * The socket lock must be held while it's corked.
  783. */
  784. lock_sock(sk);
  785. if (likely(up->pending)) {
  786. if (unlikely(up->pending != AF_INET)) {
  787. release_sock(sk);
  788. return -EINVAL;
  789. }
  790. goto do_append_data;
  791. }
  792. release_sock(sk);
  793. }
  794. ulen += sizeof(struct udphdr);
  795. /*
  796. * Get and verify the address.
  797. */
  798. if (msg->msg_name) {
  799. struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name;
  800. if (msg->msg_namelen < sizeof(*usin))
  801. return -EINVAL;
  802. if (usin->sin_family != AF_INET) {
  803. if (usin->sin_family != AF_UNSPEC)
  804. return -EAFNOSUPPORT;
  805. }
  806. daddr = usin->sin_addr.s_addr;
  807. dport = usin->sin_port;
  808. if (dport == 0)
  809. return -EINVAL;
  810. } else {
  811. if (sk->sk_state != TCP_ESTABLISHED)
  812. return -EDESTADDRREQ;
  813. daddr = inet->inet_daddr;
  814. dport = inet->inet_dport;
  815. /* Open fast path for connected socket.
  816. Route will not be used, if at least one option is set.
  817. */
  818. connected = 1;
  819. }
  820. ipc.addr = inet->inet_saddr;
  821. ipc.oif = sk->sk_bound_dev_if;
  822. sock_tx_timestamp(sk, &ipc.tx_flags);
  823. if (msg->msg_controllen) {
  824. err = ip_cmsg_send(sock_net(sk), msg, &ipc);
  825. if (err)
  826. return err;
  827. if (ipc.opt)
  828. free = 1;
  829. connected = 0;
  830. }
  831. if (!ipc.opt) {
  832. struct ip_options_rcu *inet_opt;
  833. rcu_read_lock();
  834. inet_opt = rcu_dereference(inet->inet_opt);
  835. if (inet_opt) {
  836. memcpy(&opt_copy, inet_opt,
  837. sizeof(*inet_opt) + inet_opt->opt.optlen);
  838. ipc.opt = &opt_copy.opt;
  839. }
  840. rcu_read_unlock();
  841. }
  842. saddr = ipc.addr;
  843. ipc.addr = faddr = daddr;
  844. if (ipc.opt && ipc.opt->opt.srr) {
  845. if (!daddr)
  846. return -EINVAL;
  847. faddr = ipc.opt->opt.faddr;
  848. connected = 0;
  849. }
  850. tos = RT_TOS(inet->tos);
  851. if (sock_flag(sk, SOCK_LOCALROUTE) ||
  852. (msg->msg_flags & MSG_DONTROUTE) ||
  853. (ipc.opt && ipc.opt->opt.is_strictroute)) {
  854. tos |= RTO_ONLINK;
  855. connected = 0;
  856. }
  857. if (ipv4_is_multicast(daddr)) {
  858. if (!ipc.oif)
  859. ipc.oif = inet->mc_index;
  860. if (!saddr)
  861. saddr = inet->mc_addr;
  862. connected = 0;
  863. } else if (!ipc.oif)
  864. ipc.oif = inet->uc_index;
  865. if (connected)
  866. rt = (struct rtable *)sk_dst_check(sk, 0);
  867. if (rt == NULL) {
  868. struct net *net = sock_net(sk);
  869. fl4 = &fl4_stack;
  870. flowi4_init_output(fl4, ipc.oif, sk->sk_mark, tos,
  871. RT_SCOPE_UNIVERSE, sk->sk_protocol,
  872. inet_sk_flowi_flags(sk)|FLOWI_FLAG_CAN_SLEEP,
  873. faddr, saddr, dport, inet->inet_sport);
  874. security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
  875. rt = ip_route_output_flow(net, fl4, sk);
  876. if (IS_ERR(rt)) {
  877. err = PTR_ERR(rt);
  878. rt = NULL;
  879. if (err == -ENETUNREACH)
  880. IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
  881. goto out;
  882. }
  883. err = -EACCES;
  884. if ((rt->rt_flags & RTCF_BROADCAST) &&
  885. !sock_flag(sk, SOCK_BROADCAST))
  886. goto out;
  887. if (connected)
  888. sk_dst_set(sk, dst_clone(&rt->dst));
  889. }
  890. if (msg->msg_flags&MSG_CONFIRM)
  891. goto do_confirm;
  892. back_from_confirm:
  893. saddr = fl4->saddr;
  894. if (!ipc.addr)
  895. daddr = ipc.addr = fl4->daddr;
  896. /* Lockless fast path for the non-corking case. */
  897. if (!corkreq) {
  898. skb = ip_make_skb(sk, fl4, getfrag, msg->msg_iov, ulen,
  899. sizeof(struct udphdr), &ipc, &rt,
  900. msg->msg_flags);
  901. err = PTR_ERR(skb);
  902. if (!IS_ERR_OR_NULL(skb))
  903. err = udp_send_skb(skb, fl4);
  904. goto out;
  905. }
  906. lock_sock(sk);
  907. if (unlikely(up->pending)) {
  908. /* The socket is already corked while preparing it. */
  909. /* ... which is an evident application bug. --ANK */
  910. release_sock(sk);
  911. LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("cork app bug 2\n"));
  912. err = -EINVAL;
  913. goto out;
  914. }
  915. /*
  916. * Now cork the socket to pend data.
  917. */
  918. fl4 = &inet->cork.fl.u.ip4;
  919. fl4->daddr = daddr;
  920. fl4->saddr = saddr;
  921. fl4->fl4_dport = dport;
  922. fl4->fl4_sport = inet->inet_sport;
  923. up->pending = AF_INET;
  924. do_append_data:
  925. up->len += ulen;
  926. err = ip_append_data(sk, fl4, getfrag, msg->msg_iov, ulen,
  927. sizeof(struct udphdr), &ipc, &rt,
  928. corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
  929. if (err)
  930. udp_flush_pending_frames(sk);
  931. else if (!corkreq)
  932. err = udp_push_pending_frames(sk);
  933. else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
  934. up->pending = 0;
  935. release_sock(sk);
  936. out:
  937. ip_rt_put(rt);
  938. if (free)
  939. kfree(ipc.opt);
  940. if (!err)
  941. return len;
  942. /*
  943. * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
  944. * ENOBUFS might not be good (it's not tunable per se), but otherwise
  945. * we don't have a good statistic (IpOutDiscards but it can be too many
  946. * things). We could add another new stat but at least for now that
  947. * seems like overkill.
  948. */
  949. if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
  950. UDP_INC_STATS_USER(sock_net(sk),
  951. UDP_MIB_SNDBUFERRORS, is_udplite);
  952. }
  953. return err;
  954. do_confirm:
  955. dst_confirm(&rt->dst);
  956. if (!(msg->msg_flags&MSG_PROBE) || len)
  957. goto back_from_confirm;
  958. err = 0;
  959. goto out;
  960. }
  961. EXPORT_SYMBOL(udp_sendmsg);
  962. int udp_sendpage(struct sock *sk, struct page *page, int offset,
  963. size_t size, int flags)
  964. {
  965. struct inet_sock *inet = inet_sk(sk);
  966. struct udp_sock *up = udp_sk(sk);
  967. int ret;
  968. if (!up->pending) {
  969. struct msghdr msg = { .msg_flags = flags|MSG_MORE };
  970. /* Call udp_sendmsg to specify destination address which
  971. * sendpage interface can't pass.
  972. * This will succeed only when the socket is connected.
  973. */
  974. ret = udp_sendmsg(NULL, sk, &msg, 0);
  975. if (ret < 0)
  976. return ret;
  977. }
  978. lock_sock(sk);
  979. if (unlikely(!up->pending)) {
  980. release_sock(sk);
  981. LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("udp cork app bug 3\n"));
  982. return -EINVAL;
  983. }
  984. ret = ip_append_page(sk, &inet->cork.fl.u.ip4,
  985. page, offset, size, flags);
  986. if (ret == -EOPNOTSUPP) {
  987. release_sock(sk);
  988. return sock_no_sendpage(sk->sk_socket, page, offset,
  989. size, flags);
  990. }
  991. if (ret < 0) {
  992. udp_flush_pending_frames(sk);
  993. goto out;
  994. }
  995. up->len += size;
  996. if (!(up->corkflag || (flags&MSG_MORE)))
  997. ret = udp_push_pending_frames(sk);
  998. if (!ret)
  999. ret = size;
  1000. out:
  1001. release_sock(sk);
  1002. return ret;
  1003. }
  1004. /**
  1005. * first_packet_length - return length of first packet in receive queue
  1006. * @sk: socket
  1007. *
  1008. * Drops all bad checksum frames, until a valid one is found.
  1009. * Returns the length of found skb, or 0 if none is found.
  1010. */
  1011. static unsigned int first_packet_length(struct sock *sk)
  1012. {
  1013. struct sk_buff_head list_kill, *rcvq = &sk->sk_receive_queue;
  1014. struct sk_buff *skb;
  1015. unsigned int res;
  1016. __skb_queue_head_init(&list_kill);
  1017. spin_lock_bh(&rcvq->lock);
  1018. while ((skb = skb_peek(rcvq)) != NULL &&
  1019. udp_lib_checksum_complete(skb)) {
  1020. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS,
  1021. IS_UDPLITE(sk));
  1022. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS,
  1023. IS_UDPLITE(sk));
  1024. atomic_inc(&sk->sk_drops);
  1025. __skb_unlink(skb, rcvq);
  1026. __skb_queue_tail(&list_kill, skb);
  1027. }
  1028. res = skb ? skb->len : 0;
  1029. spin_unlock_bh(&rcvq->lock);
  1030. if (!skb_queue_empty(&list_kill)) {
  1031. bool slow = lock_sock_fast(sk);
  1032. __skb_queue_purge(&list_kill);
  1033. sk_mem_reclaim_partial(sk);
  1034. unlock_sock_fast(sk, slow);
  1035. }
  1036. return res;
  1037. }
  1038. /*
  1039. * IOCTL requests applicable to the UDP protocol
  1040. */
  1041. int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  1042. {
  1043. switch (cmd) {
  1044. case SIOCOUTQ:
  1045. {
  1046. int amount = sk_wmem_alloc_get(sk);
  1047. return put_user(amount, (int __user *)arg);
  1048. }
  1049. case SIOCINQ:
  1050. {
  1051. unsigned int amount = first_packet_length(sk);
  1052. if (amount)
  1053. /*
  1054. * We will only return the amount
  1055. * of this packet since that is all
  1056. * that will be read.
  1057. */
  1058. amount -= sizeof(struct udphdr);
  1059. return put_user(amount, (int __user *)arg);
  1060. }
  1061. default:
  1062. return -ENOIOCTLCMD;
  1063. }
  1064. return 0;
  1065. }
  1066. EXPORT_SYMBOL(udp_ioctl);
  1067. /*
  1068. * This should be easy, if there is something there we
  1069. * return it, otherwise we block.
  1070. */
  1071. int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
  1072. size_t len, int noblock, int flags, int *addr_len)
  1073. {
  1074. struct inet_sock *inet = inet_sk(sk);
  1075. struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
  1076. struct sk_buff *skb;
  1077. unsigned int ulen, copied;
  1078. int peeked, off = 0;
  1079. int err;
  1080. int is_udplite = IS_UDPLITE(sk);
  1081. bool slow;
  1082. /*
  1083. * Check any passed addresses
  1084. */
  1085. if (addr_len)
  1086. *addr_len = sizeof(*sin);
  1087. if (flags & MSG_ERRQUEUE)
  1088. return ip_recv_error(sk, msg, len);
  1089. try_again:
  1090. skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
  1091. &peeked, &off, &err);
  1092. if (!skb)
  1093. goto out;
  1094. ulen = skb->len - sizeof(struct udphdr);
  1095. copied = len;
  1096. if (copied > ulen)
  1097. copied = ulen;
  1098. else if (copied < ulen)
  1099. msg->msg_flags |= MSG_TRUNC;
  1100. /*
  1101. * If checksum is needed at all, try to do it while copying the
  1102. * data. If the data is truncated, or if we only want a partial
  1103. * coverage checksum (UDP-Lite), do it before the copy.
  1104. */
  1105. if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
  1106. if (udp_lib_checksum_complete(skb))
  1107. goto csum_copy_err;
  1108. }
  1109. if (skb_csum_unnecessary(skb))
  1110. err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
  1111. msg->msg_iov, copied);
  1112. else {
  1113. err = skb_copy_and_csum_datagram_iovec(skb,
  1114. sizeof(struct udphdr),
  1115. msg->msg_iov);
  1116. if (err == -EINVAL)
  1117. goto csum_copy_err;
  1118. }
  1119. if (unlikely(err)) {
  1120. trace_kfree_skb(skb, udp_recvmsg);
  1121. if (!peeked) {
  1122. atomic_inc(&sk->sk_drops);
  1123. UDP_INC_STATS_USER(sock_net(sk),
  1124. UDP_MIB_INERRORS, is_udplite);
  1125. }
  1126. goto out_free;
  1127. }
  1128. if (!peeked)
  1129. UDP_INC_STATS_USER(sock_net(sk),
  1130. UDP_MIB_INDATAGRAMS, is_udplite);
  1131. sock_recv_ts_and_drops(msg, sk, skb);
  1132. /* Copy the address. */
  1133. if (sin) {
  1134. sin->sin_family = AF_INET;
  1135. sin->sin_port = udp_hdr(skb)->source;
  1136. sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
  1137. memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
  1138. }
  1139. if (inet->cmsg_flags)
  1140. ip_cmsg_recv(msg, skb);
  1141. err = copied;
  1142. if (flags & MSG_TRUNC)
  1143. err = ulen;
  1144. out_free:
  1145. skb_free_datagram_locked(sk, skb);
  1146. out:
  1147. return err;
  1148. csum_copy_err:
  1149. slow = lock_sock_fast(sk);
  1150. if (!skb_kill_datagram(sk, skb, flags)) {
  1151. UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
  1152. UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1153. }
  1154. unlock_sock_fast(sk, slow);
  1155. if (noblock)
  1156. return -EAGAIN;
  1157. /* starting over for a new packet */
  1158. msg->msg_flags &= ~MSG_TRUNC;
  1159. goto try_again;
  1160. }
  1161. int udp_disconnect(struct sock *sk, int flags)
  1162. {
  1163. struct inet_sock *inet = inet_sk(sk);
  1164. /*
  1165. * 1003.1g - break association.
  1166. */
  1167. sk->sk_state = TCP_CLOSE;
  1168. inet->inet_daddr = 0;
  1169. inet->inet_dport = 0;
  1170. sock_rps_reset_rxhash(sk);
  1171. sk->sk_bound_dev_if = 0;
  1172. if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
  1173. inet_reset_saddr(sk);
  1174. if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
  1175. sk->sk_prot->unhash(sk);
  1176. inet->inet_sport = 0;
  1177. }
  1178. sk_dst_reset(sk);
  1179. return 0;
  1180. }
  1181. EXPORT_SYMBOL(udp_disconnect);
  1182. void udp_lib_unhash(struct sock *sk)
  1183. {
  1184. if (sk_hashed(sk)) {
  1185. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  1186. struct udp_hslot *hslot, *hslot2;
  1187. hslot = udp_hashslot(udptable, sock_net(sk),
  1188. udp_sk(sk)->udp_port_hash);
  1189. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  1190. spin_lock_bh(&hslot->lock);
  1191. if (sk_nulls_del_node_init_rcu(sk)) {
  1192. hslot->count--;
  1193. inet_sk(sk)->inet_num = 0;
  1194. sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
  1195. spin_lock(&hslot2->lock);
  1196. hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
  1197. hslot2->count--;
  1198. spin_unlock(&hslot2->lock);
  1199. }
  1200. spin_unlock_bh(&hslot->lock);
  1201. }
  1202. }
  1203. EXPORT_SYMBOL(udp_lib_unhash);
  1204. /*
  1205. * inet_rcv_saddr was changed, we must rehash secondary hash
  1206. */
  1207. void udp_lib_rehash(struct sock *sk, u16 newhash)
  1208. {
  1209. if (sk_hashed(sk)) {
  1210. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  1211. struct udp_hslot *hslot, *hslot2, *nhslot2;
  1212. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  1213. nhslot2 = udp_hashslot2(udptable, newhash);
  1214. udp_sk(sk)->udp_portaddr_hash = newhash;
  1215. if (hslot2 != nhslot2) {
  1216. hslot = udp_hashslot(udptable, sock_net(sk),
  1217. udp_sk(sk)->udp_port_hash);
  1218. /* we must lock primary chain too */
  1219. spin_lock_bh(&hslot->lock);
  1220. spin_lock(&hslot2->lock);
  1221. hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
  1222. hslot2->count--;
  1223. spin_unlock(&hslot2->lock);
  1224. spin_lock(&nhslot2->lock);
  1225. hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
  1226. &nhslot2->head);
  1227. nhslot2->count++;
  1228. spin_unlock(&nhslot2->lock);
  1229. spin_unlock_bh(&hslot->lock);
  1230. }
  1231. }
  1232. }
  1233. EXPORT_SYMBOL(udp_lib_rehash);
  1234. static void udp_v4_rehash(struct sock *sk)
  1235. {
  1236. u16 new_hash = udp4_portaddr_hash(sock_net(sk),
  1237. inet_sk(sk)->inet_rcv_saddr,
  1238. inet_sk(sk)->inet_num);
  1239. udp_lib_rehash(sk, new_hash);
  1240. }
  1241. static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  1242. {
  1243. int rc;
  1244. if (inet_sk(sk)->inet_daddr)
  1245. sock_rps_save_rxhash(sk, skb);
  1246. rc = sock_queue_rcv_skb(sk, skb);
  1247. if (rc < 0) {
  1248. int is_udplite = IS_UDPLITE(sk);
  1249. /* Note that an ENOMEM error is charged twice */
  1250. if (rc == -ENOMEM)
  1251. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS,
  1252. is_udplite);
  1253. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1254. kfree_skb(skb);
  1255. trace_udp_fail_queue_rcv_skb(rc, sk);
  1256. return -1;
  1257. }
  1258. return 0;
  1259. }
  1260. static struct static_key udp_encap_needed __read_mostly;
  1261. void udp_encap_enable(void)
  1262. {
  1263. if (!static_key_enabled(&udp_encap_needed))
  1264. static_key_slow_inc(&udp_encap_needed);
  1265. }
  1266. EXPORT_SYMBOL(udp_encap_enable);
  1267. /* returns:
  1268. * -1: error
  1269. * 0: success
  1270. * >0: "udp encap" protocol resubmission
  1271. *
  1272. * Note that in the success and error cases, the skb is assumed to
  1273. * have either been requeued or freed.
  1274. */
  1275. int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  1276. {
  1277. struct udp_sock *up = udp_sk(sk);
  1278. int rc;
  1279. int is_udplite = IS_UDPLITE(sk);
  1280. /*
  1281. * Charge it to the socket, dropping if the queue is full.
  1282. */
  1283. if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
  1284. goto drop;
  1285. nf_reset(skb);
  1286. if (static_key_false(&udp_encap_needed) && up->encap_type) {
  1287. int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
  1288. /*
  1289. * This is an encapsulation socket so pass the skb to
  1290. * the socket's udp_encap_rcv() hook. Otherwise, just
  1291. * fall through and pass this up the UDP socket.
  1292. * up->encap_rcv() returns the following value:
  1293. * =0 if skb was successfully passed to the encap
  1294. * handler or was discarded by it.
  1295. * >0 if skb should be passed on to UDP.
  1296. * <0 if skb should be resubmitted as proto -N
  1297. */
  1298. /* if we're overly short, let UDP handle it */
  1299. encap_rcv = ACCESS_ONCE(up->encap_rcv);
  1300. if (skb->len > sizeof(struct udphdr) && encap_rcv != NULL) {
  1301. int ret;
  1302. ret = encap_rcv(sk, skb);
  1303. if (ret <= 0) {
  1304. UDP_INC_STATS_BH(sock_net(sk),
  1305. UDP_MIB_INDATAGRAMS,
  1306. is_udplite);
  1307. return -ret;
  1308. }
  1309. }
  1310. /* FALLTHROUGH -- it's a UDP Packet */
  1311. }
  1312. /*
  1313. * UDP-Lite specific tests, ignored on UDP sockets
  1314. */
  1315. if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) {
  1316. /*
  1317. * MIB statistics other than incrementing the error count are
  1318. * disabled for the following two types of errors: these depend
  1319. * on the application settings, not on the functioning of the
  1320. * protocol stack as such.
  1321. *
  1322. * RFC 3828 here recommends (sec 3.3): "There should also be a
  1323. * way ... to ... at least let the receiving application block
  1324. * delivery of packets with coverage values less than a value
  1325. * provided by the application."
  1326. */
  1327. if (up->pcrlen == 0) { /* full coverage was set */
  1328. LIMIT_NETDEBUG(KERN_WARNING "UDPLite: partial coverage %d while full coverage %d requested\n",
  1329. UDP_SKB_CB(skb)->cscov, skb->len);
  1330. goto drop;
  1331. }
  1332. /* The next case involves violating the min. coverage requested
  1333. * by the receiver. This is subtle: if receiver wants x and x is
  1334. * greater than the buffersize/MTU then receiver will complain
  1335. * that it wants x while sender emits packets of smaller size y.
  1336. * Therefore the above ...()->partial_cov statement is essential.
  1337. */
  1338. if (UDP_SKB_CB(skb)->cscov < up->pcrlen) {
  1339. LIMIT_NETDEBUG(KERN_WARNING "UDPLite: coverage %d too small, need min %d\n",
  1340. UDP_SKB_CB(skb)->cscov, up->pcrlen);
  1341. goto drop;
  1342. }
  1343. }
  1344. if (rcu_access_pointer(sk->sk_filter) &&
  1345. udp_lib_checksum_complete(skb))
  1346. goto csum_error;
  1347. if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf))
  1348. goto drop;
  1349. rc = 0;
  1350. ipv4_pktinfo_prepare(skb);
  1351. bh_lock_sock(sk);
  1352. if (!sock_owned_by_user(sk))
  1353. rc = __udp_queue_rcv_skb(sk, skb);
  1354. else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) {
  1355. bh_unlock_sock(sk);
  1356. goto drop;
  1357. }
  1358. bh_unlock_sock(sk);
  1359. return rc;
  1360. csum_error:
  1361. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
  1362. drop:
  1363. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1364. atomic_inc(&sk->sk_drops);
  1365. kfree_skb(skb);
  1366. return -1;
  1367. }
  1368. static void flush_stack(struct sock **stack, unsigned int count,
  1369. struct sk_buff *skb, unsigned int final)
  1370. {
  1371. unsigned int i;
  1372. struct sk_buff *skb1 = NULL;
  1373. struct sock *sk;
  1374. for (i = 0; i < count; i++) {
  1375. sk = stack[i];
  1376. if (likely(skb1 == NULL))
  1377. skb1 = (i == final) ? skb : skb_clone(skb, GFP_ATOMIC);
  1378. if (!skb1) {
  1379. atomic_inc(&sk->sk_drops);
  1380. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS,
  1381. IS_UDPLITE(sk));
  1382. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS,
  1383. IS_UDPLITE(sk));
  1384. }
  1385. if (skb1 && udp_queue_rcv_skb(sk, skb1) <= 0)
  1386. skb1 = NULL;
  1387. }
  1388. if (unlikely(skb1))
  1389. kfree_skb(skb1);
  1390. }
  1391. /*
  1392. * Multicasts and broadcasts go to each listener.
  1393. *
  1394. * Note: called only from the BH handler context.
  1395. */
  1396. static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
  1397. struct udphdr *uh,
  1398. __be32 saddr, __be32 daddr,
  1399. struct udp_table *udptable)
  1400. {
  1401. struct sock *sk, *stack[256 / sizeof(struct sock *)];
  1402. struct udp_hslot *hslot = udp_hashslot(udptable, net, ntohs(uh->dest));
  1403. int dif;
  1404. unsigned int i, count = 0;
  1405. spin_lock(&hslot->lock);
  1406. sk = sk_nulls_head(&hslot->head);
  1407. dif = skb->dev->ifindex;
  1408. sk = udp_v4_mcast_next(net, sk, uh->dest, daddr, uh->source, saddr, dif);
  1409. while (sk) {
  1410. stack[count++] = sk;
  1411. sk = udp_v4_mcast_next(net, sk_nulls_next(sk), uh->dest,
  1412. daddr, uh->source, saddr, dif);
  1413. if (unlikely(count == ARRAY_SIZE(stack))) {
  1414. if (!sk)
  1415. break;
  1416. flush_stack(stack, count, skb, ~0);
  1417. count = 0;
  1418. }
  1419. }
  1420. /*
  1421. * before releasing chain lock, we must take a reference on sockets
  1422. */
  1423. for (i = 0; i < count; i++)
  1424. sock_hold(stack[i]);
  1425. spin_unlock(&hslot->lock);
  1426. /*
  1427. * do the slow work with no lock held
  1428. */
  1429. if (count) {
  1430. flush_stack(stack, count, skb, count - 1);
  1431. for (i = 0; i < count; i++)
  1432. sock_put(stack[i]);
  1433. } else {
  1434. kfree_skb(skb);
  1435. }
  1436. return 0;
  1437. }
  1438. /* Initialize UDP checksum. If exited with zero value (success),
  1439. * CHECKSUM_UNNECESSARY means, that no more checks are required.
  1440. * Otherwise, csum completion requires chacksumming packet body,
  1441. * including udp header and folding it to skb->csum.
  1442. */
  1443. static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
  1444. int proto)
  1445. {
  1446. const struct iphdr *iph;
  1447. int err;
  1448. UDP_SKB_CB(skb)->partial_cov = 0;
  1449. UDP_SKB_CB(skb)->cscov = skb->len;
  1450. if (proto == IPPROTO_UDPLITE) {
  1451. err = udplite_checksum_init(skb, uh);
  1452. if (err)
  1453. return err;
  1454. }
  1455. iph = ip_hdr(skb);
  1456. if (uh->check == 0) {
  1457. skb->ip_summed = CHECKSUM_UNNECESSARY;
  1458. } else if (skb->ip_summed == CHECKSUM_COMPLETE) {
  1459. if (!csum_tcpudp_magic(iph->saddr, iph->daddr, skb->len,
  1460. proto, skb->csum))
  1461. skb->ip_summed = CHECKSUM_UNNECESSARY;
  1462. }
  1463. if (!skb_csum_unnecessary(skb))
  1464. skb->csum = csum_tcpudp_nofold(iph->saddr, iph->daddr,
  1465. skb->len, proto, 0);
  1466. /* Probably, we should checksum udp header (it should be in cache
  1467. * in any case) and data in tiny packets (< rx copybreak).
  1468. */
  1469. return 0;
  1470. }
  1471. /*
  1472. * All we need to do is get the socket, and then do a checksum.
  1473. */
  1474. int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
  1475. int proto)
  1476. {
  1477. struct sock *sk;
  1478. struct udphdr *uh;
  1479. unsigned short ulen;
  1480. struct rtable *rt = skb_rtable(skb);
  1481. __be32 saddr, daddr;
  1482. struct net *net = dev_net(skb->dev);
  1483. /*
  1484. * Validate the packet.
  1485. */
  1486. if (!pskb_may_pull(skb, sizeof(struct udphdr)))
  1487. goto drop; /* No space for header. */
  1488. uh = udp_hdr(skb);
  1489. ulen = ntohs(uh->len);
  1490. saddr = ip_hdr(skb)->saddr;
  1491. daddr = ip_hdr(skb)->daddr;
  1492. if (ulen > skb->len)
  1493. goto short_packet;
  1494. if (proto == IPPROTO_UDP) {
  1495. /* UDP validates ulen. */
  1496. if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
  1497. goto short_packet;
  1498. uh = udp_hdr(skb);
  1499. }
  1500. if (udp4_csum_init(skb, uh, proto))
  1501. goto csum_error;
  1502. if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
  1503. return __udp4_lib_mcast_deliver(net, skb, uh,
  1504. saddr, daddr, udptable);
  1505. sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
  1506. if (sk != NULL) {
  1507. int ret;
  1508. sk_mark_ll(sk, skb);
  1509. ret = udp_queue_rcv_skb(sk, skb);
  1510. sock_put(sk);
  1511. /* a return value > 0 means to resubmit the input, but
  1512. * it wants the return to be -protocol, or 0
  1513. */
  1514. if (ret > 0)
  1515. return -ret;
  1516. return 0;
  1517. }
  1518. if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
  1519. goto drop;
  1520. nf_reset(skb);
  1521. /* No socket. Drop packet silently, if checksum is wrong */
  1522. if (udp_lib_checksum_complete(skb))
  1523. goto csum_error;
  1524. UDP_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
  1525. icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
  1526. /*
  1527. * Hmm. We got an UDP packet to a port to which we
  1528. * don't wanna listen. Ignore it.
  1529. */
  1530. kfree_skb(skb);
  1531. return 0;
  1532. short_packet:
  1533. LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
  1534. proto == IPPROTO_UDPLITE ? "Lite" : "",
  1535. &saddr, ntohs(uh->source),
  1536. ulen, skb->len,
  1537. &daddr, ntohs(uh->dest));
  1538. goto drop;
  1539. csum_error:
  1540. /*
  1541. * RFC1122: OK. Discards the bad packet silently (as far as
  1542. * the network is concerned, anyway) as per 4.1.3.4 (MUST).
  1543. */
  1544. LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
  1545. proto == IPPROTO_UDPLITE ? "Lite" : "",
  1546. &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
  1547. ulen);
  1548. UDP_INC_STATS_BH(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
  1549. drop:
  1550. UDP_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
  1551. kfree_skb(skb);
  1552. return 0;
  1553. }
  1554. int udp_rcv(struct sk_buff *skb)
  1555. {
  1556. return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
  1557. }
  1558. void udp_destroy_sock(struct sock *sk)
  1559. {
  1560. struct udp_sock *up = udp_sk(sk);
  1561. bool slow = lock_sock_fast(sk);
  1562. udp_flush_pending_frames(sk);
  1563. unlock_sock_fast(sk, slow);
  1564. if (static_key_false(&udp_encap_needed) && up->encap_type) {
  1565. void (*encap_destroy)(struct sock *sk);
  1566. encap_destroy = ACCESS_ONCE(up->encap_destroy);
  1567. if (encap_destroy)
  1568. encap_destroy(sk);
  1569. }
  1570. }
  1571. /*
  1572. * Socket option code for UDP
  1573. */
  1574. int udp_lib_setsockopt(struct sock *sk, int level, int optname,
  1575. char __user *optval, unsigned int optlen,
  1576. int (*push_pending_frames)(struct sock *))
  1577. {
  1578. struct udp_sock *up = udp_sk(sk);
  1579. int val;
  1580. int err = 0;
  1581. int is_udplite = IS_UDPLITE(sk);
  1582. if (optlen < sizeof(int))
  1583. return -EINVAL;
  1584. if (get_user(val, (int __user *)optval))
  1585. return -EFAULT;
  1586. switch (optname) {
  1587. case UDP_CORK:
  1588. if (val != 0) {
  1589. up->corkflag = 1;
  1590. } else {
  1591. up->corkflag = 0;
  1592. lock_sock(sk);
  1593. (*push_pending_frames)(sk);
  1594. release_sock(sk);
  1595. }
  1596. break;
  1597. case UDP_ENCAP:
  1598. switch (val) {
  1599. case 0:
  1600. case UDP_ENCAP_ESPINUDP:
  1601. case UDP_ENCAP_ESPINUDP_NON_IKE:
  1602. up->encap_rcv = xfrm4_udp_encap_rcv;
  1603. /* FALLTHROUGH */
  1604. case UDP_ENCAP_L2TPINUDP:
  1605. up->encap_type = val;
  1606. udp_encap_enable();
  1607. break;
  1608. default:
  1609. err = -ENOPROTOOPT;
  1610. break;
  1611. }
  1612. break;
  1613. /*
  1614. * UDP-Lite's partial checksum coverage (RFC 3828).
  1615. */
  1616. /* The sender sets actual checksum coverage length via this option.
  1617. * The case coverage > packet length is handled by send module. */
  1618. case UDPLITE_SEND_CSCOV:
  1619. if (!is_udplite) /* Disable the option on UDP sockets */
  1620. return -ENOPROTOOPT;
  1621. if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
  1622. val = 8;
  1623. else if (val > USHRT_MAX)
  1624. val = USHRT_MAX;
  1625. up->pcslen = val;
  1626. up->pcflag |= UDPLITE_SEND_CC;
  1627. break;
  1628. /* The receiver specifies a minimum checksum coverage value. To make
  1629. * sense, this should be set to at least 8 (as done below). If zero is
  1630. * used, this again means full checksum coverage. */
  1631. case UDPLITE_RECV_CSCOV:
  1632. if (!is_udplite) /* Disable the option on UDP sockets */
  1633. return -ENOPROTOOPT;
  1634. if (val != 0 && val < 8) /* Avoid silly minimal values. */
  1635. val = 8;
  1636. else if (val > USHRT_MAX)
  1637. val = USHRT_MAX;
  1638. up->pcrlen = val;
  1639. up->pcflag |= UDPLITE_RECV_CC;
  1640. break;
  1641. default:
  1642. err = -ENOPROTOOPT;
  1643. break;
  1644. }
  1645. return err;
  1646. }
  1647. EXPORT_SYMBOL(udp_lib_setsockopt);
  1648. int udp_setsockopt(struct sock *sk, int level, int optname,
  1649. char __user *optval, unsigned int optlen)
  1650. {
  1651. if (level == SOL_UDP || level == SOL_UDPLITE)
  1652. return udp_lib_setsockopt(sk, level, optname, optval, optlen,
  1653. udp_push_pending_frames);
  1654. return ip_setsockopt(sk, level, optname, optval, optlen);
  1655. }
  1656. #ifdef CONFIG_COMPAT
  1657. int compat_udp_setsockopt(struct sock *sk, int level, int optname,
  1658. char __user *optval, unsigned int optlen)
  1659. {
  1660. if (level == SOL_UDP || level == SOL_UDPLITE)
  1661. return udp_lib_setsockopt(sk, level, optname, optval, optlen,
  1662. udp_push_pending_frames);
  1663. return compat_ip_setsockopt(sk, level, optname, optval, optlen);
  1664. }
  1665. #endif
  1666. int udp_lib_getsockopt(struct sock *sk, int level, int optname,
  1667. char __user *optval, int __user *optlen)
  1668. {
  1669. struct udp_sock *up = udp_sk(sk);
  1670. int val, len;
  1671. if (get_user(len, optlen))
  1672. return -EFAULT;
  1673. len = min_t(unsigned int, len, sizeof(int));
  1674. if (len < 0)
  1675. return -EINVAL;
  1676. switch (optname) {
  1677. case UDP_CORK:
  1678. val = up->corkflag;
  1679. break;
  1680. case UDP_ENCAP:
  1681. val = up->encap_type;
  1682. break;
  1683. /* The following two cannot be changed on UDP sockets, the return is
  1684. * always 0 (which corresponds to the full checksum coverage of UDP). */
  1685. case UDPLITE_SEND_CSCOV:
  1686. val = up->pcslen;
  1687. break;
  1688. case UDPLITE_RECV_CSCOV:
  1689. val = up->pcrlen;
  1690. break;
  1691. default:
  1692. return -ENOPROTOOPT;
  1693. }
  1694. if (put_user(len, optlen))
  1695. return -EFAULT;
  1696. if (copy_to_user(optval, &val, len))
  1697. return -EFAULT;
  1698. return 0;
  1699. }
  1700. EXPORT_SYMBOL(udp_lib_getsockopt);
  1701. int udp_getsockopt(struct sock *sk, int level, int optname,
  1702. char __user *optval, int __user *optlen)
  1703. {
  1704. if (level == SOL_UDP || level == SOL_UDPLITE)
  1705. return udp_lib_getsockopt(sk, level, optname, optval, optlen);
  1706. return ip_getsockopt(sk, level, optname, optval, optlen);
  1707. }
  1708. #ifdef CONFIG_COMPAT
  1709. int compat_udp_getsockopt(struct sock *sk, int level, int optname,
  1710. char __user *optval, int __user *optlen)
  1711. {
  1712. if (level == SOL_UDP || level == SOL_UDPLITE)
  1713. return udp_lib_getsockopt(sk, level, optname, optval, optlen);
  1714. return compat_ip_getsockopt(sk, level, optname, optval, optlen);
  1715. }
  1716. #endif
  1717. /**
  1718. * udp_poll - wait for a UDP event.
  1719. * @file - file struct
  1720. * @sock - socket
  1721. * @wait - poll table
  1722. *
  1723. * This is same as datagram poll, except for the special case of
  1724. * blocking sockets. If application is using a blocking fd
  1725. * and a packet with checksum error is in the queue;
  1726. * then it could get return from select indicating data available
  1727. * but then block when reading it. Add special case code
  1728. * to work around these arguably broken applications.
  1729. */
  1730. unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
  1731. {
  1732. unsigned int mask = datagram_poll(file, sock, wait);
  1733. struct sock *sk = sock->sk;
  1734. sock_rps_record_flow(sk);
  1735. /* Check for false positives due to checksum errors */
  1736. if ((mask & POLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
  1737. !(sk->sk_shutdown & RCV_SHUTDOWN) && !first_packet_length(sk))
  1738. mask &= ~(POLLIN | POLLRDNORM);
  1739. return mask;
  1740. }
  1741. EXPORT_SYMBOL(udp_poll);
  1742. struct proto udp_prot = {
  1743. .name = "UDP",
  1744. .owner = THIS_MODULE,
  1745. .close = udp_lib_close,
  1746. .connect = ip4_datagram_connect,
  1747. .disconnect = udp_disconnect,
  1748. .ioctl = udp_ioctl,
  1749. .destroy = udp_destroy_sock,
  1750. .setsockopt = udp_setsockopt,
  1751. .getsockopt = udp_getsockopt,
  1752. .sendmsg = udp_sendmsg,
  1753. .recvmsg = udp_recvmsg,
  1754. .sendpage = udp_sendpage,
  1755. .backlog_rcv = __udp_queue_rcv_skb,
  1756. .release_cb = ip4_datagram_release_cb,
  1757. .hash = udp_lib_hash,
  1758. .unhash = udp_lib_unhash,
  1759. .rehash = udp_v4_rehash,
  1760. .get_port = udp_v4_get_port,
  1761. .memory_allocated = &udp_memory_allocated,
  1762. .sysctl_mem = sysctl_udp_mem,
  1763. .sysctl_wmem = &sysctl_udp_wmem_min,
  1764. .sysctl_rmem = &sysctl_udp_rmem_min,
  1765. .obj_size = sizeof(struct udp_sock),
  1766. .slab_flags = SLAB_DESTROY_BY_RCU,
  1767. .h.udp_table = &udp_table,
  1768. #ifdef CONFIG_COMPAT
  1769. .compat_setsockopt = compat_udp_setsockopt,
  1770. .compat_getsockopt = compat_udp_getsockopt,
  1771. #endif
  1772. .clear_sk = sk_prot_clear_portaddr_nulls,
  1773. };
  1774. EXPORT_SYMBOL(udp_prot);
  1775. /* ------------------------------------------------------------------------ */
  1776. #ifdef CONFIG_PROC_FS
  1777. static struct sock *udp_get_first(struct seq_file *seq, int start)
  1778. {
  1779. struct sock *sk;
  1780. struct udp_iter_state *state = seq->private;
  1781. struct net *net = seq_file_net(seq);
  1782. for (state->bucket = start; state->bucket <= state->udp_table->mask;
  1783. ++state->bucket) {
  1784. struct hlist_nulls_node *node;
  1785. struct udp_hslot *hslot = &state->udp_table->hash[state->bucket];
  1786. if (hlist_nulls_empty(&hslot->head))
  1787. continue;
  1788. spin_lock_bh(&hslot->lock);
  1789. sk_nulls_for_each(sk, node, &hslot->head) {
  1790. if (!net_eq(sock_net(sk), net))
  1791. continue;
  1792. if (sk->sk_family == state->family)
  1793. goto found;
  1794. }
  1795. spin_unlock_bh(&hslot->lock);
  1796. }
  1797. sk = NULL;
  1798. found:
  1799. return sk;
  1800. }
  1801. static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
  1802. {
  1803. struct udp_iter_state *state = seq->private;
  1804. struct net *net = seq_file_net(seq);
  1805. do {
  1806. sk = sk_nulls_next(sk);
  1807. } while (sk && (!net_eq(sock_net(sk), net) || sk->sk_family != state->family));
  1808. if (!sk) {
  1809. if (state->bucket <= state->udp_table->mask)
  1810. spin_unlock_bh(&state->udp_table->hash[state->bucket].lock);
  1811. return udp_get_first(seq, state->bucket + 1);
  1812. }
  1813. return sk;
  1814. }
  1815. static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
  1816. {
  1817. struct sock *sk = udp_get_first(seq, 0);
  1818. if (sk)
  1819. while (pos && (sk = udp_get_next(seq, sk)) != NULL)
  1820. --pos;
  1821. return pos ? NULL : sk;
  1822. }
  1823. static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
  1824. {
  1825. struct udp_iter_state *state = seq->private;
  1826. state->bucket = MAX_UDP_PORTS;
  1827. return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
  1828. }
  1829. static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  1830. {
  1831. struct sock *sk;
  1832. if (v == SEQ_START_TOKEN)
  1833. sk = udp_get_idx(seq, 0);
  1834. else
  1835. sk = udp_get_next(seq, v);
  1836. ++*pos;
  1837. return sk;
  1838. }
  1839. static void udp_seq_stop(struct seq_file *seq, void *v)
  1840. {
  1841. struct udp_iter_state *state = seq->private;
  1842. if (state->bucket <= state->udp_table->mask)
  1843. spin_unlock_bh(&state->udp_table->hash[state->bucket].lock);
  1844. }
  1845. int udp_seq_open(struct inode *inode, struct file *file)
  1846. {
  1847. struct udp_seq_afinfo *afinfo = PDE_DATA(inode);
  1848. struct udp_iter_state *s;
  1849. int err;
  1850. err = seq_open_net(inode, file, &afinfo->seq_ops,
  1851. sizeof(struct udp_iter_state));
  1852. if (err < 0)
  1853. return err;
  1854. s = ((struct seq_file *)file->private_data)->private;
  1855. s->family = afinfo->family;
  1856. s->udp_table = afinfo->udp_table;
  1857. return err;
  1858. }
  1859. EXPORT_SYMBOL(udp_seq_open);
  1860. /* ------------------------------------------------------------------------ */
  1861. int udp_proc_register(struct net *net, struct udp_seq_afinfo *afinfo)
  1862. {
  1863. struct proc_dir_entry *p;
  1864. int rc = 0;
  1865. afinfo->seq_ops.start = udp_seq_start;
  1866. afinfo->seq_ops.next = udp_seq_next;
  1867. afinfo->seq_ops.stop = udp_seq_stop;
  1868. p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net,
  1869. afinfo->seq_fops, afinfo);
  1870. if (!p)
  1871. rc = -ENOMEM;
  1872. return rc;
  1873. }
  1874. EXPORT_SYMBOL(udp_proc_register);
  1875. void udp_proc_unregister(struct net *net, struct udp_seq_afinfo *afinfo)
  1876. {
  1877. remove_proc_entry(afinfo->name, net->proc_net);
  1878. }
  1879. EXPORT_SYMBOL(udp_proc_unregister);
  1880. /* ------------------------------------------------------------------------ */
  1881. static void udp4_format_sock(struct sock *sp, struct seq_file *f,
  1882. int bucket, int *len)
  1883. {
  1884. struct inet_sock *inet = inet_sk(sp);
  1885. __be32 dest = inet->inet_daddr;
  1886. __be32 src = inet->inet_rcv_saddr;
  1887. __u16 destp = ntohs(inet->inet_dport);
  1888. __u16 srcp = ntohs(inet->inet_sport);
  1889. seq_printf(f, "%5d: %08X:%04X %08X:%04X"
  1890. " %02X %08X:%08X %02X:%08lX %08X %5d %8d %lu %d %pK %d%n",
  1891. bucket, src, srcp, dest, destp, sp->sk_state,
  1892. sk_wmem_alloc_get(sp),
  1893. sk_rmem_alloc_get(sp),
  1894. 0, 0L, 0,
  1895. from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
  1896. 0, sock_i_ino(sp),
  1897. atomic_read(&sp->sk_refcnt), sp,
  1898. atomic_read(&sp->sk_drops), len);
  1899. }
  1900. int udp4_seq_show(struct seq_file *seq, void *v)
  1901. {
  1902. if (v == SEQ_START_TOKEN)
  1903. seq_printf(seq, "%-127s\n",
  1904. " sl local_address rem_address st tx_queue "
  1905. "rx_queue tr tm->when retrnsmt uid timeout "
  1906. "inode ref pointer drops");
  1907. else {
  1908. struct udp_iter_state *state = seq->private;
  1909. int len;
  1910. udp4_format_sock(v, seq, state->bucket, &len);
  1911. seq_printf(seq, "%*s\n", 127 - len, "");
  1912. }
  1913. return 0;
  1914. }
  1915. static const struct file_operations udp_afinfo_seq_fops = {
  1916. .owner = THIS_MODULE,
  1917. .open = udp_seq_open,
  1918. .read = seq_read,
  1919. .llseek = seq_lseek,
  1920. .release = seq_release_net
  1921. };
  1922. /* ------------------------------------------------------------------------ */
  1923. static struct udp_seq_afinfo udp4_seq_afinfo = {
  1924. .name = "udp",
  1925. .family = AF_INET,
  1926. .udp_table = &udp_table,
  1927. .seq_fops = &udp_afinfo_seq_fops,
  1928. .seq_ops = {
  1929. .show = udp4_seq_show,
  1930. },
  1931. };
  1932. static int __net_init udp4_proc_init_net(struct net *net)
  1933. {
  1934. return udp_proc_register(net, &udp4_seq_afinfo);
  1935. }
  1936. static void __net_exit udp4_proc_exit_net(struct net *net)
  1937. {
  1938. udp_proc_unregister(net, &udp4_seq_afinfo);
  1939. }
  1940. static struct pernet_operations udp4_net_ops = {
  1941. .init = udp4_proc_init_net,
  1942. .exit = udp4_proc_exit_net,
  1943. };
  1944. int __init udp4_proc_init(void)
  1945. {
  1946. return register_pernet_subsys(&udp4_net_ops);
  1947. }
  1948. void udp4_proc_exit(void)
  1949. {
  1950. unregister_pernet_subsys(&udp4_net_ops);
  1951. }
  1952. #endif /* CONFIG_PROC_FS */
  1953. static __initdata unsigned long uhash_entries;
  1954. static int __init set_uhash_entries(char *str)
  1955. {
  1956. ssize_t ret;
  1957. if (!str)
  1958. return 0;
  1959. ret = kstrtoul(str, 0, &uhash_entries);
  1960. if (ret)
  1961. return 0;
  1962. if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
  1963. uhash_entries = UDP_HTABLE_SIZE_MIN;
  1964. return 1;
  1965. }
  1966. __setup("uhash_entries=", set_uhash_entries);
  1967. void __init udp_table_init(struct udp_table *table, const char *name)
  1968. {
  1969. unsigned int i;
  1970. table->hash = alloc_large_system_hash(name,
  1971. 2 * sizeof(struct udp_hslot),
  1972. uhash_entries,
  1973. 21, /* one slot per 2 MB */
  1974. 0,
  1975. &table->log,
  1976. &table->mask,
  1977. UDP_HTABLE_SIZE_MIN,
  1978. 64 * 1024);
  1979. table->hash2 = table->hash + (table->mask + 1);
  1980. for (i = 0; i <= table->mask; i++) {
  1981. INIT_HLIST_NULLS_HEAD(&table->hash[i].head, i);
  1982. table->hash[i].count = 0;
  1983. spin_lock_init(&table->hash[i].lock);
  1984. }
  1985. for (i = 0; i <= table->mask; i++) {
  1986. INIT_HLIST_NULLS_HEAD(&table->hash2[i].head, i);
  1987. table->hash2[i].count = 0;
  1988. spin_lock_init(&table->hash2[i].lock);
  1989. }
  1990. }
  1991. void __init udp_init(void)
  1992. {
  1993. unsigned long limit;
  1994. udp_table_init(&udp_table, "UDP");
  1995. limit = nr_free_buffer_pages() / 8;
  1996. limit = max(limit, 128UL);
  1997. sysctl_udp_mem[0] = limit / 4 * 3;
  1998. sysctl_udp_mem[1] = limit;
  1999. sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
  2000. sysctl_udp_rmem_min = SK_MEM_QUANTUM;
  2001. sysctl_udp_wmem_min = SK_MEM_QUANTUM;
  2002. }
  2003. struct sk_buff *skb_udp_tunnel_segment(struct sk_buff *skb,
  2004. netdev_features_t features)
  2005. {
  2006. struct sk_buff *segs = ERR_PTR(-EINVAL);
  2007. int mac_len = skb->mac_len;
  2008. int tnl_hlen = skb_inner_mac_header(skb) - skb_transport_header(skb);
  2009. __be16 protocol = skb->protocol;
  2010. netdev_features_t enc_features;
  2011. int outer_hlen;
  2012. if (unlikely(!pskb_may_pull(skb, tnl_hlen)))
  2013. goto out;
  2014. skb->encapsulation = 0;
  2015. __skb_pull(skb, tnl_hlen);
  2016. skb_reset_mac_header(skb);
  2017. skb_set_network_header(skb, skb_inner_network_offset(skb));
  2018. skb->mac_len = skb_inner_network_offset(skb);
  2019. skb->protocol = htons(ETH_P_TEB);
  2020. /* segment inner packet. */
  2021. enc_features = skb->dev->hw_enc_features & netif_skb_features(skb);
  2022. segs = skb_mac_gso_segment(skb, enc_features);
  2023. if (!segs || IS_ERR(segs))
  2024. goto out;
  2025. outer_hlen = skb_tnl_header_len(skb);
  2026. skb = segs;
  2027. do {
  2028. struct udphdr *uh;
  2029. int udp_offset = outer_hlen - tnl_hlen;
  2030. skb->mac_len = mac_len;
  2031. skb_push(skb, outer_hlen);
  2032. skb_reset_mac_header(skb);
  2033. skb_set_network_header(skb, mac_len);
  2034. skb_set_transport_header(skb, udp_offset);
  2035. uh = udp_hdr(skb);
  2036. uh->len = htons(skb->len - udp_offset);
  2037. /* csum segment if tunnel sets skb with csum. */
  2038. if (unlikely(uh->check)) {
  2039. struct iphdr *iph = ip_hdr(skb);
  2040. uh->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr,
  2041. skb->len - udp_offset,
  2042. IPPROTO_UDP, 0);
  2043. uh->check = csum_fold(skb_checksum(skb, udp_offset,
  2044. skb->len - udp_offset, 0));
  2045. if (uh->check == 0)
  2046. uh->check = CSUM_MANGLED_0;
  2047. }
  2048. skb->ip_summed = CHECKSUM_NONE;
  2049. skb->protocol = protocol;
  2050. } while ((skb = skb->next));
  2051. out:
  2052. return segs;
  2053. }