udp.c 103 KB

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