udp.c 68 KB

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