udp.c 72 KB

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