udp.c 83 KB

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