udp.c 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367
  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 <asm/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/in.h>
  92. #include <linux/errno.h>
  93. #include <linux/timer.h>
  94. #include <linux/mm.h>
  95. #include <linux/inet.h>
  96. #include <linux/netdevice.h>
  97. #include <linux/slab.h>
  98. #include <net/tcp_states.h>
  99. #include <linux/skbuff.h>
  100. #include <linux/proc_fs.h>
  101. #include <linux/seq_file.h>
  102. #include <net/net_namespace.h>
  103. #include <net/icmp.h>
  104. #include <net/route.h>
  105. #include <net/checksum.h>
  106. #include <net/xfrm.h>
  107. #include <trace/events/udp.h>
  108. #include <linux/static_key.h>
  109. #include <trace/events/skb.h>
  110. #include <net/busy_poll.h>
  111. #include "udp_impl.h"
  112. struct udp_table udp_table __read_mostly;
  113. EXPORT_SYMBOL(udp_table);
  114. long sysctl_udp_mem[3] __read_mostly;
  115. EXPORT_SYMBOL(sysctl_udp_mem);
  116. int sysctl_udp_rmem_min __read_mostly;
  117. EXPORT_SYMBOL(sysctl_udp_rmem_min);
  118. int sysctl_udp_wmem_min __read_mostly;
  119. EXPORT_SYMBOL(sysctl_udp_wmem_min);
  120. atomic_long_t udp_memory_allocated;
  121. EXPORT_SYMBOL(udp_memory_allocated);
  122. #define MAX_UDP_PORTS 65536
  123. #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN)
  124. static int udp_lib_lport_inuse(struct net *net, __u16 num,
  125. const struct udp_hslot *hslot,
  126. unsigned long *bitmap,
  127. struct sock *sk,
  128. int (*saddr_comp)(const struct sock *sk1,
  129. const struct sock *sk2),
  130. unsigned int log)
  131. {
  132. struct sock *sk2;
  133. struct hlist_nulls_node *node;
  134. kuid_t uid = sock_i_uid(sk);
  135. sk_nulls_for_each(sk2, node, &hslot->head)
  136. if (net_eq(sock_net(sk2), net) &&
  137. sk2 != sk &&
  138. (bitmap || udp_sk(sk2)->udp_port_hash == num) &&
  139. (!sk2->sk_reuse || !sk->sk_reuse) &&
  140. (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
  141. sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
  142. (!sk2->sk_reuseport || !sk->sk_reuseport ||
  143. !uid_eq(uid, sock_i_uid(sk2))) &&
  144. (*saddr_comp)(sk, sk2)) {
  145. if (bitmap)
  146. __set_bit(udp_sk(sk2)->udp_port_hash >> log,
  147. bitmap);
  148. else
  149. return 1;
  150. }
  151. return 0;
  152. }
  153. /*
  154. * Note: we still hold spinlock of primary hash chain, so no other writer
  155. * can insert/delete a socket with local_port == num
  156. */
  157. static int udp_lib_lport_inuse2(struct net *net, __u16 num,
  158. struct udp_hslot *hslot2,
  159. struct sock *sk,
  160. int (*saddr_comp)(const struct sock *sk1,
  161. const struct sock *sk2))
  162. {
  163. struct sock *sk2;
  164. struct hlist_nulls_node *node;
  165. kuid_t uid = sock_i_uid(sk);
  166. int res = 0;
  167. spin_lock(&hslot2->lock);
  168. udp_portaddr_for_each_entry(sk2, node, &hslot2->head)
  169. if (net_eq(sock_net(sk2), net) &&
  170. sk2 != sk &&
  171. (udp_sk(sk2)->udp_port_hash == num) &&
  172. (!sk2->sk_reuse || !sk->sk_reuse) &&
  173. (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if ||
  174. sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&
  175. (!sk2->sk_reuseport || !sk->sk_reuseport ||
  176. !uid_eq(uid, sock_i_uid(sk2))) &&
  177. (*saddr_comp)(sk, sk2)) {
  178. res = 1;
  179. break;
  180. }
  181. spin_unlock(&hslot2->lock);
  182. return res;
  183. }
  184. /**
  185. * udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6
  186. *
  187. * @sk: socket struct in question
  188. * @snum: port number to look up
  189. * @saddr_comp: AF-dependent comparison of bound local IP addresses
  190. * @hash2_nulladdr: AF-dependent hash value in secondary hash chains,
  191. * with NULL address
  192. */
  193. int udp_lib_get_port(struct sock *sk, unsigned short snum,
  194. int (*saddr_comp)(const struct sock *sk1,
  195. const struct sock *sk2),
  196. unsigned int hash2_nulladdr)
  197. {
  198. struct udp_hslot *hslot, *hslot2;
  199. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  200. int error = 1;
  201. struct net *net = sock_net(sk);
  202. if (!snum) {
  203. int low, high, remaining;
  204. unsigned int rand;
  205. unsigned short first, last;
  206. DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN);
  207. inet_get_local_port_range(&low, &high);
  208. remaining = (high - low) + 1;
  209. rand = net_random();
  210. first = (((u64)rand * remaining) >> 32) + low;
  211. /*
  212. * force rand to be an odd multiple of UDP_HTABLE_SIZE
  213. */
  214. rand = (rand | 1) * (udptable->mask + 1);
  215. last = first + udptable->mask + 1;
  216. do {
  217. hslot = udp_hashslot(udptable, net, first);
  218. bitmap_zero(bitmap, PORTS_PER_CHAIN);
  219. spin_lock_bh(&hslot->lock);
  220. udp_lib_lport_inuse(net, snum, hslot, bitmap, sk,
  221. saddr_comp, udptable->log);
  222. snum = first;
  223. /*
  224. * Iterate on all possible values of snum for this hash.
  225. * Using steps of an odd multiple of UDP_HTABLE_SIZE
  226. * give us randomization and full range coverage.
  227. */
  228. do {
  229. if (low <= snum && snum <= high &&
  230. !test_bit(snum >> udptable->log, bitmap) &&
  231. !inet_is_reserved_local_port(snum))
  232. goto found;
  233. snum += rand;
  234. } while (snum != first);
  235. spin_unlock_bh(&hslot->lock);
  236. } while (++first != last);
  237. goto fail;
  238. } else {
  239. hslot = udp_hashslot(udptable, net, snum);
  240. spin_lock_bh(&hslot->lock);
  241. if (hslot->count > 10) {
  242. int exist;
  243. unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum;
  244. slot2 &= udptable->mask;
  245. hash2_nulladdr &= udptable->mask;
  246. hslot2 = udp_hashslot2(udptable, slot2);
  247. if (hslot->count < hslot2->count)
  248. goto scan_primary_hash;
  249. exist = udp_lib_lport_inuse2(net, snum, hslot2,
  250. sk, saddr_comp);
  251. if (!exist && (hash2_nulladdr != slot2)) {
  252. hslot2 = udp_hashslot2(udptable, hash2_nulladdr);
  253. exist = udp_lib_lport_inuse2(net, snum, hslot2,
  254. sk, saddr_comp);
  255. }
  256. if (exist)
  257. goto fail_unlock;
  258. else
  259. goto found;
  260. }
  261. scan_primary_hash:
  262. if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk,
  263. saddr_comp, 0))
  264. goto fail_unlock;
  265. }
  266. found:
  267. inet_sk(sk)->inet_num = snum;
  268. udp_sk(sk)->udp_port_hash = snum;
  269. udp_sk(sk)->udp_portaddr_hash ^= snum;
  270. if (sk_unhashed(sk)) {
  271. sk_nulls_add_node_rcu(sk, &hslot->head);
  272. hslot->count++;
  273. sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
  274. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  275. spin_lock(&hslot2->lock);
  276. hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
  277. &hslot2->head);
  278. hslot2->count++;
  279. spin_unlock(&hslot2->lock);
  280. }
  281. error = 0;
  282. fail_unlock:
  283. spin_unlock_bh(&hslot->lock);
  284. fail:
  285. return error;
  286. }
  287. EXPORT_SYMBOL(udp_lib_get_port);
  288. static int ipv4_rcv_saddr_equal(const struct sock *sk1, const struct sock *sk2)
  289. {
  290. struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2);
  291. return (!ipv6_only_sock(sk2) &&
  292. (!inet1->inet_rcv_saddr || !inet2->inet_rcv_saddr ||
  293. inet1->inet_rcv_saddr == inet2->inet_rcv_saddr));
  294. }
  295. static unsigned int udp4_portaddr_hash(struct net *net, __be32 saddr,
  296. unsigned int port)
  297. {
  298. return jhash_1word((__force u32)saddr, net_hash_mix(net)) ^ port;
  299. }
  300. int udp_v4_get_port(struct sock *sk, unsigned short snum)
  301. {
  302. unsigned int hash2_nulladdr =
  303. udp4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum);
  304. unsigned int hash2_partial =
  305. udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0);
  306. /* precompute partial secondary hash */
  307. udp_sk(sk)->udp_portaddr_hash = hash2_partial;
  308. return udp_lib_get_port(sk, snum, ipv4_rcv_saddr_equal, hash2_nulladdr);
  309. }
  310. static inline int compute_score(struct sock *sk, struct net *net, __be32 saddr,
  311. unsigned short hnum,
  312. __be16 sport, __be32 daddr, __be16 dport, int dif)
  313. {
  314. int score = -1;
  315. if (net_eq(sock_net(sk), net) && udp_sk(sk)->udp_port_hash == hnum &&
  316. !ipv6_only_sock(sk)) {
  317. struct inet_sock *inet = inet_sk(sk);
  318. score = (sk->sk_family == PF_INET ? 2 : 1);
  319. if (inet->inet_rcv_saddr) {
  320. if (inet->inet_rcv_saddr != daddr)
  321. return -1;
  322. score += 4;
  323. }
  324. if (inet->inet_daddr) {
  325. if (inet->inet_daddr != saddr)
  326. return -1;
  327. score += 4;
  328. }
  329. if (inet->inet_dport) {
  330. if (inet->inet_dport != sport)
  331. return -1;
  332. score += 4;
  333. }
  334. if (sk->sk_bound_dev_if) {
  335. if (sk->sk_bound_dev_if != dif)
  336. return -1;
  337. score += 4;
  338. }
  339. }
  340. return score;
  341. }
  342. /*
  343. * In this second variant, we check (daddr, dport) matches (inet_rcv_sadd, inet_num)
  344. */
  345. static inline int compute_score2(struct sock *sk, struct net *net,
  346. __be32 saddr, __be16 sport,
  347. __be32 daddr, unsigned int hnum, int dif)
  348. {
  349. int score = -1;
  350. if (net_eq(sock_net(sk), net) && !ipv6_only_sock(sk)) {
  351. struct inet_sock *inet = inet_sk(sk);
  352. if (inet->inet_rcv_saddr != daddr)
  353. return -1;
  354. if (inet->inet_num != hnum)
  355. return -1;
  356. score = (sk->sk_family == PF_INET ? 2 : 1);
  357. if (inet->inet_daddr) {
  358. if (inet->inet_daddr != saddr)
  359. return -1;
  360. score += 4;
  361. }
  362. if (inet->inet_dport) {
  363. if (inet->inet_dport != sport)
  364. return -1;
  365. score += 4;
  366. }
  367. if (sk->sk_bound_dev_if) {
  368. if (sk->sk_bound_dev_if != dif)
  369. return -1;
  370. score += 4;
  371. }
  372. }
  373. return score;
  374. }
  375. /* called with read_rcu_lock() */
  376. static struct sock *udp4_lib_lookup2(struct net *net,
  377. __be32 saddr, __be16 sport,
  378. __be32 daddr, unsigned int hnum, int dif,
  379. struct udp_hslot *hslot2, unsigned int slot2)
  380. {
  381. struct sock *sk, *result;
  382. struct hlist_nulls_node *node;
  383. int score, badness, matches = 0, reuseport = 0;
  384. u32 hash = 0;
  385. begin:
  386. result = NULL;
  387. badness = 0;
  388. udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) {
  389. score = compute_score2(sk, net, saddr, sport,
  390. daddr, hnum, dif);
  391. if (score > badness) {
  392. result = sk;
  393. badness = score;
  394. reuseport = sk->sk_reuseport;
  395. if (reuseport) {
  396. hash = inet_ehashfn(net, daddr, hnum,
  397. saddr, sport);
  398. matches = 1;
  399. }
  400. } else if (score == badness && reuseport) {
  401. matches++;
  402. if (((u64)hash * matches) >> 32 == 0)
  403. result = sk;
  404. hash = next_pseudo_random32(hash);
  405. }
  406. }
  407. /*
  408. * if the nulls value we got at the end of this lookup is
  409. * not the expected one, we must restart lookup.
  410. * We probably met an item that was moved to another chain.
  411. */
  412. if (get_nulls_value(node) != slot2)
  413. goto begin;
  414. if (result) {
  415. if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2)))
  416. result = NULL;
  417. else if (unlikely(compute_score2(result, net, saddr, sport,
  418. daddr, hnum, dif) < badness)) {
  419. sock_put(result);
  420. goto begin;
  421. }
  422. }
  423. return result;
  424. }
  425. /* UDP is nearly always wildcards out the wazoo, it makes no sense to try
  426. * harder than this. -DaveM
  427. */
  428. struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr,
  429. __be16 sport, __be32 daddr, __be16 dport,
  430. int dif, struct udp_table *udptable)
  431. {
  432. struct sock *sk, *result;
  433. struct hlist_nulls_node *node;
  434. unsigned short hnum = ntohs(dport);
  435. unsigned int hash2, slot2, slot = udp_hashfn(net, hnum, udptable->mask);
  436. struct udp_hslot *hslot2, *hslot = &udptable->hash[slot];
  437. int score, badness, matches = 0, reuseport = 0;
  438. u32 hash = 0;
  439. rcu_read_lock();
  440. if (hslot->count > 10) {
  441. hash2 = udp4_portaddr_hash(net, daddr, hnum);
  442. slot2 = hash2 & udptable->mask;
  443. hslot2 = &udptable->hash2[slot2];
  444. if (hslot->count < hslot2->count)
  445. goto begin;
  446. result = udp4_lib_lookup2(net, saddr, sport,
  447. daddr, hnum, dif,
  448. hslot2, slot2);
  449. if (!result) {
  450. hash2 = udp4_portaddr_hash(net, htonl(INADDR_ANY), 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. htonl(INADDR_ANY), hnum, dif,
  457. hslot2, slot2);
  458. }
  459. rcu_read_unlock();
  460. return result;
  461. }
  462. begin:
  463. result = NULL;
  464. badness = 0;
  465. sk_nulls_for_each_rcu(sk, node, &hslot->head) {
  466. score = compute_score(sk, net, saddr, hnum, sport,
  467. daddr, dport, dif);
  468. if (score > badness) {
  469. result = sk;
  470. badness = score;
  471. reuseport = sk->sk_reuseport;
  472. if (reuseport) {
  473. hash = inet_ehashfn(net, daddr, hnum,
  474. saddr, sport);
  475. matches = 1;
  476. }
  477. } else if (score == badness && reuseport) {
  478. matches++;
  479. if (((u64)hash * matches) >> 32 == 0)
  480. result = sk;
  481. hash = next_pseudo_random32(hash);
  482. }
  483. }
  484. /*
  485. * if the nulls value we got at the end of this lookup is
  486. * not the expected one, we must restart lookup.
  487. * We probably met an item that was moved to another chain.
  488. */
  489. if (get_nulls_value(node) != slot)
  490. goto begin;
  491. if (result) {
  492. if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2)))
  493. result = NULL;
  494. else if (unlikely(compute_score(result, net, saddr, hnum, sport,
  495. daddr, dport, dif) < badness)) {
  496. sock_put(result);
  497. goto begin;
  498. }
  499. }
  500. rcu_read_unlock();
  501. return result;
  502. }
  503. EXPORT_SYMBOL_GPL(__udp4_lib_lookup);
  504. static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb,
  505. __be16 sport, __be16 dport,
  506. struct udp_table *udptable)
  507. {
  508. struct sock *sk;
  509. const struct iphdr *iph = ip_hdr(skb);
  510. if (unlikely(sk = skb_steal_sock(skb)))
  511. return sk;
  512. else
  513. return __udp4_lib_lookup(dev_net(skb_dst(skb)->dev), iph->saddr, sport,
  514. iph->daddr, dport, inet_iif(skb),
  515. udptable);
  516. }
  517. struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport,
  518. __be32 daddr, __be16 dport, int dif)
  519. {
  520. return __udp4_lib_lookup(net, saddr, sport, daddr, dport, dif, &udp_table);
  521. }
  522. EXPORT_SYMBOL_GPL(udp4_lib_lookup);
  523. static inline struct sock *udp_v4_mcast_next(struct net *net, struct sock *sk,
  524. __be16 loc_port, __be32 loc_addr,
  525. __be16 rmt_port, __be32 rmt_addr,
  526. int dif)
  527. {
  528. struct hlist_nulls_node *node;
  529. struct sock *s = sk;
  530. unsigned short hnum = ntohs(loc_port);
  531. sk_nulls_for_each_from(s, node) {
  532. struct inet_sock *inet = inet_sk(s);
  533. if (!net_eq(sock_net(s), net) ||
  534. udp_sk(s)->udp_port_hash != hnum ||
  535. (inet->inet_daddr && inet->inet_daddr != rmt_addr) ||
  536. (inet->inet_dport != rmt_port && inet->inet_dport) ||
  537. (inet->inet_rcv_saddr &&
  538. inet->inet_rcv_saddr != loc_addr) ||
  539. ipv6_only_sock(s) ||
  540. (s->sk_bound_dev_if && s->sk_bound_dev_if != dif))
  541. continue;
  542. if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif))
  543. continue;
  544. goto found;
  545. }
  546. s = NULL;
  547. found:
  548. return s;
  549. }
  550. /*
  551. * This routine is called by the ICMP module when it gets some
  552. * sort of error condition. If err < 0 then the socket should
  553. * be closed and the error returned to the user. If err > 0
  554. * it's just the icmp type << 8 | icmp code.
  555. * Header points to the ip header of the error packet. We move
  556. * on past this. Then (as it used to claim before adjustment)
  557. * header points to the first 8 bytes of the udp header. We need
  558. * to find the appropriate port.
  559. */
  560. void __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable)
  561. {
  562. struct inet_sock *inet;
  563. const struct iphdr *iph = (const struct iphdr *)skb->data;
  564. struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2));
  565. const int type = icmp_hdr(skb)->type;
  566. const int code = icmp_hdr(skb)->code;
  567. struct sock *sk;
  568. int harderr;
  569. int err;
  570. struct net *net = dev_net(skb->dev);
  571. sk = __udp4_lib_lookup(net, iph->daddr, uh->dest,
  572. iph->saddr, uh->source, skb->dev->ifindex, udptable);
  573. if (sk == NULL) {
  574. ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS);
  575. return; /* No socket for error */
  576. }
  577. err = 0;
  578. harderr = 0;
  579. inet = inet_sk(sk);
  580. switch (type) {
  581. default:
  582. case ICMP_TIME_EXCEEDED:
  583. err = EHOSTUNREACH;
  584. break;
  585. case ICMP_SOURCE_QUENCH:
  586. goto out;
  587. case ICMP_PARAMETERPROB:
  588. err = EPROTO;
  589. harderr = 1;
  590. break;
  591. case ICMP_DEST_UNREACH:
  592. if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
  593. ipv4_sk_update_pmtu(skb, sk, info);
  594. if (inet->pmtudisc != IP_PMTUDISC_DONT) {
  595. err = EMSGSIZE;
  596. harderr = 1;
  597. break;
  598. }
  599. goto out;
  600. }
  601. err = EHOSTUNREACH;
  602. if (code <= NR_ICMP_UNREACH) {
  603. harderr = icmp_err_convert[code].fatal;
  604. err = icmp_err_convert[code].errno;
  605. }
  606. break;
  607. case ICMP_REDIRECT:
  608. ipv4_sk_redirect(skb, sk);
  609. break;
  610. }
  611. /*
  612. * RFC1122: OK. Passes ICMP errors back to application, as per
  613. * 4.1.3.3.
  614. */
  615. if (!inet->recverr) {
  616. if (!harderr || sk->sk_state != TCP_ESTABLISHED)
  617. goto out;
  618. } else
  619. ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1));
  620. sk->sk_err = err;
  621. sk->sk_error_report(sk);
  622. out:
  623. sock_put(sk);
  624. }
  625. void udp_err(struct sk_buff *skb, u32 info)
  626. {
  627. __udp4_lib_err(skb, info, &udp_table);
  628. }
  629. /*
  630. * Throw away all pending data and cancel the corking. Socket is locked.
  631. */
  632. void udp_flush_pending_frames(struct sock *sk)
  633. {
  634. struct udp_sock *up = udp_sk(sk);
  635. if (up->pending) {
  636. up->len = 0;
  637. up->pending = 0;
  638. ip_flush_pending_frames(sk);
  639. }
  640. }
  641. EXPORT_SYMBOL(udp_flush_pending_frames);
  642. /**
  643. * udp4_hwcsum - handle outgoing HW checksumming
  644. * @skb: sk_buff containing the filled-in UDP header
  645. * (checksum field must be zeroed out)
  646. * @src: source IP address
  647. * @dst: destination IP address
  648. */
  649. void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst)
  650. {
  651. struct udphdr *uh = udp_hdr(skb);
  652. struct sk_buff *frags = skb_shinfo(skb)->frag_list;
  653. int offset = skb_transport_offset(skb);
  654. int len = skb->len - offset;
  655. int hlen = len;
  656. __wsum csum = 0;
  657. if (!frags) {
  658. /*
  659. * Only one fragment on the socket.
  660. */
  661. skb->csum_start = skb_transport_header(skb) - skb->head;
  662. skb->csum_offset = offsetof(struct udphdr, check);
  663. uh->check = ~csum_tcpudp_magic(src, dst, len,
  664. IPPROTO_UDP, 0);
  665. } else {
  666. /*
  667. * HW-checksum won't work as there are two or more
  668. * fragments on the socket so that all csums of sk_buffs
  669. * should be together
  670. */
  671. do {
  672. csum = csum_add(csum, frags->csum);
  673. hlen -= frags->len;
  674. } while ((frags = frags->next));
  675. csum = skb_checksum(skb, offset, hlen, csum);
  676. skb->ip_summed = CHECKSUM_NONE;
  677. uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);
  678. if (uh->check == 0)
  679. uh->check = CSUM_MANGLED_0;
  680. }
  681. }
  682. EXPORT_SYMBOL_GPL(udp4_hwcsum);
  683. static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4)
  684. {
  685. struct sock *sk = skb->sk;
  686. struct inet_sock *inet = inet_sk(sk);
  687. struct udphdr *uh;
  688. int err = 0;
  689. int is_udplite = IS_UDPLITE(sk);
  690. int offset = skb_transport_offset(skb);
  691. int len = skb->len - offset;
  692. __wsum csum = 0;
  693. /*
  694. * Create a UDP header
  695. */
  696. uh = udp_hdr(skb);
  697. uh->source = inet->inet_sport;
  698. uh->dest = fl4->fl4_dport;
  699. uh->len = htons(len);
  700. uh->check = 0;
  701. if (is_udplite) /* UDP-Lite */
  702. csum = udplite_csum(skb);
  703. else if (sk->sk_no_check == UDP_CSUM_NOXMIT) { /* UDP csum disabled */
  704. skb->ip_summed = CHECKSUM_NONE;
  705. goto send;
  706. } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */
  707. udp4_hwcsum(skb, fl4->saddr, fl4->daddr);
  708. goto send;
  709. } else
  710. csum = udp_csum(skb);
  711. /* add protocol-dependent pseudo-header */
  712. uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len,
  713. sk->sk_protocol, csum);
  714. if (uh->check == 0)
  715. uh->check = CSUM_MANGLED_0;
  716. send:
  717. err = ip_send_skb(sock_net(sk), skb);
  718. if (err) {
  719. if (err == -ENOBUFS && !inet->recverr) {
  720. UDP_INC_STATS_USER(sock_net(sk),
  721. UDP_MIB_SNDBUFERRORS, is_udplite);
  722. err = 0;
  723. }
  724. } else
  725. UDP_INC_STATS_USER(sock_net(sk),
  726. UDP_MIB_OUTDATAGRAMS, is_udplite);
  727. return err;
  728. }
  729. /*
  730. * Push out all pending data as one UDP datagram. Socket is locked.
  731. */
  732. int udp_push_pending_frames(struct sock *sk)
  733. {
  734. struct udp_sock *up = udp_sk(sk);
  735. struct inet_sock *inet = inet_sk(sk);
  736. struct flowi4 *fl4 = &inet->cork.fl.u.ip4;
  737. struct sk_buff *skb;
  738. int err = 0;
  739. skb = ip_finish_skb(sk, fl4);
  740. if (!skb)
  741. goto out;
  742. err = udp_send_skb(skb, fl4);
  743. out:
  744. up->len = 0;
  745. up->pending = 0;
  746. return err;
  747. }
  748. EXPORT_SYMBOL(udp_push_pending_frames);
  749. int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
  750. size_t len)
  751. {
  752. struct inet_sock *inet = inet_sk(sk);
  753. struct udp_sock *up = udp_sk(sk);
  754. struct flowi4 fl4_stack;
  755. struct flowi4 *fl4;
  756. int ulen = len;
  757. struct ipcm_cookie ipc;
  758. struct rtable *rt = NULL;
  759. int free = 0;
  760. int connected = 0;
  761. __be32 daddr, faddr, saddr;
  762. __be16 dport;
  763. u8 tos;
  764. int err, is_udplite = IS_UDPLITE(sk);
  765. int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
  766. int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
  767. struct sk_buff *skb;
  768. struct ip_options_data opt_copy;
  769. if (len > 0xFFFF)
  770. return -EMSGSIZE;
  771. /*
  772. * Check the flags.
  773. */
  774. if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
  775. return -EOPNOTSUPP;
  776. ipc.opt = NULL;
  777. ipc.tx_flags = 0;
  778. getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
  779. fl4 = &inet->cork.fl.u.ip4;
  780. if (up->pending) {
  781. /*
  782. * There are pending frames.
  783. * The socket lock must be held while it's corked.
  784. */
  785. lock_sock(sk);
  786. if (likely(up->pending)) {
  787. if (unlikely(up->pending != AF_INET)) {
  788. release_sock(sk);
  789. return -EINVAL;
  790. }
  791. goto do_append_data;
  792. }
  793. release_sock(sk);
  794. }
  795. ulen += sizeof(struct udphdr);
  796. /*
  797. * Get and verify the address.
  798. */
  799. if (msg->msg_name) {
  800. struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name;
  801. if (msg->msg_namelen < sizeof(*usin))
  802. return -EINVAL;
  803. if (usin->sin_family != AF_INET) {
  804. if (usin->sin_family != AF_UNSPEC)
  805. return -EAFNOSUPPORT;
  806. }
  807. daddr = usin->sin_addr.s_addr;
  808. dport = usin->sin_port;
  809. if (dport == 0)
  810. return -EINVAL;
  811. } else {
  812. if (sk->sk_state != TCP_ESTABLISHED)
  813. return -EDESTADDRREQ;
  814. daddr = inet->inet_daddr;
  815. dport = inet->inet_dport;
  816. /* Open fast path for connected socket.
  817. Route will not be used, if at least one option is set.
  818. */
  819. connected = 1;
  820. }
  821. ipc.addr = inet->inet_saddr;
  822. ipc.oif = sk->sk_bound_dev_if;
  823. sock_tx_timestamp(sk, &ipc.tx_flags);
  824. if (msg->msg_controllen) {
  825. err = ip_cmsg_send(sock_net(sk), msg, &ipc);
  826. if (err)
  827. return err;
  828. if (ipc.opt)
  829. free = 1;
  830. connected = 0;
  831. }
  832. if (!ipc.opt) {
  833. struct ip_options_rcu *inet_opt;
  834. rcu_read_lock();
  835. inet_opt = rcu_dereference(inet->inet_opt);
  836. if (inet_opt) {
  837. memcpy(&opt_copy, inet_opt,
  838. sizeof(*inet_opt) + inet_opt->opt.optlen);
  839. ipc.opt = &opt_copy.opt;
  840. }
  841. rcu_read_unlock();
  842. }
  843. saddr = ipc.addr;
  844. ipc.addr = faddr = daddr;
  845. if (ipc.opt && ipc.opt->opt.srr) {
  846. if (!daddr)
  847. return -EINVAL;
  848. faddr = ipc.opt->opt.faddr;
  849. connected = 0;
  850. }
  851. tos = RT_TOS(inet->tos);
  852. if (sock_flag(sk, SOCK_LOCALROUTE) ||
  853. (msg->msg_flags & MSG_DONTROUTE) ||
  854. (ipc.opt && ipc.opt->opt.is_strictroute)) {
  855. tos |= RTO_ONLINK;
  856. connected = 0;
  857. }
  858. if (ipv4_is_multicast(daddr)) {
  859. if (!ipc.oif)
  860. ipc.oif = inet->mc_index;
  861. if (!saddr)
  862. saddr = inet->mc_addr;
  863. connected = 0;
  864. } else if (!ipc.oif)
  865. ipc.oif = inet->uc_index;
  866. if (connected)
  867. rt = (struct rtable *)sk_dst_check(sk, 0);
  868. if (rt == NULL) {
  869. struct net *net = sock_net(sk);
  870. fl4 = &fl4_stack;
  871. flowi4_init_output(fl4, ipc.oif, sk->sk_mark, tos,
  872. RT_SCOPE_UNIVERSE, sk->sk_protocol,
  873. inet_sk_flowi_flags(sk)|FLOWI_FLAG_CAN_SLEEP,
  874. faddr, saddr, dport, inet->inet_sport);
  875. security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
  876. rt = ip_route_output_flow(net, fl4, sk);
  877. if (IS_ERR(rt)) {
  878. err = PTR_ERR(rt);
  879. rt = NULL;
  880. if (err == -ENETUNREACH)
  881. IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
  882. goto out;
  883. }
  884. err = -EACCES;
  885. if ((rt->rt_flags & RTCF_BROADCAST) &&
  886. !sock_flag(sk, SOCK_BROADCAST))
  887. goto out;
  888. if (connected)
  889. sk_dst_set(sk, dst_clone(&rt->dst));
  890. }
  891. if (msg->msg_flags&MSG_CONFIRM)
  892. goto do_confirm;
  893. back_from_confirm:
  894. saddr = fl4->saddr;
  895. if (!ipc.addr)
  896. daddr = ipc.addr = fl4->daddr;
  897. /* Lockless fast path for the non-corking case. */
  898. if (!corkreq) {
  899. skb = ip_make_skb(sk, fl4, getfrag, msg->msg_iov, ulen,
  900. sizeof(struct udphdr), &ipc, &rt,
  901. msg->msg_flags);
  902. err = PTR_ERR(skb);
  903. if (!IS_ERR_OR_NULL(skb))
  904. err = udp_send_skb(skb, fl4);
  905. goto out;
  906. }
  907. lock_sock(sk);
  908. if (unlikely(up->pending)) {
  909. /* The socket is already corked while preparing it. */
  910. /* ... which is an evident application bug. --ANK */
  911. release_sock(sk);
  912. LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("cork app bug 2\n"));
  913. err = -EINVAL;
  914. goto out;
  915. }
  916. /*
  917. * Now cork the socket to pend data.
  918. */
  919. fl4 = &inet->cork.fl.u.ip4;
  920. fl4->daddr = daddr;
  921. fl4->saddr = saddr;
  922. fl4->fl4_dport = dport;
  923. fl4->fl4_sport = inet->inet_sport;
  924. up->pending = AF_INET;
  925. do_append_data:
  926. up->len += ulen;
  927. err = ip_append_data(sk, fl4, getfrag, msg->msg_iov, ulen,
  928. sizeof(struct udphdr), &ipc, &rt,
  929. corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
  930. if (err)
  931. udp_flush_pending_frames(sk);
  932. else if (!corkreq)
  933. err = udp_push_pending_frames(sk);
  934. else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
  935. up->pending = 0;
  936. release_sock(sk);
  937. out:
  938. ip_rt_put(rt);
  939. if (free)
  940. kfree(ipc.opt);
  941. if (!err)
  942. return len;
  943. /*
  944. * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
  945. * ENOBUFS might not be good (it's not tunable per se), but otherwise
  946. * we don't have a good statistic (IpOutDiscards but it can be too many
  947. * things). We could add another new stat but at least for now that
  948. * seems like overkill.
  949. */
  950. if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
  951. UDP_INC_STATS_USER(sock_net(sk),
  952. UDP_MIB_SNDBUFERRORS, is_udplite);
  953. }
  954. return err;
  955. do_confirm:
  956. dst_confirm(&rt->dst);
  957. if (!(msg->msg_flags&MSG_PROBE) || len)
  958. goto back_from_confirm;
  959. err = 0;
  960. goto out;
  961. }
  962. EXPORT_SYMBOL(udp_sendmsg);
  963. int udp_sendpage(struct sock *sk, struct page *page, int offset,
  964. size_t size, int flags)
  965. {
  966. struct inet_sock *inet = inet_sk(sk);
  967. struct udp_sock *up = udp_sk(sk);
  968. int ret;
  969. if (!up->pending) {
  970. struct msghdr msg = { .msg_flags = flags|MSG_MORE };
  971. /* Call udp_sendmsg to specify destination address which
  972. * sendpage interface can't pass.
  973. * This will succeed only when the socket is connected.
  974. */
  975. ret = udp_sendmsg(NULL, sk, &msg, 0);
  976. if (ret < 0)
  977. return ret;
  978. }
  979. lock_sock(sk);
  980. if (unlikely(!up->pending)) {
  981. release_sock(sk);
  982. LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("udp cork app bug 3\n"));
  983. return -EINVAL;
  984. }
  985. ret = ip_append_page(sk, &inet->cork.fl.u.ip4,
  986. page, offset, size, flags);
  987. if (ret == -EOPNOTSUPP) {
  988. release_sock(sk);
  989. return sock_no_sendpage(sk->sk_socket, page, offset,
  990. size, flags);
  991. }
  992. if (ret < 0) {
  993. udp_flush_pending_frames(sk);
  994. goto out;
  995. }
  996. up->len += size;
  997. if (!(up->corkflag || (flags&MSG_MORE)))
  998. ret = udp_push_pending_frames(sk);
  999. if (!ret)
  1000. ret = size;
  1001. out:
  1002. release_sock(sk);
  1003. return ret;
  1004. }
  1005. /**
  1006. * first_packet_length - return length of first packet in receive queue
  1007. * @sk: socket
  1008. *
  1009. * Drops all bad checksum frames, until a valid one is found.
  1010. * Returns the length of found skb, or 0 if none is found.
  1011. */
  1012. static unsigned int first_packet_length(struct sock *sk)
  1013. {
  1014. struct sk_buff_head list_kill, *rcvq = &sk->sk_receive_queue;
  1015. struct sk_buff *skb;
  1016. unsigned int res;
  1017. __skb_queue_head_init(&list_kill);
  1018. spin_lock_bh(&rcvq->lock);
  1019. while ((skb = skb_peek(rcvq)) != NULL &&
  1020. udp_lib_checksum_complete(skb)) {
  1021. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS,
  1022. IS_UDPLITE(sk));
  1023. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS,
  1024. IS_UDPLITE(sk));
  1025. atomic_inc(&sk->sk_drops);
  1026. __skb_unlink(skb, rcvq);
  1027. __skb_queue_tail(&list_kill, skb);
  1028. }
  1029. res = skb ? skb->len : 0;
  1030. spin_unlock_bh(&rcvq->lock);
  1031. if (!skb_queue_empty(&list_kill)) {
  1032. bool slow = lock_sock_fast(sk);
  1033. __skb_queue_purge(&list_kill);
  1034. sk_mem_reclaim_partial(sk);
  1035. unlock_sock_fast(sk, slow);
  1036. }
  1037. return res;
  1038. }
  1039. /*
  1040. * IOCTL requests applicable to the UDP protocol
  1041. */
  1042. int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  1043. {
  1044. switch (cmd) {
  1045. case SIOCOUTQ:
  1046. {
  1047. int amount = sk_wmem_alloc_get(sk);
  1048. return put_user(amount, (int __user *)arg);
  1049. }
  1050. case SIOCINQ:
  1051. {
  1052. unsigned int amount = first_packet_length(sk);
  1053. if (amount)
  1054. /*
  1055. * We will only return the amount
  1056. * of this packet since that is all
  1057. * that will be read.
  1058. */
  1059. amount -= sizeof(struct udphdr);
  1060. return put_user(amount, (int __user *)arg);
  1061. }
  1062. default:
  1063. return -ENOIOCTLCMD;
  1064. }
  1065. return 0;
  1066. }
  1067. EXPORT_SYMBOL(udp_ioctl);
  1068. /*
  1069. * This should be easy, if there is something there we
  1070. * return it, otherwise we block.
  1071. */
  1072. int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
  1073. size_t len, int noblock, int flags, int *addr_len)
  1074. {
  1075. struct inet_sock *inet = inet_sk(sk);
  1076. struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
  1077. struct sk_buff *skb;
  1078. unsigned int ulen, copied;
  1079. int peeked, off = 0;
  1080. int err;
  1081. int is_udplite = IS_UDPLITE(sk);
  1082. bool slow;
  1083. /*
  1084. * Check any passed addresses
  1085. */
  1086. if (addr_len)
  1087. *addr_len = sizeof(*sin);
  1088. if (flags & MSG_ERRQUEUE)
  1089. return ip_recv_error(sk, msg, len);
  1090. try_again:
  1091. skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
  1092. &peeked, &off, &err);
  1093. if (!skb)
  1094. goto out;
  1095. ulen = skb->len - sizeof(struct udphdr);
  1096. copied = len;
  1097. if (copied > ulen)
  1098. copied = ulen;
  1099. else if (copied < ulen)
  1100. msg->msg_flags |= MSG_TRUNC;
  1101. /*
  1102. * If checksum is needed at all, try to do it while copying the
  1103. * data. If the data is truncated, or if we only want a partial
  1104. * coverage checksum (UDP-Lite), do it before the copy.
  1105. */
  1106. if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
  1107. if (udp_lib_checksum_complete(skb))
  1108. goto csum_copy_err;
  1109. }
  1110. if (skb_csum_unnecessary(skb))
  1111. err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
  1112. msg->msg_iov, copied);
  1113. else {
  1114. err = skb_copy_and_csum_datagram_iovec(skb,
  1115. sizeof(struct udphdr),
  1116. msg->msg_iov);
  1117. if (err == -EINVAL)
  1118. goto csum_copy_err;
  1119. }
  1120. if (unlikely(err)) {
  1121. trace_kfree_skb(skb, udp_recvmsg);
  1122. if (!peeked) {
  1123. atomic_inc(&sk->sk_drops);
  1124. UDP_INC_STATS_USER(sock_net(sk),
  1125. UDP_MIB_INERRORS, is_udplite);
  1126. }
  1127. goto out_free;
  1128. }
  1129. if (!peeked)
  1130. UDP_INC_STATS_USER(sock_net(sk),
  1131. UDP_MIB_INDATAGRAMS, is_udplite);
  1132. sock_recv_ts_and_drops(msg, sk, skb);
  1133. /* Copy the address. */
  1134. if (sin) {
  1135. sin->sin_family = AF_INET;
  1136. sin->sin_port = udp_hdr(skb)->source;
  1137. sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
  1138. memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
  1139. }
  1140. if (inet->cmsg_flags)
  1141. ip_cmsg_recv(msg, skb);
  1142. err = copied;
  1143. if (flags & MSG_TRUNC)
  1144. err = ulen;
  1145. out_free:
  1146. skb_free_datagram_locked(sk, skb);
  1147. out:
  1148. return err;
  1149. csum_copy_err:
  1150. slow = lock_sock_fast(sk);
  1151. if (!skb_kill_datagram(sk, skb, flags)) {
  1152. UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
  1153. UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1154. }
  1155. unlock_sock_fast(sk, slow);
  1156. if (noblock)
  1157. return -EAGAIN;
  1158. /* starting over for a new packet */
  1159. msg->msg_flags &= ~MSG_TRUNC;
  1160. goto try_again;
  1161. }
  1162. int udp_disconnect(struct sock *sk, int flags)
  1163. {
  1164. struct inet_sock *inet = inet_sk(sk);
  1165. /*
  1166. * 1003.1g - break association.
  1167. */
  1168. sk->sk_state = TCP_CLOSE;
  1169. inet->inet_daddr = 0;
  1170. inet->inet_dport = 0;
  1171. sock_rps_reset_rxhash(sk);
  1172. sk->sk_bound_dev_if = 0;
  1173. if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
  1174. inet_reset_saddr(sk);
  1175. if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
  1176. sk->sk_prot->unhash(sk);
  1177. inet->inet_sport = 0;
  1178. }
  1179. sk_dst_reset(sk);
  1180. return 0;
  1181. }
  1182. EXPORT_SYMBOL(udp_disconnect);
  1183. void udp_lib_unhash(struct sock *sk)
  1184. {
  1185. if (sk_hashed(sk)) {
  1186. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  1187. struct udp_hslot *hslot, *hslot2;
  1188. hslot = udp_hashslot(udptable, sock_net(sk),
  1189. udp_sk(sk)->udp_port_hash);
  1190. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  1191. spin_lock_bh(&hslot->lock);
  1192. if (sk_nulls_del_node_init_rcu(sk)) {
  1193. hslot->count--;
  1194. inet_sk(sk)->inet_num = 0;
  1195. sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
  1196. spin_lock(&hslot2->lock);
  1197. hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
  1198. hslot2->count--;
  1199. spin_unlock(&hslot2->lock);
  1200. }
  1201. spin_unlock_bh(&hslot->lock);
  1202. }
  1203. }
  1204. EXPORT_SYMBOL(udp_lib_unhash);
  1205. /*
  1206. * inet_rcv_saddr was changed, we must rehash secondary hash
  1207. */
  1208. void udp_lib_rehash(struct sock *sk, u16 newhash)
  1209. {
  1210. if (sk_hashed(sk)) {
  1211. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  1212. struct udp_hslot *hslot, *hslot2, *nhslot2;
  1213. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  1214. nhslot2 = udp_hashslot2(udptable, newhash);
  1215. udp_sk(sk)->udp_portaddr_hash = newhash;
  1216. if (hslot2 != nhslot2) {
  1217. hslot = udp_hashslot(udptable, sock_net(sk),
  1218. udp_sk(sk)->udp_port_hash);
  1219. /* we must lock primary chain too */
  1220. spin_lock_bh(&hslot->lock);
  1221. spin_lock(&hslot2->lock);
  1222. hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
  1223. hslot2->count--;
  1224. spin_unlock(&hslot2->lock);
  1225. spin_lock(&nhslot2->lock);
  1226. hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
  1227. &nhslot2->head);
  1228. nhslot2->count++;
  1229. spin_unlock(&nhslot2->lock);
  1230. spin_unlock_bh(&hslot->lock);
  1231. }
  1232. }
  1233. }
  1234. EXPORT_SYMBOL(udp_lib_rehash);
  1235. static void udp_v4_rehash(struct sock *sk)
  1236. {
  1237. u16 new_hash = udp4_portaddr_hash(sock_net(sk),
  1238. inet_sk(sk)->inet_rcv_saddr,
  1239. inet_sk(sk)->inet_num);
  1240. udp_lib_rehash(sk, new_hash);
  1241. }
  1242. static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  1243. {
  1244. int rc;
  1245. if (inet_sk(sk)->inet_daddr)
  1246. sock_rps_save_rxhash(sk, skb);
  1247. rc = sock_queue_rcv_skb(sk, skb);
  1248. if (rc < 0) {
  1249. int is_udplite = IS_UDPLITE(sk);
  1250. /* Note that an ENOMEM error is charged twice */
  1251. if (rc == -ENOMEM)
  1252. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS,
  1253. is_udplite);
  1254. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1255. kfree_skb(skb);
  1256. trace_udp_fail_queue_rcv_skb(rc, sk);
  1257. return -1;
  1258. }
  1259. return 0;
  1260. }
  1261. static struct static_key udp_encap_needed __read_mostly;
  1262. void udp_encap_enable(void)
  1263. {
  1264. if (!static_key_enabled(&udp_encap_needed))
  1265. static_key_slow_inc(&udp_encap_needed);
  1266. }
  1267. EXPORT_SYMBOL(udp_encap_enable);
  1268. /* returns:
  1269. * -1: error
  1270. * 0: success
  1271. * >0: "udp encap" protocol resubmission
  1272. *
  1273. * Note that in the success and error cases, the skb is assumed to
  1274. * have either been requeued or freed.
  1275. */
  1276. int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  1277. {
  1278. struct udp_sock *up = udp_sk(sk);
  1279. int rc;
  1280. int is_udplite = IS_UDPLITE(sk);
  1281. /*
  1282. * Charge it to the socket, dropping if the queue is full.
  1283. */
  1284. if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
  1285. goto drop;
  1286. nf_reset(skb);
  1287. if (static_key_false(&udp_encap_needed) && up->encap_type) {
  1288. int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
  1289. /*
  1290. * This is an encapsulation socket so pass the skb to
  1291. * the socket's udp_encap_rcv() hook. Otherwise, just
  1292. * fall through and pass this up the UDP socket.
  1293. * up->encap_rcv() returns the following value:
  1294. * =0 if skb was successfully passed to the encap
  1295. * handler or was discarded by it.
  1296. * >0 if skb should be passed on to UDP.
  1297. * <0 if skb should be resubmitted as proto -N
  1298. */
  1299. /* if we're overly short, let UDP handle it */
  1300. encap_rcv = ACCESS_ONCE(up->encap_rcv);
  1301. if (skb->len > sizeof(struct udphdr) && encap_rcv != NULL) {
  1302. int ret;
  1303. ret = encap_rcv(sk, skb);
  1304. if (ret <= 0) {
  1305. UDP_INC_STATS_BH(sock_net(sk),
  1306. UDP_MIB_INDATAGRAMS,
  1307. is_udplite);
  1308. return -ret;
  1309. }
  1310. }
  1311. /* FALLTHROUGH -- it's a UDP Packet */
  1312. }
  1313. /*
  1314. * UDP-Lite specific tests, ignored on UDP sockets
  1315. */
  1316. if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) {
  1317. /*
  1318. * MIB statistics other than incrementing the error count are
  1319. * disabled for the following two types of errors: these depend
  1320. * on the application settings, not on the functioning of the
  1321. * protocol stack as such.
  1322. *
  1323. * RFC 3828 here recommends (sec 3.3): "There should also be a
  1324. * way ... to ... at least let the receiving application block
  1325. * delivery of packets with coverage values less than a value
  1326. * provided by the application."
  1327. */
  1328. if (up->pcrlen == 0) { /* full coverage was set */
  1329. LIMIT_NETDEBUG(KERN_WARNING "UDPLite: partial coverage %d while full coverage %d requested\n",
  1330. UDP_SKB_CB(skb)->cscov, skb->len);
  1331. goto drop;
  1332. }
  1333. /* The next case involves violating the min. coverage requested
  1334. * by the receiver. This is subtle: if receiver wants x and x is
  1335. * greater than the buffersize/MTU then receiver will complain
  1336. * that it wants x while sender emits packets of smaller size y.
  1337. * Therefore the above ...()->partial_cov statement is essential.
  1338. */
  1339. if (UDP_SKB_CB(skb)->cscov < up->pcrlen) {
  1340. LIMIT_NETDEBUG(KERN_WARNING "UDPLite: coverage %d too small, need min %d\n",
  1341. UDP_SKB_CB(skb)->cscov, up->pcrlen);
  1342. goto drop;
  1343. }
  1344. }
  1345. if (rcu_access_pointer(sk->sk_filter) &&
  1346. udp_lib_checksum_complete(skb))
  1347. goto csum_error;
  1348. if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf))
  1349. goto drop;
  1350. rc = 0;
  1351. ipv4_pktinfo_prepare(skb);
  1352. bh_lock_sock(sk);
  1353. if (!sock_owned_by_user(sk))
  1354. rc = __udp_queue_rcv_skb(sk, skb);
  1355. else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) {
  1356. bh_unlock_sock(sk);
  1357. goto drop;
  1358. }
  1359. bh_unlock_sock(sk);
  1360. return rc;
  1361. csum_error:
  1362. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
  1363. drop:
  1364. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1365. atomic_inc(&sk->sk_drops);
  1366. kfree_skb(skb);
  1367. return -1;
  1368. }
  1369. static void flush_stack(struct sock **stack, unsigned int count,
  1370. struct sk_buff *skb, unsigned int final)
  1371. {
  1372. unsigned int i;
  1373. struct sk_buff *skb1 = NULL;
  1374. struct sock *sk;
  1375. for (i = 0; i < count; i++) {
  1376. sk = stack[i];
  1377. if (likely(skb1 == NULL))
  1378. skb1 = (i == final) ? skb : skb_clone(skb, GFP_ATOMIC);
  1379. if (!skb1) {
  1380. atomic_inc(&sk->sk_drops);
  1381. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS,
  1382. IS_UDPLITE(sk));
  1383. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS,
  1384. IS_UDPLITE(sk));
  1385. }
  1386. if (skb1 && udp_queue_rcv_skb(sk, skb1) <= 0)
  1387. skb1 = NULL;
  1388. }
  1389. if (unlikely(skb1))
  1390. kfree_skb(skb1);
  1391. }
  1392. /*
  1393. * Multicasts and broadcasts go to each listener.
  1394. *
  1395. * Note: called only from the BH handler context.
  1396. */
  1397. static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
  1398. struct udphdr *uh,
  1399. __be32 saddr, __be32 daddr,
  1400. struct udp_table *udptable)
  1401. {
  1402. struct sock *sk, *stack[256 / sizeof(struct sock *)];
  1403. struct udp_hslot *hslot = udp_hashslot(udptable, net, ntohs(uh->dest));
  1404. int dif;
  1405. unsigned int i, count = 0;
  1406. spin_lock(&hslot->lock);
  1407. sk = sk_nulls_head(&hslot->head);
  1408. dif = skb->dev->ifindex;
  1409. sk = udp_v4_mcast_next(net, sk, uh->dest, daddr, uh->source, saddr, dif);
  1410. while (sk) {
  1411. stack[count++] = sk;
  1412. sk = udp_v4_mcast_next(net, sk_nulls_next(sk), uh->dest,
  1413. daddr, uh->source, saddr, dif);
  1414. if (unlikely(count == ARRAY_SIZE(stack))) {
  1415. if (!sk)
  1416. break;
  1417. flush_stack(stack, count, skb, ~0);
  1418. count = 0;
  1419. }
  1420. }
  1421. /*
  1422. * before releasing chain lock, we must take a reference on sockets
  1423. */
  1424. for (i = 0; i < count; i++)
  1425. sock_hold(stack[i]);
  1426. spin_unlock(&hslot->lock);
  1427. /*
  1428. * do the slow work with no lock held
  1429. */
  1430. if (count) {
  1431. flush_stack(stack, count, skb, count - 1);
  1432. for (i = 0; i < count; i++)
  1433. sock_put(stack[i]);
  1434. } else {
  1435. kfree_skb(skb);
  1436. }
  1437. return 0;
  1438. }
  1439. /* Initialize UDP checksum. If exited with zero value (success),
  1440. * CHECKSUM_UNNECESSARY means, that no more checks are required.
  1441. * Otherwise, csum completion requires chacksumming packet body,
  1442. * including udp header and folding it to skb->csum.
  1443. */
  1444. static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
  1445. int proto)
  1446. {
  1447. const struct iphdr *iph;
  1448. int err;
  1449. UDP_SKB_CB(skb)->partial_cov = 0;
  1450. UDP_SKB_CB(skb)->cscov = skb->len;
  1451. if (proto == IPPROTO_UDPLITE) {
  1452. err = udplite_checksum_init(skb, uh);
  1453. if (err)
  1454. return err;
  1455. }
  1456. iph = ip_hdr(skb);
  1457. if (uh->check == 0) {
  1458. skb->ip_summed = CHECKSUM_UNNECESSARY;
  1459. } else if (skb->ip_summed == CHECKSUM_COMPLETE) {
  1460. if (!csum_tcpudp_magic(iph->saddr, iph->daddr, skb->len,
  1461. proto, skb->csum))
  1462. skb->ip_summed = CHECKSUM_UNNECESSARY;
  1463. }
  1464. if (!skb_csum_unnecessary(skb))
  1465. skb->csum = csum_tcpudp_nofold(iph->saddr, iph->daddr,
  1466. skb->len, proto, 0);
  1467. /* Probably, we should checksum udp header (it should be in cache
  1468. * in any case) and data in tiny packets (< rx copybreak).
  1469. */
  1470. return 0;
  1471. }
  1472. /*
  1473. * All we need to do is get the socket, and then do a checksum.
  1474. */
  1475. int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
  1476. int proto)
  1477. {
  1478. struct sock *sk;
  1479. struct udphdr *uh;
  1480. unsigned short ulen;
  1481. struct rtable *rt = skb_rtable(skb);
  1482. __be32 saddr, daddr;
  1483. struct net *net = dev_net(skb->dev);
  1484. /*
  1485. * Validate the packet.
  1486. */
  1487. if (!pskb_may_pull(skb, sizeof(struct udphdr)))
  1488. goto drop; /* No space for header. */
  1489. uh = udp_hdr(skb);
  1490. ulen = ntohs(uh->len);
  1491. saddr = ip_hdr(skb)->saddr;
  1492. daddr = ip_hdr(skb)->daddr;
  1493. if (ulen > skb->len)
  1494. goto short_packet;
  1495. if (proto == IPPROTO_UDP) {
  1496. /* UDP validates ulen. */
  1497. if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
  1498. goto short_packet;
  1499. uh = udp_hdr(skb);
  1500. }
  1501. if (udp4_csum_init(skb, uh, proto))
  1502. goto csum_error;
  1503. if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
  1504. return __udp4_lib_mcast_deliver(net, skb, uh,
  1505. saddr, daddr, udptable);
  1506. sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
  1507. if (sk != NULL) {
  1508. int ret;
  1509. sk_mark_napi_id(sk, skb);
  1510. ret = udp_queue_rcv_skb(sk, skb);
  1511. sock_put(sk);
  1512. /* a return value > 0 means to resubmit the input, but
  1513. * it wants the return to be -protocol, or 0
  1514. */
  1515. if (ret > 0)
  1516. return -ret;
  1517. return 0;
  1518. }
  1519. if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
  1520. goto drop;
  1521. nf_reset(skb);
  1522. /* No socket. Drop packet silently, if checksum is wrong */
  1523. if (udp_lib_checksum_complete(skb))
  1524. goto csum_error;
  1525. UDP_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
  1526. icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
  1527. /*
  1528. * Hmm. We got an UDP packet to a port to which we
  1529. * don't wanna listen. Ignore it.
  1530. */
  1531. kfree_skb(skb);
  1532. return 0;
  1533. short_packet:
  1534. LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
  1535. proto == IPPROTO_UDPLITE ? "Lite" : "",
  1536. &saddr, ntohs(uh->source),
  1537. ulen, skb->len,
  1538. &daddr, ntohs(uh->dest));
  1539. goto drop;
  1540. csum_error:
  1541. /*
  1542. * RFC1122: OK. Discards the bad packet silently (as far as
  1543. * the network is concerned, anyway) as per 4.1.3.4 (MUST).
  1544. */
  1545. LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
  1546. proto == IPPROTO_UDPLITE ? "Lite" : "",
  1547. &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
  1548. ulen);
  1549. UDP_INC_STATS_BH(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
  1550. drop:
  1551. UDP_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
  1552. kfree_skb(skb);
  1553. return 0;
  1554. }
  1555. int udp_rcv(struct sk_buff *skb)
  1556. {
  1557. return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
  1558. }
  1559. void udp_destroy_sock(struct sock *sk)
  1560. {
  1561. struct udp_sock *up = udp_sk(sk);
  1562. bool slow = lock_sock_fast(sk);
  1563. udp_flush_pending_frames(sk);
  1564. unlock_sock_fast(sk, slow);
  1565. if (static_key_false(&udp_encap_needed) && up->encap_type) {
  1566. void (*encap_destroy)(struct sock *sk);
  1567. encap_destroy = ACCESS_ONCE(up->encap_destroy);
  1568. if (encap_destroy)
  1569. encap_destroy(sk);
  1570. }
  1571. }
  1572. /*
  1573. * Socket option code for UDP
  1574. */
  1575. int udp_lib_setsockopt(struct sock *sk, int level, int optname,
  1576. char __user *optval, unsigned int optlen,
  1577. int (*push_pending_frames)(struct sock *))
  1578. {
  1579. struct udp_sock *up = udp_sk(sk);
  1580. int val;
  1581. int err = 0;
  1582. int is_udplite = IS_UDPLITE(sk);
  1583. if (optlen < sizeof(int))
  1584. return -EINVAL;
  1585. if (get_user(val, (int __user *)optval))
  1586. return -EFAULT;
  1587. switch (optname) {
  1588. case UDP_CORK:
  1589. if (val != 0) {
  1590. up->corkflag = 1;
  1591. } else {
  1592. up->corkflag = 0;
  1593. lock_sock(sk);
  1594. (*push_pending_frames)(sk);
  1595. release_sock(sk);
  1596. }
  1597. break;
  1598. case UDP_ENCAP:
  1599. switch (val) {
  1600. case 0:
  1601. case UDP_ENCAP_ESPINUDP:
  1602. case UDP_ENCAP_ESPINUDP_NON_IKE:
  1603. up->encap_rcv = xfrm4_udp_encap_rcv;
  1604. /* FALLTHROUGH */
  1605. case UDP_ENCAP_L2TPINUDP:
  1606. up->encap_type = val;
  1607. udp_encap_enable();
  1608. break;
  1609. default:
  1610. err = -ENOPROTOOPT;
  1611. break;
  1612. }
  1613. break;
  1614. /*
  1615. * UDP-Lite's partial checksum coverage (RFC 3828).
  1616. */
  1617. /* The sender sets actual checksum coverage length via this option.
  1618. * The case coverage > packet length is handled by send module. */
  1619. case UDPLITE_SEND_CSCOV:
  1620. if (!is_udplite) /* Disable the option on UDP sockets */
  1621. return -ENOPROTOOPT;
  1622. if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
  1623. val = 8;
  1624. else if (val > USHRT_MAX)
  1625. val = USHRT_MAX;
  1626. up->pcslen = val;
  1627. up->pcflag |= UDPLITE_SEND_CC;
  1628. break;
  1629. /* The receiver specifies a minimum checksum coverage value. To make
  1630. * sense, this should be set to at least 8 (as done below). If zero is
  1631. * used, this again means full checksum coverage. */
  1632. case UDPLITE_RECV_CSCOV:
  1633. if (!is_udplite) /* Disable the option on UDP sockets */
  1634. return -ENOPROTOOPT;
  1635. if (val != 0 && val < 8) /* Avoid silly minimal values. */
  1636. val = 8;
  1637. else if (val > USHRT_MAX)
  1638. val = USHRT_MAX;
  1639. up->pcrlen = val;
  1640. up->pcflag |= UDPLITE_RECV_CC;
  1641. break;
  1642. default:
  1643. err = -ENOPROTOOPT;
  1644. break;
  1645. }
  1646. return err;
  1647. }
  1648. EXPORT_SYMBOL(udp_lib_setsockopt);
  1649. int udp_setsockopt(struct sock *sk, int level, int optname,
  1650. char __user *optval, unsigned int optlen)
  1651. {
  1652. if (level == SOL_UDP || level == SOL_UDPLITE)
  1653. return udp_lib_setsockopt(sk, level, optname, optval, optlen,
  1654. udp_push_pending_frames);
  1655. return ip_setsockopt(sk, level, optname, optval, optlen);
  1656. }
  1657. #ifdef CONFIG_COMPAT
  1658. int compat_udp_setsockopt(struct sock *sk, int level, int optname,
  1659. char __user *optval, unsigned int optlen)
  1660. {
  1661. if (level == SOL_UDP || level == SOL_UDPLITE)
  1662. return udp_lib_setsockopt(sk, level, optname, optval, optlen,
  1663. udp_push_pending_frames);
  1664. return compat_ip_setsockopt(sk, level, optname, optval, optlen);
  1665. }
  1666. #endif
  1667. int udp_lib_getsockopt(struct sock *sk, int level, int optname,
  1668. char __user *optval, int __user *optlen)
  1669. {
  1670. struct udp_sock *up = udp_sk(sk);
  1671. int val, len;
  1672. if (get_user(len, optlen))
  1673. return -EFAULT;
  1674. len = min_t(unsigned int, len, sizeof(int));
  1675. if (len < 0)
  1676. return -EINVAL;
  1677. switch (optname) {
  1678. case UDP_CORK:
  1679. val = up->corkflag;
  1680. break;
  1681. case UDP_ENCAP:
  1682. val = up->encap_type;
  1683. break;
  1684. /* The following two cannot be changed on UDP sockets, the return is
  1685. * always 0 (which corresponds to the full checksum coverage of UDP). */
  1686. case UDPLITE_SEND_CSCOV:
  1687. val = up->pcslen;
  1688. break;
  1689. case UDPLITE_RECV_CSCOV:
  1690. val = up->pcrlen;
  1691. break;
  1692. default:
  1693. return -ENOPROTOOPT;
  1694. }
  1695. if (put_user(len, optlen))
  1696. return -EFAULT;
  1697. if (copy_to_user(optval, &val, len))
  1698. return -EFAULT;
  1699. return 0;
  1700. }
  1701. EXPORT_SYMBOL(udp_lib_getsockopt);
  1702. int udp_getsockopt(struct sock *sk, int level, int optname,
  1703. char __user *optval, int __user *optlen)
  1704. {
  1705. if (level == SOL_UDP || level == SOL_UDPLITE)
  1706. return udp_lib_getsockopt(sk, level, optname, optval, optlen);
  1707. return ip_getsockopt(sk, level, optname, optval, optlen);
  1708. }
  1709. #ifdef CONFIG_COMPAT
  1710. int compat_udp_getsockopt(struct sock *sk, int level, int optname,
  1711. char __user *optval, int __user *optlen)
  1712. {
  1713. if (level == SOL_UDP || level == SOL_UDPLITE)
  1714. return udp_lib_getsockopt(sk, level, optname, optval, optlen);
  1715. return compat_ip_getsockopt(sk, level, optname, optval, optlen);
  1716. }
  1717. #endif
  1718. /**
  1719. * udp_poll - wait for a UDP event.
  1720. * @file - file struct
  1721. * @sock - socket
  1722. * @wait - poll table
  1723. *
  1724. * This is same as datagram poll, except for the special case of
  1725. * blocking sockets. If application is using a blocking fd
  1726. * and a packet with checksum error is in the queue;
  1727. * then it could get return from select indicating data available
  1728. * but then block when reading it. Add special case code
  1729. * to work around these arguably broken applications.
  1730. */
  1731. unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
  1732. {
  1733. unsigned int mask = datagram_poll(file, sock, wait);
  1734. struct sock *sk = sock->sk;
  1735. sock_rps_record_flow(sk);
  1736. /* Check for false positives due to checksum errors */
  1737. if ((mask & POLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
  1738. !(sk->sk_shutdown & RCV_SHUTDOWN) && !first_packet_length(sk))
  1739. mask &= ~(POLLIN | POLLRDNORM);
  1740. return mask;
  1741. }
  1742. EXPORT_SYMBOL(udp_poll);
  1743. struct proto udp_prot = {
  1744. .name = "UDP",
  1745. .owner = THIS_MODULE,
  1746. .close = udp_lib_close,
  1747. .connect = ip4_datagram_connect,
  1748. .disconnect = udp_disconnect,
  1749. .ioctl = udp_ioctl,
  1750. .destroy = udp_destroy_sock,
  1751. .setsockopt = udp_setsockopt,
  1752. .getsockopt = udp_getsockopt,
  1753. .sendmsg = udp_sendmsg,
  1754. .recvmsg = udp_recvmsg,
  1755. .sendpage = udp_sendpage,
  1756. .backlog_rcv = __udp_queue_rcv_skb,
  1757. .release_cb = ip4_datagram_release_cb,
  1758. .hash = udp_lib_hash,
  1759. .unhash = udp_lib_unhash,
  1760. .rehash = udp_v4_rehash,
  1761. .get_port = udp_v4_get_port,
  1762. .memory_allocated = &udp_memory_allocated,
  1763. .sysctl_mem = sysctl_udp_mem,
  1764. .sysctl_wmem = &sysctl_udp_wmem_min,
  1765. .sysctl_rmem = &sysctl_udp_rmem_min,
  1766. .obj_size = sizeof(struct udp_sock),
  1767. .slab_flags = SLAB_DESTROY_BY_RCU,
  1768. .h.udp_table = &udp_table,
  1769. #ifdef CONFIG_COMPAT
  1770. .compat_setsockopt = compat_udp_setsockopt,
  1771. .compat_getsockopt = compat_udp_getsockopt,
  1772. #endif
  1773. .clear_sk = sk_prot_clear_portaddr_nulls,
  1774. };
  1775. EXPORT_SYMBOL(udp_prot);
  1776. /* ------------------------------------------------------------------------ */
  1777. #ifdef CONFIG_PROC_FS
  1778. static struct sock *udp_get_first(struct seq_file *seq, int start)
  1779. {
  1780. struct sock *sk;
  1781. struct udp_iter_state *state = seq->private;
  1782. struct net *net = seq_file_net(seq);
  1783. for (state->bucket = start; state->bucket <= state->udp_table->mask;
  1784. ++state->bucket) {
  1785. struct hlist_nulls_node *node;
  1786. struct udp_hslot *hslot = &state->udp_table->hash[state->bucket];
  1787. if (hlist_nulls_empty(&hslot->head))
  1788. continue;
  1789. spin_lock_bh(&hslot->lock);
  1790. sk_nulls_for_each(sk, node, &hslot->head) {
  1791. if (!net_eq(sock_net(sk), net))
  1792. continue;
  1793. if (sk->sk_family == state->family)
  1794. goto found;
  1795. }
  1796. spin_unlock_bh(&hslot->lock);
  1797. }
  1798. sk = NULL;
  1799. found:
  1800. return sk;
  1801. }
  1802. static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
  1803. {
  1804. struct udp_iter_state *state = seq->private;
  1805. struct net *net = seq_file_net(seq);
  1806. do {
  1807. sk = sk_nulls_next(sk);
  1808. } while (sk && (!net_eq(sock_net(sk), net) || sk->sk_family != state->family));
  1809. if (!sk) {
  1810. if (state->bucket <= state->udp_table->mask)
  1811. spin_unlock_bh(&state->udp_table->hash[state->bucket].lock);
  1812. return udp_get_first(seq, state->bucket + 1);
  1813. }
  1814. return sk;
  1815. }
  1816. static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
  1817. {
  1818. struct sock *sk = udp_get_first(seq, 0);
  1819. if (sk)
  1820. while (pos && (sk = udp_get_next(seq, sk)) != NULL)
  1821. --pos;
  1822. return pos ? NULL : sk;
  1823. }
  1824. static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
  1825. {
  1826. struct udp_iter_state *state = seq->private;
  1827. state->bucket = MAX_UDP_PORTS;
  1828. return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
  1829. }
  1830. static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  1831. {
  1832. struct sock *sk;
  1833. if (v == SEQ_START_TOKEN)
  1834. sk = udp_get_idx(seq, 0);
  1835. else
  1836. sk = udp_get_next(seq, v);
  1837. ++*pos;
  1838. return sk;
  1839. }
  1840. static void udp_seq_stop(struct seq_file *seq, void *v)
  1841. {
  1842. struct udp_iter_state *state = seq->private;
  1843. if (state->bucket <= state->udp_table->mask)
  1844. spin_unlock_bh(&state->udp_table->hash[state->bucket].lock);
  1845. }
  1846. int udp_seq_open(struct inode *inode, struct file *file)
  1847. {
  1848. struct udp_seq_afinfo *afinfo = PDE_DATA(inode);
  1849. struct udp_iter_state *s;
  1850. int err;
  1851. err = seq_open_net(inode, file, &afinfo->seq_ops,
  1852. sizeof(struct udp_iter_state));
  1853. if (err < 0)
  1854. return err;
  1855. s = ((struct seq_file *)file->private_data)->private;
  1856. s->family = afinfo->family;
  1857. s->udp_table = afinfo->udp_table;
  1858. return err;
  1859. }
  1860. EXPORT_SYMBOL(udp_seq_open);
  1861. /* ------------------------------------------------------------------------ */
  1862. int udp_proc_register(struct net *net, struct udp_seq_afinfo *afinfo)
  1863. {
  1864. struct proc_dir_entry *p;
  1865. int rc = 0;
  1866. afinfo->seq_ops.start = udp_seq_start;
  1867. afinfo->seq_ops.next = udp_seq_next;
  1868. afinfo->seq_ops.stop = udp_seq_stop;
  1869. p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net,
  1870. afinfo->seq_fops, afinfo);
  1871. if (!p)
  1872. rc = -ENOMEM;
  1873. return rc;
  1874. }
  1875. EXPORT_SYMBOL(udp_proc_register);
  1876. void udp_proc_unregister(struct net *net, struct udp_seq_afinfo *afinfo)
  1877. {
  1878. remove_proc_entry(afinfo->name, net->proc_net);
  1879. }
  1880. EXPORT_SYMBOL(udp_proc_unregister);
  1881. /* ------------------------------------------------------------------------ */
  1882. static void udp4_format_sock(struct sock *sp, struct seq_file *f,
  1883. int bucket, int *len)
  1884. {
  1885. struct inet_sock *inet = inet_sk(sp);
  1886. __be32 dest = inet->inet_daddr;
  1887. __be32 src = inet->inet_rcv_saddr;
  1888. __u16 destp = ntohs(inet->inet_dport);
  1889. __u16 srcp = ntohs(inet->inet_sport);
  1890. seq_printf(f, "%5d: %08X:%04X %08X:%04X"
  1891. " %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d%n",
  1892. bucket, src, srcp, dest, destp, sp->sk_state,
  1893. sk_wmem_alloc_get(sp),
  1894. sk_rmem_alloc_get(sp),
  1895. 0, 0L, 0,
  1896. from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
  1897. 0, sock_i_ino(sp),
  1898. atomic_read(&sp->sk_refcnt), sp,
  1899. atomic_read(&sp->sk_drops), len);
  1900. }
  1901. int udp4_seq_show(struct seq_file *seq, void *v)
  1902. {
  1903. if (v == SEQ_START_TOKEN)
  1904. seq_printf(seq, "%-127s\n",
  1905. " sl local_address rem_address st tx_queue "
  1906. "rx_queue tr tm->when retrnsmt uid timeout "
  1907. "inode ref pointer drops");
  1908. else {
  1909. struct udp_iter_state *state = seq->private;
  1910. int len;
  1911. udp4_format_sock(v, seq, state->bucket, &len);
  1912. seq_printf(seq, "%*s\n", 127 - len, "");
  1913. }
  1914. return 0;
  1915. }
  1916. static const struct file_operations udp_afinfo_seq_fops = {
  1917. .owner = THIS_MODULE,
  1918. .open = udp_seq_open,
  1919. .read = seq_read,
  1920. .llseek = seq_lseek,
  1921. .release = seq_release_net
  1922. };
  1923. /* ------------------------------------------------------------------------ */
  1924. static struct udp_seq_afinfo udp4_seq_afinfo = {
  1925. .name = "udp",
  1926. .family = AF_INET,
  1927. .udp_table = &udp_table,
  1928. .seq_fops = &udp_afinfo_seq_fops,
  1929. .seq_ops = {
  1930. .show = udp4_seq_show,
  1931. },
  1932. };
  1933. static int __net_init udp4_proc_init_net(struct net *net)
  1934. {
  1935. return udp_proc_register(net, &udp4_seq_afinfo);
  1936. }
  1937. static void __net_exit udp4_proc_exit_net(struct net *net)
  1938. {
  1939. udp_proc_unregister(net, &udp4_seq_afinfo);
  1940. }
  1941. static struct pernet_operations udp4_net_ops = {
  1942. .init = udp4_proc_init_net,
  1943. .exit = udp4_proc_exit_net,
  1944. };
  1945. int __init udp4_proc_init(void)
  1946. {
  1947. return register_pernet_subsys(&udp4_net_ops);
  1948. }
  1949. void udp4_proc_exit(void)
  1950. {
  1951. unregister_pernet_subsys(&udp4_net_ops);
  1952. }
  1953. #endif /* CONFIG_PROC_FS */
  1954. static __initdata unsigned long uhash_entries;
  1955. static int __init set_uhash_entries(char *str)
  1956. {
  1957. ssize_t ret;
  1958. if (!str)
  1959. return 0;
  1960. ret = kstrtoul(str, 0, &uhash_entries);
  1961. if (ret)
  1962. return 0;
  1963. if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
  1964. uhash_entries = UDP_HTABLE_SIZE_MIN;
  1965. return 1;
  1966. }
  1967. __setup("uhash_entries=", set_uhash_entries);
  1968. void __init udp_table_init(struct udp_table *table, const char *name)
  1969. {
  1970. unsigned int i;
  1971. table->hash = alloc_large_system_hash(name,
  1972. 2 * sizeof(struct udp_hslot),
  1973. uhash_entries,
  1974. 21, /* one slot per 2 MB */
  1975. 0,
  1976. &table->log,
  1977. &table->mask,
  1978. UDP_HTABLE_SIZE_MIN,
  1979. 64 * 1024);
  1980. table->hash2 = table->hash + (table->mask + 1);
  1981. for (i = 0; i <= table->mask; i++) {
  1982. INIT_HLIST_NULLS_HEAD(&table->hash[i].head, i);
  1983. table->hash[i].count = 0;
  1984. spin_lock_init(&table->hash[i].lock);
  1985. }
  1986. for (i = 0; i <= table->mask; i++) {
  1987. INIT_HLIST_NULLS_HEAD(&table->hash2[i].head, i);
  1988. table->hash2[i].count = 0;
  1989. spin_lock_init(&table->hash2[i].lock);
  1990. }
  1991. }
  1992. void __init udp_init(void)
  1993. {
  1994. unsigned long limit;
  1995. udp_table_init(&udp_table, "UDP");
  1996. limit = nr_free_buffer_pages() / 8;
  1997. limit = max(limit, 128UL);
  1998. sysctl_udp_mem[0] = limit / 4 * 3;
  1999. sysctl_udp_mem[1] = limit;
  2000. sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
  2001. sysctl_udp_rmem_min = SK_MEM_QUANTUM;
  2002. sysctl_udp_wmem_min = SK_MEM_QUANTUM;
  2003. }
  2004. struct sk_buff *skb_udp_tunnel_segment(struct sk_buff *skb,
  2005. netdev_features_t features)
  2006. {
  2007. struct sk_buff *segs = ERR_PTR(-EINVAL);
  2008. int mac_len = skb->mac_len;
  2009. int tnl_hlen = skb_inner_mac_header(skb) - skb_transport_header(skb);
  2010. __be16 protocol = skb->protocol;
  2011. netdev_features_t enc_features;
  2012. int outer_hlen;
  2013. if (unlikely(!pskb_may_pull(skb, tnl_hlen)))
  2014. goto out;
  2015. skb->encapsulation = 0;
  2016. __skb_pull(skb, tnl_hlen);
  2017. skb_reset_mac_header(skb);
  2018. skb_set_network_header(skb, skb_inner_network_offset(skb));
  2019. skb->mac_len = skb_inner_network_offset(skb);
  2020. skb->protocol = htons(ETH_P_TEB);
  2021. /* segment inner packet. */
  2022. enc_features = skb->dev->hw_enc_features & netif_skb_features(skb);
  2023. segs = skb_mac_gso_segment(skb, enc_features);
  2024. if (!segs || IS_ERR(segs))
  2025. goto out;
  2026. outer_hlen = skb_tnl_header_len(skb);
  2027. skb = segs;
  2028. do {
  2029. struct udphdr *uh;
  2030. int udp_offset = outer_hlen - tnl_hlen;
  2031. skb_reset_inner_headers(skb);
  2032. skb->encapsulation = 1;
  2033. skb->mac_len = mac_len;
  2034. skb_push(skb, outer_hlen);
  2035. skb_reset_mac_header(skb);
  2036. skb_set_network_header(skb, mac_len);
  2037. skb_set_transport_header(skb, udp_offset);
  2038. uh = udp_hdr(skb);
  2039. uh->len = htons(skb->len - udp_offset);
  2040. /* csum segment if tunnel sets skb with csum. */
  2041. if (protocol == htons(ETH_P_IP) && unlikely(uh->check)) {
  2042. struct iphdr *iph = ip_hdr(skb);
  2043. uh->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr,
  2044. skb->len - udp_offset,
  2045. IPPROTO_UDP, 0);
  2046. uh->check = csum_fold(skb_checksum(skb, udp_offset,
  2047. skb->len - udp_offset, 0));
  2048. if (uh->check == 0)
  2049. uh->check = CSUM_MANGLED_0;
  2050. } else if (protocol == htons(ETH_P_IPV6)) {
  2051. struct ipv6hdr *ipv6h = ipv6_hdr(skb);
  2052. u32 len = skb->len - udp_offset;
  2053. uh->check = ~csum_ipv6_magic(&ipv6h->saddr, &ipv6h->daddr,
  2054. len, IPPROTO_UDP, 0);
  2055. uh->check = csum_fold(skb_checksum(skb, udp_offset, len, 0));
  2056. if (uh->check == 0)
  2057. uh->check = CSUM_MANGLED_0;
  2058. skb->ip_summed = CHECKSUM_NONE;
  2059. }
  2060. skb->protocol = protocol;
  2061. } while ((skb = skb->next));
  2062. out:
  2063. return segs;
  2064. }