udp.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369
  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(net, &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. ipc.ttl = 0;
  779. ipc.tos = -1;
  780. getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
  781. fl4 = &inet->cork.fl.u.ip4;
  782. if (up->pending) {
  783. /*
  784. * There are pending frames.
  785. * The socket lock must be held while it's corked.
  786. */
  787. lock_sock(sk);
  788. if (likely(up->pending)) {
  789. if (unlikely(up->pending != AF_INET)) {
  790. release_sock(sk);
  791. return -EINVAL;
  792. }
  793. goto do_append_data;
  794. }
  795. release_sock(sk);
  796. }
  797. ulen += sizeof(struct udphdr);
  798. /*
  799. * Get and verify the address.
  800. */
  801. if (msg->msg_name) {
  802. struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name;
  803. if (msg->msg_namelen < sizeof(*usin))
  804. return -EINVAL;
  805. if (usin->sin_family != AF_INET) {
  806. if (usin->sin_family != AF_UNSPEC)
  807. return -EAFNOSUPPORT;
  808. }
  809. daddr = usin->sin_addr.s_addr;
  810. dport = usin->sin_port;
  811. if (dport == 0)
  812. return -EINVAL;
  813. } else {
  814. if (sk->sk_state != TCP_ESTABLISHED)
  815. return -EDESTADDRREQ;
  816. daddr = inet->inet_daddr;
  817. dport = inet->inet_dport;
  818. /* Open fast path for connected socket.
  819. Route will not be used, if at least one option is set.
  820. */
  821. connected = 1;
  822. }
  823. ipc.addr = inet->inet_saddr;
  824. ipc.oif = sk->sk_bound_dev_if;
  825. sock_tx_timestamp(sk, &ipc.tx_flags);
  826. if (msg->msg_controllen) {
  827. err = ip_cmsg_send(sock_net(sk), msg, &ipc);
  828. if (err)
  829. return err;
  830. if (ipc.opt)
  831. free = 1;
  832. connected = 0;
  833. }
  834. if (!ipc.opt) {
  835. struct ip_options_rcu *inet_opt;
  836. rcu_read_lock();
  837. inet_opt = rcu_dereference(inet->inet_opt);
  838. if (inet_opt) {
  839. memcpy(&opt_copy, inet_opt,
  840. sizeof(*inet_opt) + inet_opt->opt.optlen);
  841. ipc.opt = &opt_copy.opt;
  842. }
  843. rcu_read_unlock();
  844. }
  845. saddr = ipc.addr;
  846. ipc.addr = faddr = daddr;
  847. if (ipc.opt && ipc.opt->opt.srr) {
  848. if (!daddr)
  849. return -EINVAL;
  850. faddr = ipc.opt->opt.faddr;
  851. connected = 0;
  852. }
  853. tos = get_rttos(&ipc, inet);
  854. if (sock_flag(sk, SOCK_LOCALROUTE) ||
  855. (msg->msg_flags & MSG_DONTROUTE) ||
  856. (ipc.opt && ipc.opt->opt.is_strictroute)) {
  857. tos |= RTO_ONLINK;
  858. connected = 0;
  859. }
  860. if (ipv4_is_multicast(daddr)) {
  861. if (!ipc.oif)
  862. ipc.oif = inet->mc_index;
  863. if (!saddr)
  864. saddr = inet->mc_addr;
  865. connected = 0;
  866. } else if (!ipc.oif)
  867. ipc.oif = inet->uc_index;
  868. if (connected)
  869. rt = (struct rtable *)sk_dst_check(sk, 0);
  870. if (rt == NULL) {
  871. struct net *net = sock_net(sk);
  872. fl4 = &fl4_stack;
  873. flowi4_init_output(fl4, ipc.oif, sk->sk_mark, tos,
  874. RT_SCOPE_UNIVERSE, sk->sk_protocol,
  875. inet_sk_flowi_flags(sk)|FLOWI_FLAG_CAN_SLEEP,
  876. faddr, saddr, dport, inet->inet_sport);
  877. security_sk_classify_flow(sk, flowi4_to_flowi(fl4));
  878. rt = ip_route_output_flow(net, fl4, sk);
  879. if (IS_ERR(rt)) {
  880. err = PTR_ERR(rt);
  881. rt = NULL;
  882. if (err == -ENETUNREACH)
  883. IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
  884. goto out;
  885. }
  886. err = -EACCES;
  887. if ((rt->rt_flags & RTCF_BROADCAST) &&
  888. !sock_flag(sk, SOCK_BROADCAST))
  889. goto out;
  890. if (connected)
  891. sk_dst_set(sk, dst_clone(&rt->dst));
  892. }
  893. if (msg->msg_flags&MSG_CONFIRM)
  894. goto do_confirm;
  895. back_from_confirm:
  896. saddr = fl4->saddr;
  897. if (!ipc.addr)
  898. daddr = ipc.addr = fl4->daddr;
  899. /* Lockless fast path for the non-corking case. */
  900. if (!corkreq) {
  901. skb = ip_make_skb(sk, fl4, getfrag, msg->msg_iov, ulen,
  902. sizeof(struct udphdr), &ipc, &rt,
  903. msg->msg_flags);
  904. err = PTR_ERR(skb);
  905. if (!IS_ERR_OR_NULL(skb))
  906. err = udp_send_skb(skb, fl4);
  907. goto out;
  908. }
  909. lock_sock(sk);
  910. if (unlikely(up->pending)) {
  911. /* The socket is already corked while preparing it. */
  912. /* ... which is an evident application bug. --ANK */
  913. release_sock(sk);
  914. LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("cork app bug 2\n"));
  915. err = -EINVAL;
  916. goto out;
  917. }
  918. /*
  919. * Now cork the socket to pend data.
  920. */
  921. fl4 = &inet->cork.fl.u.ip4;
  922. fl4->daddr = daddr;
  923. fl4->saddr = saddr;
  924. fl4->fl4_dport = dport;
  925. fl4->fl4_sport = inet->inet_sport;
  926. up->pending = AF_INET;
  927. do_append_data:
  928. up->len += ulen;
  929. err = ip_append_data(sk, fl4, getfrag, msg->msg_iov, ulen,
  930. sizeof(struct udphdr), &ipc, &rt,
  931. corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
  932. if (err)
  933. udp_flush_pending_frames(sk);
  934. else if (!corkreq)
  935. err = udp_push_pending_frames(sk);
  936. else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
  937. up->pending = 0;
  938. release_sock(sk);
  939. out:
  940. ip_rt_put(rt);
  941. if (free)
  942. kfree(ipc.opt);
  943. if (!err)
  944. return len;
  945. /*
  946. * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
  947. * ENOBUFS might not be good (it's not tunable per se), but otherwise
  948. * we don't have a good statistic (IpOutDiscards but it can be too many
  949. * things). We could add another new stat but at least for now that
  950. * seems like overkill.
  951. */
  952. if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
  953. UDP_INC_STATS_USER(sock_net(sk),
  954. UDP_MIB_SNDBUFERRORS, is_udplite);
  955. }
  956. return err;
  957. do_confirm:
  958. dst_confirm(&rt->dst);
  959. if (!(msg->msg_flags&MSG_PROBE) || len)
  960. goto back_from_confirm;
  961. err = 0;
  962. goto out;
  963. }
  964. EXPORT_SYMBOL(udp_sendmsg);
  965. int udp_sendpage(struct sock *sk, struct page *page, int offset,
  966. size_t size, int flags)
  967. {
  968. struct inet_sock *inet = inet_sk(sk);
  969. struct udp_sock *up = udp_sk(sk);
  970. int ret;
  971. if (!up->pending) {
  972. struct msghdr msg = { .msg_flags = flags|MSG_MORE };
  973. /* Call udp_sendmsg to specify destination address which
  974. * sendpage interface can't pass.
  975. * This will succeed only when the socket is connected.
  976. */
  977. ret = udp_sendmsg(NULL, sk, &msg, 0);
  978. if (ret < 0)
  979. return ret;
  980. }
  981. lock_sock(sk);
  982. if (unlikely(!up->pending)) {
  983. release_sock(sk);
  984. LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("udp cork app bug 3\n"));
  985. return -EINVAL;
  986. }
  987. ret = ip_append_page(sk, &inet->cork.fl.u.ip4,
  988. page, offset, size, flags);
  989. if (ret == -EOPNOTSUPP) {
  990. release_sock(sk);
  991. return sock_no_sendpage(sk->sk_socket, page, offset,
  992. size, flags);
  993. }
  994. if (ret < 0) {
  995. udp_flush_pending_frames(sk);
  996. goto out;
  997. }
  998. up->len += size;
  999. if (!(up->corkflag || (flags&MSG_MORE)))
  1000. ret = udp_push_pending_frames(sk);
  1001. if (!ret)
  1002. ret = size;
  1003. out:
  1004. release_sock(sk);
  1005. return ret;
  1006. }
  1007. /**
  1008. * first_packet_length - return length of first packet in receive queue
  1009. * @sk: socket
  1010. *
  1011. * Drops all bad checksum frames, until a valid one is found.
  1012. * Returns the length of found skb, or 0 if none is found.
  1013. */
  1014. static unsigned int first_packet_length(struct sock *sk)
  1015. {
  1016. struct sk_buff_head list_kill, *rcvq = &sk->sk_receive_queue;
  1017. struct sk_buff *skb;
  1018. unsigned int res;
  1019. __skb_queue_head_init(&list_kill);
  1020. spin_lock_bh(&rcvq->lock);
  1021. while ((skb = skb_peek(rcvq)) != NULL &&
  1022. udp_lib_checksum_complete(skb)) {
  1023. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS,
  1024. IS_UDPLITE(sk));
  1025. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS,
  1026. IS_UDPLITE(sk));
  1027. atomic_inc(&sk->sk_drops);
  1028. __skb_unlink(skb, rcvq);
  1029. __skb_queue_tail(&list_kill, skb);
  1030. }
  1031. res = skb ? skb->len : 0;
  1032. spin_unlock_bh(&rcvq->lock);
  1033. if (!skb_queue_empty(&list_kill)) {
  1034. bool slow = lock_sock_fast(sk);
  1035. __skb_queue_purge(&list_kill);
  1036. sk_mem_reclaim_partial(sk);
  1037. unlock_sock_fast(sk, slow);
  1038. }
  1039. return res;
  1040. }
  1041. /*
  1042. * IOCTL requests applicable to the UDP protocol
  1043. */
  1044. int udp_ioctl(struct sock *sk, int cmd, unsigned long arg)
  1045. {
  1046. switch (cmd) {
  1047. case SIOCOUTQ:
  1048. {
  1049. int amount = sk_wmem_alloc_get(sk);
  1050. return put_user(amount, (int __user *)arg);
  1051. }
  1052. case SIOCINQ:
  1053. {
  1054. unsigned int amount = first_packet_length(sk);
  1055. if (amount)
  1056. /*
  1057. * We will only return the amount
  1058. * of this packet since that is all
  1059. * that will be read.
  1060. */
  1061. amount -= sizeof(struct udphdr);
  1062. return put_user(amount, (int __user *)arg);
  1063. }
  1064. default:
  1065. return -ENOIOCTLCMD;
  1066. }
  1067. return 0;
  1068. }
  1069. EXPORT_SYMBOL(udp_ioctl);
  1070. /*
  1071. * This should be easy, if there is something there we
  1072. * return it, otherwise we block.
  1073. */
  1074. int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
  1075. size_t len, int noblock, int flags, int *addr_len)
  1076. {
  1077. struct inet_sock *inet = inet_sk(sk);
  1078. struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
  1079. struct sk_buff *skb;
  1080. unsigned int ulen, copied;
  1081. int peeked, off = 0;
  1082. int err;
  1083. int is_udplite = IS_UDPLITE(sk);
  1084. bool slow;
  1085. /*
  1086. * Check any passed addresses
  1087. */
  1088. if (addr_len)
  1089. *addr_len = sizeof(*sin);
  1090. if (flags & MSG_ERRQUEUE)
  1091. return ip_recv_error(sk, msg, len);
  1092. try_again:
  1093. skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
  1094. &peeked, &off, &err);
  1095. if (!skb)
  1096. goto out;
  1097. ulen = skb->len - sizeof(struct udphdr);
  1098. copied = len;
  1099. if (copied > ulen)
  1100. copied = ulen;
  1101. else if (copied < ulen)
  1102. msg->msg_flags |= MSG_TRUNC;
  1103. /*
  1104. * If checksum is needed at all, try to do it while copying the
  1105. * data. If the data is truncated, or if we only want a partial
  1106. * coverage checksum (UDP-Lite), do it before the copy.
  1107. */
  1108. if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
  1109. if (udp_lib_checksum_complete(skb))
  1110. goto csum_copy_err;
  1111. }
  1112. if (skb_csum_unnecessary(skb))
  1113. err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
  1114. msg->msg_iov, copied);
  1115. else {
  1116. err = skb_copy_and_csum_datagram_iovec(skb,
  1117. sizeof(struct udphdr),
  1118. msg->msg_iov);
  1119. if (err == -EINVAL)
  1120. goto csum_copy_err;
  1121. }
  1122. if (unlikely(err)) {
  1123. trace_kfree_skb(skb, udp_recvmsg);
  1124. if (!peeked) {
  1125. atomic_inc(&sk->sk_drops);
  1126. UDP_INC_STATS_USER(sock_net(sk),
  1127. UDP_MIB_INERRORS, is_udplite);
  1128. }
  1129. goto out_free;
  1130. }
  1131. if (!peeked)
  1132. UDP_INC_STATS_USER(sock_net(sk),
  1133. UDP_MIB_INDATAGRAMS, is_udplite);
  1134. sock_recv_ts_and_drops(msg, sk, skb);
  1135. /* Copy the address. */
  1136. if (sin) {
  1137. sin->sin_family = AF_INET;
  1138. sin->sin_port = udp_hdr(skb)->source;
  1139. sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
  1140. memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
  1141. }
  1142. if (inet->cmsg_flags)
  1143. ip_cmsg_recv(msg, skb);
  1144. err = copied;
  1145. if (flags & MSG_TRUNC)
  1146. err = ulen;
  1147. out_free:
  1148. skb_free_datagram_locked(sk, skb);
  1149. out:
  1150. return err;
  1151. csum_copy_err:
  1152. slow = lock_sock_fast(sk);
  1153. if (!skb_kill_datagram(sk, skb, flags)) {
  1154. UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
  1155. UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1156. }
  1157. unlock_sock_fast(sk, slow);
  1158. if (noblock)
  1159. return -EAGAIN;
  1160. /* starting over for a new packet */
  1161. msg->msg_flags &= ~MSG_TRUNC;
  1162. goto try_again;
  1163. }
  1164. int udp_disconnect(struct sock *sk, int flags)
  1165. {
  1166. struct inet_sock *inet = inet_sk(sk);
  1167. /*
  1168. * 1003.1g - break association.
  1169. */
  1170. sk->sk_state = TCP_CLOSE;
  1171. inet->inet_daddr = 0;
  1172. inet->inet_dport = 0;
  1173. sock_rps_reset_rxhash(sk);
  1174. sk->sk_bound_dev_if = 0;
  1175. if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
  1176. inet_reset_saddr(sk);
  1177. if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) {
  1178. sk->sk_prot->unhash(sk);
  1179. inet->inet_sport = 0;
  1180. }
  1181. sk_dst_reset(sk);
  1182. return 0;
  1183. }
  1184. EXPORT_SYMBOL(udp_disconnect);
  1185. void udp_lib_unhash(struct sock *sk)
  1186. {
  1187. if (sk_hashed(sk)) {
  1188. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  1189. struct udp_hslot *hslot, *hslot2;
  1190. hslot = udp_hashslot(udptable, sock_net(sk),
  1191. udp_sk(sk)->udp_port_hash);
  1192. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  1193. spin_lock_bh(&hslot->lock);
  1194. if (sk_nulls_del_node_init_rcu(sk)) {
  1195. hslot->count--;
  1196. inet_sk(sk)->inet_num = 0;
  1197. sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
  1198. spin_lock(&hslot2->lock);
  1199. hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
  1200. hslot2->count--;
  1201. spin_unlock(&hslot2->lock);
  1202. }
  1203. spin_unlock_bh(&hslot->lock);
  1204. }
  1205. }
  1206. EXPORT_SYMBOL(udp_lib_unhash);
  1207. /*
  1208. * inet_rcv_saddr was changed, we must rehash secondary hash
  1209. */
  1210. void udp_lib_rehash(struct sock *sk, u16 newhash)
  1211. {
  1212. if (sk_hashed(sk)) {
  1213. struct udp_table *udptable = sk->sk_prot->h.udp_table;
  1214. struct udp_hslot *hslot, *hslot2, *nhslot2;
  1215. hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash);
  1216. nhslot2 = udp_hashslot2(udptable, newhash);
  1217. udp_sk(sk)->udp_portaddr_hash = newhash;
  1218. if (hslot2 != nhslot2) {
  1219. hslot = udp_hashslot(udptable, sock_net(sk),
  1220. udp_sk(sk)->udp_port_hash);
  1221. /* we must lock primary chain too */
  1222. spin_lock_bh(&hslot->lock);
  1223. spin_lock(&hslot2->lock);
  1224. hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node);
  1225. hslot2->count--;
  1226. spin_unlock(&hslot2->lock);
  1227. spin_lock(&nhslot2->lock);
  1228. hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node,
  1229. &nhslot2->head);
  1230. nhslot2->count++;
  1231. spin_unlock(&nhslot2->lock);
  1232. spin_unlock_bh(&hslot->lock);
  1233. }
  1234. }
  1235. }
  1236. EXPORT_SYMBOL(udp_lib_rehash);
  1237. static void udp_v4_rehash(struct sock *sk)
  1238. {
  1239. u16 new_hash = udp4_portaddr_hash(sock_net(sk),
  1240. inet_sk(sk)->inet_rcv_saddr,
  1241. inet_sk(sk)->inet_num);
  1242. udp_lib_rehash(sk, new_hash);
  1243. }
  1244. static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  1245. {
  1246. int rc;
  1247. if (inet_sk(sk)->inet_daddr)
  1248. sock_rps_save_rxhash(sk, skb);
  1249. rc = sock_queue_rcv_skb(sk, skb);
  1250. if (rc < 0) {
  1251. int is_udplite = IS_UDPLITE(sk);
  1252. /* Note that an ENOMEM error is charged twice */
  1253. if (rc == -ENOMEM)
  1254. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS,
  1255. is_udplite);
  1256. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1257. kfree_skb(skb);
  1258. trace_udp_fail_queue_rcv_skb(rc, sk);
  1259. return -1;
  1260. }
  1261. return 0;
  1262. }
  1263. static struct static_key udp_encap_needed __read_mostly;
  1264. void udp_encap_enable(void)
  1265. {
  1266. if (!static_key_enabled(&udp_encap_needed))
  1267. static_key_slow_inc(&udp_encap_needed);
  1268. }
  1269. EXPORT_SYMBOL(udp_encap_enable);
  1270. /* returns:
  1271. * -1: error
  1272. * 0: success
  1273. * >0: "udp encap" protocol resubmission
  1274. *
  1275. * Note that in the success and error cases, the skb is assumed to
  1276. * have either been requeued or freed.
  1277. */
  1278. int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
  1279. {
  1280. struct udp_sock *up = udp_sk(sk);
  1281. int rc;
  1282. int is_udplite = IS_UDPLITE(sk);
  1283. /*
  1284. * Charge it to the socket, dropping if the queue is full.
  1285. */
  1286. if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
  1287. goto drop;
  1288. nf_reset(skb);
  1289. if (static_key_false(&udp_encap_needed) && up->encap_type) {
  1290. int (*encap_rcv)(struct sock *sk, struct sk_buff *skb);
  1291. /*
  1292. * This is an encapsulation socket so pass the skb to
  1293. * the socket's udp_encap_rcv() hook. Otherwise, just
  1294. * fall through and pass this up the UDP socket.
  1295. * up->encap_rcv() returns the following value:
  1296. * =0 if skb was successfully passed to the encap
  1297. * handler or was discarded by it.
  1298. * >0 if skb should be passed on to UDP.
  1299. * <0 if skb should be resubmitted as proto -N
  1300. */
  1301. /* if we're overly short, let UDP handle it */
  1302. encap_rcv = ACCESS_ONCE(up->encap_rcv);
  1303. if (skb->len > sizeof(struct udphdr) && encap_rcv != NULL) {
  1304. int ret;
  1305. ret = encap_rcv(sk, skb);
  1306. if (ret <= 0) {
  1307. UDP_INC_STATS_BH(sock_net(sk),
  1308. UDP_MIB_INDATAGRAMS,
  1309. is_udplite);
  1310. return -ret;
  1311. }
  1312. }
  1313. /* FALLTHROUGH -- it's a UDP Packet */
  1314. }
  1315. /*
  1316. * UDP-Lite specific tests, ignored on UDP sockets
  1317. */
  1318. if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) {
  1319. /*
  1320. * MIB statistics other than incrementing the error count are
  1321. * disabled for the following two types of errors: these depend
  1322. * on the application settings, not on the functioning of the
  1323. * protocol stack as such.
  1324. *
  1325. * RFC 3828 here recommends (sec 3.3): "There should also be a
  1326. * way ... to ... at least let the receiving application block
  1327. * delivery of packets with coverage values less than a value
  1328. * provided by the application."
  1329. */
  1330. if (up->pcrlen == 0) { /* full coverage was set */
  1331. LIMIT_NETDEBUG(KERN_WARNING "UDPLite: partial coverage %d while full coverage %d requested\n",
  1332. UDP_SKB_CB(skb)->cscov, skb->len);
  1333. goto drop;
  1334. }
  1335. /* The next case involves violating the min. coverage requested
  1336. * by the receiver. This is subtle: if receiver wants x and x is
  1337. * greater than the buffersize/MTU then receiver will complain
  1338. * that it wants x while sender emits packets of smaller size y.
  1339. * Therefore the above ...()->partial_cov statement is essential.
  1340. */
  1341. if (UDP_SKB_CB(skb)->cscov < up->pcrlen) {
  1342. LIMIT_NETDEBUG(KERN_WARNING "UDPLite: coverage %d too small, need min %d\n",
  1343. UDP_SKB_CB(skb)->cscov, up->pcrlen);
  1344. goto drop;
  1345. }
  1346. }
  1347. if (rcu_access_pointer(sk->sk_filter) &&
  1348. udp_lib_checksum_complete(skb))
  1349. goto csum_error;
  1350. if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf))
  1351. goto drop;
  1352. rc = 0;
  1353. ipv4_pktinfo_prepare(skb);
  1354. bh_lock_sock(sk);
  1355. if (!sock_owned_by_user(sk))
  1356. rc = __udp_queue_rcv_skb(sk, skb);
  1357. else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) {
  1358. bh_unlock_sock(sk);
  1359. goto drop;
  1360. }
  1361. bh_unlock_sock(sk);
  1362. return rc;
  1363. csum_error:
  1364. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
  1365. drop:
  1366. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
  1367. atomic_inc(&sk->sk_drops);
  1368. kfree_skb(skb);
  1369. return -1;
  1370. }
  1371. static void flush_stack(struct sock **stack, unsigned int count,
  1372. struct sk_buff *skb, unsigned int final)
  1373. {
  1374. unsigned int i;
  1375. struct sk_buff *skb1 = NULL;
  1376. struct sock *sk;
  1377. for (i = 0; i < count; i++) {
  1378. sk = stack[i];
  1379. if (likely(skb1 == NULL))
  1380. skb1 = (i == final) ? skb : skb_clone(skb, GFP_ATOMIC);
  1381. if (!skb1) {
  1382. atomic_inc(&sk->sk_drops);
  1383. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS,
  1384. IS_UDPLITE(sk));
  1385. UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS,
  1386. IS_UDPLITE(sk));
  1387. }
  1388. if (skb1 && udp_queue_rcv_skb(sk, skb1) <= 0)
  1389. skb1 = NULL;
  1390. }
  1391. if (unlikely(skb1))
  1392. kfree_skb(skb1);
  1393. }
  1394. /*
  1395. * Multicasts and broadcasts go to each listener.
  1396. *
  1397. * Note: called only from the BH handler context.
  1398. */
  1399. static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb,
  1400. struct udphdr *uh,
  1401. __be32 saddr, __be32 daddr,
  1402. struct udp_table *udptable)
  1403. {
  1404. struct sock *sk, *stack[256 / sizeof(struct sock *)];
  1405. struct udp_hslot *hslot = udp_hashslot(udptable, net, ntohs(uh->dest));
  1406. int dif;
  1407. unsigned int i, count = 0;
  1408. spin_lock(&hslot->lock);
  1409. sk = sk_nulls_head(&hslot->head);
  1410. dif = skb->dev->ifindex;
  1411. sk = udp_v4_mcast_next(net, sk, uh->dest, daddr, uh->source, saddr, dif);
  1412. while (sk) {
  1413. stack[count++] = sk;
  1414. sk = udp_v4_mcast_next(net, sk_nulls_next(sk), uh->dest,
  1415. daddr, uh->source, saddr, dif);
  1416. if (unlikely(count == ARRAY_SIZE(stack))) {
  1417. if (!sk)
  1418. break;
  1419. flush_stack(stack, count, skb, ~0);
  1420. count = 0;
  1421. }
  1422. }
  1423. /*
  1424. * before releasing chain lock, we must take a reference on sockets
  1425. */
  1426. for (i = 0; i < count; i++)
  1427. sock_hold(stack[i]);
  1428. spin_unlock(&hslot->lock);
  1429. /*
  1430. * do the slow work with no lock held
  1431. */
  1432. if (count) {
  1433. flush_stack(stack, count, skb, count - 1);
  1434. for (i = 0; i < count; i++)
  1435. sock_put(stack[i]);
  1436. } else {
  1437. kfree_skb(skb);
  1438. }
  1439. return 0;
  1440. }
  1441. /* Initialize UDP checksum. If exited with zero value (success),
  1442. * CHECKSUM_UNNECESSARY means, that no more checks are required.
  1443. * Otherwise, csum completion requires chacksumming packet body,
  1444. * including udp header and folding it to skb->csum.
  1445. */
  1446. static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh,
  1447. int proto)
  1448. {
  1449. const struct iphdr *iph;
  1450. int err;
  1451. UDP_SKB_CB(skb)->partial_cov = 0;
  1452. UDP_SKB_CB(skb)->cscov = skb->len;
  1453. if (proto == IPPROTO_UDPLITE) {
  1454. err = udplite_checksum_init(skb, uh);
  1455. if (err)
  1456. return err;
  1457. }
  1458. iph = ip_hdr(skb);
  1459. if (uh->check == 0) {
  1460. skb->ip_summed = CHECKSUM_UNNECESSARY;
  1461. } else if (skb->ip_summed == CHECKSUM_COMPLETE) {
  1462. if (!csum_tcpudp_magic(iph->saddr, iph->daddr, skb->len,
  1463. proto, skb->csum))
  1464. skb->ip_summed = CHECKSUM_UNNECESSARY;
  1465. }
  1466. if (!skb_csum_unnecessary(skb))
  1467. skb->csum = csum_tcpudp_nofold(iph->saddr, iph->daddr,
  1468. skb->len, proto, 0);
  1469. /* Probably, we should checksum udp header (it should be in cache
  1470. * in any case) and data in tiny packets (< rx copybreak).
  1471. */
  1472. return 0;
  1473. }
  1474. /*
  1475. * All we need to do is get the socket, and then do a checksum.
  1476. */
  1477. int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable,
  1478. int proto)
  1479. {
  1480. struct sock *sk;
  1481. struct udphdr *uh;
  1482. unsigned short ulen;
  1483. struct rtable *rt = skb_rtable(skb);
  1484. __be32 saddr, daddr;
  1485. struct net *net = dev_net(skb->dev);
  1486. /*
  1487. * Validate the packet.
  1488. */
  1489. if (!pskb_may_pull(skb, sizeof(struct udphdr)))
  1490. goto drop; /* No space for header. */
  1491. uh = udp_hdr(skb);
  1492. ulen = ntohs(uh->len);
  1493. saddr = ip_hdr(skb)->saddr;
  1494. daddr = ip_hdr(skb)->daddr;
  1495. if (ulen > skb->len)
  1496. goto short_packet;
  1497. if (proto == IPPROTO_UDP) {
  1498. /* UDP validates ulen. */
  1499. if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen))
  1500. goto short_packet;
  1501. uh = udp_hdr(skb);
  1502. }
  1503. if (udp4_csum_init(skb, uh, proto))
  1504. goto csum_error;
  1505. if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST))
  1506. return __udp4_lib_mcast_deliver(net, skb, uh,
  1507. saddr, daddr, udptable);
  1508. sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable);
  1509. if (sk != NULL) {
  1510. int ret;
  1511. sk_mark_napi_id(sk, skb);
  1512. ret = udp_queue_rcv_skb(sk, skb);
  1513. sock_put(sk);
  1514. /* a return value > 0 means to resubmit the input, but
  1515. * it wants the return to be -protocol, or 0
  1516. */
  1517. if (ret > 0)
  1518. return -ret;
  1519. return 0;
  1520. }
  1521. if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
  1522. goto drop;
  1523. nf_reset(skb);
  1524. /* No socket. Drop packet silently, if checksum is wrong */
  1525. if (udp_lib_checksum_complete(skb))
  1526. goto csum_error;
  1527. UDP_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE);
  1528. icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
  1529. /*
  1530. * Hmm. We got an UDP packet to a port to which we
  1531. * don't wanna listen. Ignore it.
  1532. */
  1533. kfree_skb(skb);
  1534. return 0;
  1535. short_packet:
  1536. LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n",
  1537. proto == IPPROTO_UDPLITE ? "Lite" : "",
  1538. &saddr, ntohs(uh->source),
  1539. ulen, skb->len,
  1540. &daddr, ntohs(uh->dest));
  1541. goto drop;
  1542. csum_error:
  1543. /*
  1544. * RFC1122: OK. Discards the bad packet silently (as far as
  1545. * the network is concerned, anyway) as per 4.1.3.4 (MUST).
  1546. */
  1547. LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n",
  1548. proto == IPPROTO_UDPLITE ? "Lite" : "",
  1549. &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest),
  1550. ulen);
  1551. UDP_INC_STATS_BH(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE);
  1552. drop:
  1553. UDP_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE);
  1554. kfree_skb(skb);
  1555. return 0;
  1556. }
  1557. int udp_rcv(struct sk_buff *skb)
  1558. {
  1559. return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP);
  1560. }
  1561. void udp_destroy_sock(struct sock *sk)
  1562. {
  1563. struct udp_sock *up = udp_sk(sk);
  1564. bool slow = lock_sock_fast(sk);
  1565. udp_flush_pending_frames(sk);
  1566. unlock_sock_fast(sk, slow);
  1567. if (static_key_false(&udp_encap_needed) && up->encap_type) {
  1568. void (*encap_destroy)(struct sock *sk);
  1569. encap_destroy = ACCESS_ONCE(up->encap_destroy);
  1570. if (encap_destroy)
  1571. encap_destroy(sk);
  1572. }
  1573. }
  1574. /*
  1575. * Socket option code for UDP
  1576. */
  1577. int udp_lib_setsockopt(struct sock *sk, int level, int optname,
  1578. char __user *optval, unsigned int optlen,
  1579. int (*push_pending_frames)(struct sock *))
  1580. {
  1581. struct udp_sock *up = udp_sk(sk);
  1582. int val;
  1583. int err = 0;
  1584. int is_udplite = IS_UDPLITE(sk);
  1585. if (optlen < sizeof(int))
  1586. return -EINVAL;
  1587. if (get_user(val, (int __user *)optval))
  1588. return -EFAULT;
  1589. switch (optname) {
  1590. case UDP_CORK:
  1591. if (val != 0) {
  1592. up->corkflag = 1;
  1593. } else {
  1594. up->corkflag = 0;
  1595. lock_sock(sk);
  1596. (*push_pending_frames)(sk);
  1597. release_sock(sk);
  1598. }
  1599. break;
  1600. case UDP_ENCAP:
  1601. switch (val) {
  1602. case 0:
  1603. case UDP_ENCAP_ESPINUDP:
  1604. case UDP_ENCAP_ESPINUDP_NON_IKE:
  1605. up->encap_rcv = xfrm4_udp_encap_rcv;
  1606. /* FALLTHROUGH */
  1607. case UDP_ENCAP_L2TPINUDP:
  1608. up->encap_type = val;
  1609. udp_encap_enable();
  1610. break;
  1611. default:
  1612. err = -ENOPROTOOPT;
  1613. break;
  1614. }
  1615. break;
  1616. /*
  1617. * UDP-Lite's partial checksum coverage (RFC 3828).
  1618. */
  1619. /* The sender sets actual checksum coverage length via this option.
  1620. * The case coverage > packet length is handled by send module. */
  1621. case UDPLITE_SEND_CSCOV:
  1622. if (!is_udplite) /* Disable the option on UDP sockets */
  1623. return -ENOPROTOOPT;
  1624. if (val != 0 && val < 8) /* Illegal coverage: use default (8) */
  1625. val = 8;
  1626. else if (val > USHRT_MAX)
  1627. val = USHRT_MAX;
  1628. up->pcslen = val;
  1629. up->pcflag |= UDPLITE_SEND_CC;
  1630. break;
  1631. /* The receiver specifies a minimum checksum coverage value. To make
  1632. * sense, this should be set to at least 8 (as done below). If zero is
  1633. * used, this again means full checksum coverage. */
  1634. case UDPLITE_RECV_CSCOV:
  1635. if (!is_udplite) /* Disable the option on UDP sockets */
  1636. return -ENOPROTOOPT;
  1637. if (val != 0 && val < 8) /* Avoid silly minimal values. */
  1638. val = 8;
  1639. else if (val > USHRT_MAX)
  1640. val = USHRT_MAX;
  1641. up->pcrlen = val;
  1642. up->pcflag |= UDPLITE_RECV_CC;
  1643. break;
  1644. default:
  1645. err = -ENOPROTOOPT;
  1646. break;
  1647. }
  1648. return err;
  1649. }
  1650. EXPORT_SYMBOL(udp_lib_setsockopt);
  1651. int udp_setsockopt(struct sock *sk, int level, int optname,
  1652. char __user *optval, unsigned int optlen)
  1653. {
  1654. if (level == SOL_UDP || level == SOL_UDPLITE)
  1655. return udp_lib_setsockopt(sk, level, optname, optval, optlen,
  1656. udp_push_pending_frames);
  1657. return ip_setsockopt(sk, level, optname, optval, optlen);
  1658. }
  1659. #ifdef CONFIG_COMPAT
  1660. int compat_udp_setsockopt(struct sock *sk, int level, int optname,
  1661. char __user *optval, unsigned int optlen)
  1662. {
  1663. if (level == SOL_UDP || level == SOL_UDPLITE)
  1664. return udp_lib_setsockopt(sk, level, optname, optval, optlen,
  1665. udp_push_pending_frames);
  1666. return compat_ip_setsockopt(sk, level, optname, optval, optlen);
  1667. }
  1668. #endif
  1669. int udp_lib_getsockopt(struct sock *sk, int level, int optname,
  1670. char __user *optval, int __user *optlen)
  1671. {
  1672. struct udp_sock *up = udp_sk(sk);
  1673. int val, len;
  1674. if (get_user(len, optlen))
  1675. return -EFAULT;
  1676. len = min_t(unsigned int, len, sizeof(int));
  1677. if (len < 0)
  1678. return -EINVAL;
  1679. switch (optname) {
  1680. case UDP_CORK:
  1681. val = up->corkflag;
  1682. break;
  1683. case UDP_ENCAP:
  1684. val = up->encap_type;
  1685. break;
  1686. /* The following two cannot be changed on UDP sockets, the return is
  1687. * always 0 (which corresponds to the full checksum coverage of UDP). */
  1688. case UDPLITE_SEND_CSCOV:
  1689. val = up->pcslen;
  1690. break;
  1691. case UDPLITE_RECV_CSCOV:
  1692. val = up->pcrlen;
  1693. break;
  1694. default:
  1695. return -ENOPROTOOPT;
  1696. }
  1697. if (put_user(len, optlen))
  1698. return -EFAULT;
  1699. if (copy_to_user(optval, &val, len))
  1700. return -EFAULT;
  1701. return 0;
  1702. }
  1703. EXPORT_SYMBOL(udp_lib_getsockopt);
  1704. int udp_getsockopt(struct sock *sk, int level, int optname,
  1705. char __user *optval, int __user *optlen)
  1706. {
  1707. if (level == SOL_UDP || level == SOL_UDPLITE)
  1708. return udp_lib_getsockopt(sk, level, optname, optval, optlen);
  1709. return ip_getsockopt(sk, level, optname, optval, optlen);
  1710. }
  1711. #ifdef CONFIG_COMPAT
  1712. int compat_udp_getsockopt(struct sock *sk, int level, int optname,
  1713. char __user *optval, int __user *optlen)
  1714. {
  1715. if (level == SOL_UDP || level == SOL_UDPLITE)
  1716. return udp_lib_getsockopt(sk, level, optname, optval, optlen);
  1717. return compat_ip_getsockopt(sk, level, optname, optval, optlen);
  1718. }
  1719. #endif
  1720. /**
  1721. * udp_poll - wait for a UDP event.
  1722. * @file - file struct
  1723. * @sock - socket
  1724. * @wait - poll table
  1725. *
  1726. * This is same as datagram poll, except for the special case of
  1727. * blocking sockets. If application is using a blocking fd
  1728. * and a packet with checksum error is in the queue;
  1729. * then it could get return from select indicating data available
  1730. * but then block when reading it. Add special case code
  1731. * to work around these arguably broken applications.
  1732. */
  1733. unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait)
  1734. {
  1735. unsigned int mask = datagram_poll(file, sock, wait);
  1736. struct sock *sk = sock->sk;
  1737. sock_rps_record_flow(sk);
  1738. /* Check for false positives due to checksum errors */
  1739. if ((mask & POLLRDNORM) && !(file->f_flags & O_NONBLOCK) &&
  1740. !(sk->sk_shutdown & RCV_SHUTDOWN) && !first_packet_length(sk))
  1741. mask &= ~(POLLIN | POLLRDNORM);
  1742. return mask;
  1743. }
  1744. EXPORT_SYMBOL(udp_poll);
  1745. struct proto udp_prot = {
  1746. .name = "UDP",
  1747. .owner = THIS_MODULE,
  1748. .close = udp_lib_close,
  1749. .connect = ip4_datagram_connect,
  1750. .disconnect = udp_disconnect,
  1751. .ioctl = udp_ioctl,
  1752. .destroy = udp_destroy_sock,
  1753. .setsockopt = udp_setsockopt,
  1754. .getsockopt = udp_getsockopt,
  1755. .sendmsg = udp_sendmsg,
  1756. .recvmsg = udp_recvmsg,
  1757. .sendpage = udp_sendpage,
  1758. .backlog_rcv = __udp_queue_rcv_skb,
  1759. .release_cb = ip4_datagram_release_cb,
  1760. .hash = udp_lib_hash,
  1761. .unhash = udp_lib_unhash,
  1762. .rehash = udp_v4_rehash,
  1763. .get_port = udp_v4_get_port,
  1764. .memory_allocated = &udp_memory_allocated,
  1765. .sysctl_mem = sysctl_udp_mem,
  1766. .sysctl_wmem = &sysctl_udp_wmem_min,
  1767. .sysctl_rmem = &sysctl_udp_rmem_min,
  1768. .obj_size = sizeof(struct udp_sock),
  1769. .slab_flags = SLAB_DESTROY_BY_RCU,
  1770. .h.udp_table = &udp_table,
  1771. #ifdef CONFIG_COMPAT
  1772. .compat_setsockopt = compat_udp_setsockopt,
  1773. .compat_getsockopt = compat_udp_getsockopt,
  1774. #endif
  1775. .clear_sk = sk_prot_clear_portaddr_nulls,
  1776. };
  1777. EXPORT_SYMBOL(udp_prot);
  1778. /* ------------------------------------------------------------------------ */
  1779. #ifdef CONFIG_PROC_FS
  1780. static struct sock *udp_get_first(struct seq_file *seq, int start)
  1781. {
  1782. struct sock *sk;
  1783. struct udp_iter_state *state = seq->private;
  1784. struct net *net = seq_file_net(seq);
  1785. for (state->bucket = start; state->bucket <= state->udp_table->mask;
  1786. ++state->bucket) {
  1787. struct hlist_nulls_node *node;
  1788. struct udp_hslot *hslot = &state->udp_table->hash[state->bucket];
  1789. if (hlist_nulls_empty(&hslot->head))
  1790. continue;
  1791. spin_lock_bh(&hslot->lock);
  1792. sk_nulls_for_each(sk, node, &hslot->head) {
  1793. if (!net_eq(sock_net(sk), net))
  1794. continue;
  1795. if (sk->sk_family == state->family)
  1796. goto found;
  1797. }
  1798. spin_unlock_bh(&hslot->lock);
  1799. }
  1800. sk = NULL;
  1801. found:
  1802. return sk;
  1803. }
  1804. static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk)
  1805. {
  1806. struct udp_iter_state *state = seq->private;
  1807. struct net *net = seq_file_net(seq);
  1808. do {
  1809. sk = sk_nulls_next(sk);
  1810. } while (sk && (!net_eq(sock_net(sk), net) || sk->sk_family != state->family));
  1811. if (!sk) {
  1812. if (state->bucket <= state->udp_table->mask)
  1813. spin_unlock_bh(&state->udp_table->hash[state->bucket].lock);
  1814. return udp_get_first(seq, state->bucket + 1);
  1815. }
  1816. return sk;
  1817. }
  1818. static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos)
  1819. {
  1820. struct sock *sk = udp_get_first(seq, 0);
  1821. if (sk)
  1822. while (pos && (sk = udp_get_next(seq, sk)) != NULL)
  1823. --pos;
  1824. return pos ? NULL : sk;
  1825. }
  1826. static void *udp_seq_start(struct seq_file *seq, loff_t *pos)
  1827. {
  1828. struct udp_iter_state *state = seq->private;
  1829. state->bucket = MAX_UDP_PORTS;
  1830. return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
  1831. }
  1832. static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
  1833. {
  1834. struct sock *sk;
  1835. if (v == SEQ_START_TOKEN)
  1836. sk = udp_get_idx(seq, 0);
  1837. else
  1838. sk = udp_get_next(seq, v);
  1839. ++*pos;
  1840. return sk;
  1841. }
  1842. static void udp_seq_stop(struct seq_file *seq, void *v)
  1843. {
  1844. struct udp_iter_state *state = seq->private;
  1845. if (state->bucket <= state->udp_table->mask)
  1846. spin_unlock_bh(&state->udp_table->hash[state->bucket].lock);
  1847. }
  1848. int udp_seq_open(struct inode *inode, struct file *file)
  1849. {
  1850. struct udp_seq_afinfo *afinfo = PDE_DATA(inode);
  1851. struct udp_iter_state *s;
  1852. int err;
  1853. err = seq_open_net(inode, file, &afinfo->seq_ops,
  1854. sizeof(struct udp_iter_state));
  1855. if (err < 0)
  1856. return err;
  1857. s = ((struct seq_file *)file->private_data)->private;
  1858. s->family = afinfo->family;
  1859. s->udp_table = afinfo->udp_table;
  1860. return err;
  1861. }
  1862. EXPORT_SYMBOL(udp_seq_open);
  1863. /* ------------------------------------------------------------------------ */
  1864. int udp_proc_register(struct net *net, struct udp_seq_afinfo *afinfo)
  1865. {
  1866. struct proc_dir_entry *p;
  1867. int rc = 0;
  1868. afinfo->seq_ops.start = udp_seq_start;
  1869. afinfo->seq_ops.next = udp_seq_next;
  1870. afinfo->seq_ops.stop = udp_seq_stop;
  1871. p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net,
  1872. afinfo->seq_fops, afinfo);
  1873. if (!p)
  1874. rc = -ENOMEM;
  1875. return rc;
  1876. }
  1877. EXPORT_SYMBOL(udp_proc_register);
  1878. void udp_proc_unregister(struct net *net, struct udp_seq_afinfo *afinfo)
  1879. {
  1880. remove_proc_entry(afinfo->name, net->proc_net);
  1881. }
  1882. EXPORT_SYMBOL(udp_proc_unregister);
  1883. /* ------------------------------------------------------------------------ */
  1884. static void udp4_format_sock(struct sock *sp, struct seq_file *f,
  1885. int bucket, int *len)
  1886. {
  1887. struct inet_sock *inet = inet_sk(sp);
  1888. __be32 dest = inet->inet_daddr;
  1889. __be32 src = inet->inet_rcv_saddr;
  1890. __u16 destp = ntohs(inet->inet_dport);
  1891. __u16 srcp = ntohs(inet->inet_sport);
  1892. seq_printf(f, "%5d: %08X:%04X %08X:%04X"
  1893. " %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d%n",
  1894. bucket, src, srcp, dest, destp, sp->sk_state,
  1895. sk_wmem_alloc_get(sp),
  1896. sk_rmem_alloc_get(sp),
  1897. 0, 0L, 0,
  1898. from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
  1899. 0, sock_i_ino(sp),
  1900. atomic_read(&sp->sk_refcnt), sp,
  1901. atomic_read(&sp->sk_drops), len);
  1902. }
  1903. int udp4_seq_show(struct seq_file *seq, void *v)
  1904. {
  1905. if (v == SEQ_START_TOKEN)
  1906. seq_printf(seq, "%-127s\n",
  1907. " sl local_address rem_address st tx_queue "
  1908. "rx_queue tr tm->when retrnsmt uid timeout "
  1909. "inode ref pointer drops");
  1910. else {
  1911. struct udp_iter_state *state = seq->private;
  1912. int len;
  1913. udp4_format_sock(v, seq, state->bucket, &len);
  1914. seq_printf(seq, "%*s\n", 127 - len, "");
  1915. }
  1916. return 0;
  1917. }
  1918. static const struct file_operations udp_afinfo_seq_fops = {
  1919. .owner = THIS_MODULE,
  1920. .open = udp_seq_open,
  1921. .read = seq_read,
  1922. .llseek = seq_lseek,
  1923. .release = seq_release_net
  1924. };
  1925. /* ------------------------------------------------------------------------ */
  1926. static struct udp_seq_afinfo udp4_seq_afinfo = {
  1927. .name = "udp",
  1928. .family = AF_INET,
  1929. .udp_table = &udp_table,
  1930. .seq_fops = &udp_afinfo_seq_fops,
  1931. .seq_ops = {
  1932. .show = udp4_seq_show,
  1933. },
  1934. };
  1935. static int __net_init udp4_proc_init_net(struct net *net)
  1936. {
  1937. return udp_proc_register(net, &udp4_seq_afinfo);
  1938. }
  1939. static void __net_exit udp4_proc_exit_net(struct net *net)
  1940. {
  1941. udp_proc_unregister(net, &udp4_seq_afinfo);
  1942. }
  1943. static struct pernet_operations udp4_net_ops = {
  1944. .init = udp4_proc_init_net,
  1945. .exit = udp4_proc_exit_net,
  1946. };
  1947. int __init udp4_proc_init(void)
  1948. {
  1949. return register_pernet_subsys(&udp4_net_ops);
  1950. }
  1951. void udp4_proc_exit(void)
  1952. {
  1953. unregister_pernet_subsys(&udp4_net_ops);
  1954. }
  1955. #endif /* CONFIG_PROC_FS */
  1956. static __initdata unsigned long uhash_entries;
  1957. static int __init set_uhash_entries(char *str)
  1958. {
  1959. ssize_t ret;
  1960. if (!str)
  1961. return 0;
  1962. ret = kstrtoul(str, 0, &uhash_entries);
  1963. if (ret)
  1964. return 0;
  1965. if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN)
  1966. uhash_entries = UDP_HTABLE_SIZE_MIN;
  1967. return 1;
  1968. }
  1969. __setup("uhash_entries=", set_uhash_entries);
  1970. void __init udp_table_init(struct udp_table *table, const char *name)
  1971. {
  1972. unsigned int i;
  1973. table->hash = alloc_large_system_hash(name,
  1974. 2 * sizeof(struct udp_hslot),
  1975. uhash_entries,
  1976. 21, /* one slot per 2 MB */
  1977. 0,
  1978. &table->log,
  1979. &table->mask,
  1980. UDP_HTABLE_SIZE_MIN,
  1981. 64 * 1024);
  1982. table->hash2 = table->hash + (table->mask + 1);
  1983. for (i = 0; i <= table->mask; i++) {
  1984. INIT_HLIST_NULLS_HEAD(&table->hash[i].head, i);
  1985. table->hash[i].count = 0;
  1986. spin_lock_init(&table->hash[i].lock);
  1987. }
  1988. for (i = 0; i <= table->mask; i++) {
  1989. INIT_HLIST_NULLS_HEAD(&table->hash2[i].head, i);
  1990. table->hash2[i].count = 0;
  1991. spin_lock_init(&table->hash2[i].lock);
  1992. }
  1993. }
  1994. void __init udp_init(void)
  1995. {
  1996. unsigned long limit;
  1997. udp_table_init(&udp_table, "UDP");
  1998. limit = nr_free_buffer_pages() / 8;
  1999. limit = max(limit, 128UL);
  2000. sysctl_udp_mem[0] = limit / 4 * 3;
  2001. sysctl_udp_mem[1] = limit;
  2002. sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2;
  2003. sysctl_udp_rmem_min = SK_MEM_QUANTUM;
  2004. sysctl_udp_wmem_min = SK_MEM_QUANTUM;
  2005. }
  2006. struct sk_buff *skb_udp_tunnel_segment(struct sk_buff *skb,
  2007. netdev_features_t features)
  2008. {
  2009. struct sk_buff *segs = ERR_PTR(-EINVAL);
  2010. int mac_len = skb->mac_len;
  2011. int tnl_hlen = skb_inner_mac_header(skb) - skb_transport_header(skb);
  2012. __be16 protocol = skb->protocol;
  2013. netdev_features_t enc_features;
  2014. int outer_hlen;
  2015. if (unlikely(!pskb_may_pull(skb, tnl_hlen)))
  2016. goto out;
  2017. skb->encapsulation = 0;
  2018. __skb_pull(skb, tnl_hlen);
  2019. skb_reset_mac_header(skb);
  2020. skb_set_network_header(skb, skb_inner_network_offset(skb));
  2021. skb->mac_len = skb_inner_network_offset(skb);
  2022. skb->protocol = htons(ETH_P_TEB);
  2023. /* segment inner packet. */
  2024. enc_features = skb->dev->hw_enc_features & netif_skb_features(skb);
  2025. segs = skb_mac_gso_segment(skb, enc_features);
  2026. if (!segs || IS_ERR(segs))
  2027. goto out;
  2028. outer_hlen = skb_tnl_header_len(skb);
  2029. skb = segs;
  2030. do {
  2031. struct udphdr *uh;
  2032. int udp_offset = outer_hlen - tnl_hlen;
  2033. skb_reset_inner_headers(skb);
  2034. skb->encapsulation = 1;
  2035. skb->mac_len = mac_len;
  2036. skb_push(skb, outer_hlen);
  2037. skb_reset_mac_header(skb);
  2038. skb_set_network_header(skb, mac_len);
  2039. skb_set_transport_header(skb, udp_offset);
  2040. uh = udp_hdr(skb);
  2041. uh->len = htons(skb->len - udp_offset);
  2042. /* csum segment if tunnel sets skb with csum. */
  2043. if (protocol == htons(ETH_P_IP) && unlikely(uh->check)) {
  2044. struct iphdr *iph = ip_hdr(skb);
  2045. uh->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr,
  2046. skb->len - udp_offset,
  2047. IPPROTO_UDP, 0);
  2048. uh->check = csum_fold(skb_checksum(skb, udp_offset,
  2049. skb->len - udp_offset, 0));
  2050. if (uh->check == 0)
  2051. uh->check = CSUM_MANGLED_0;
  2052. } else if (protocol == htons(ETH_P_IPV6)) {
  2053. struct ipv6hdr *ipv6h = ipv6_hdr(skb);
  2054. u32 len = skb->len - udp_offset;
  2055. uh->check = ~csum_ipv6_magic(&ipv6h->saddr, &ipv6h->daddr,
  2056. len, IPPROTO_UDP, 0);
  2057. uh->check = csum_fold(skb_checksum(skb, udp_offset, len, 0));
  2058. if (uh->check == 0)
  2059. uh->check = CSUM_MANGLED_0;
  2060. skb->ip_summed = CHECKSUM_NONE;
  2061. }
  2062. skb->protocol = protocol;
  2063. } while ((skb = skb->next));
  2064. out:
  2065. return segs;
  2066. }