udp.c 72 KB

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