udp.c 74 KB

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