udp.c 74 KB

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