udp.c 59 KB

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