📄 udp.c
字号:
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * The User Datagram Protocol (UDP). * * Version: $Id: udp.c,v 1.102 2002/02/01 22:01:04 davem Exp $ * * Authors: Ross Biro, <bir7@leland.Stanford.Edu> * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Alan Cox, <Alan.Cox@linux.org> * Hirokazu Takahashi, <taka@valinux.co.jp> * * Fixes: * Alan Cox : verify_area() calls * Alan Cox : stopped close while in use off icmp * messages. Not a fix but a botch that * for udp at least is 'valid'. * Alan Cox : Fixed icmp handling properly * Alan Cox : Correct error for oversized datagrams * Alan Cox : Tidied select() semantics. * Alan Cox : udp_err() fixed properly, also now * select and read wake correctly on errors * Alan Cox : udp_send verify_area moved to avoid mem leak * Alan Cox : UDP can count its memory * Alan Cox : send to an unknown connection causes * an ECONNREFUSED off the icmp, but * does NOT close. * Alan Cox : Switched to new sk_buff handlers. No more backlog! * Alan Cox : Using generic datagram code. Even smaller and the PEEK * bug no longer crashes it. * Fred Van Kempen : Net2e support for sk->broadcast. * Alan Cox : Uses skb_free_datagram * Alan Cox : Added get/set sockopt support. * Alan Cox : Broadcasting without option set returns EACCES. * Alan Cox : No wakeup calls. Instead we now use the callbacks. * Alan Cox : Use ip_tos and ip_ttl * Alan Cox : SNMP Mibs * Alan Cox : MSG_DONTROUTE, and 0.0.0.0 support. * Matt Dillon : UDP length checks. * Alan Cox : Smarter af_inet used properly. * Alan Cox : Use new kernel side addressing. * Alan Cox : Incorrect return on truncated datagram receive. * Arnt Gulbrandsen : New udp_send and stuff * Alan Cox : Cache last socket * Alan Cox : Route cache * Jon Peatfield : Minor efficiency fix to sendto(). * Mike Shaver : RFC1122 checks. * Alan Cox : Nonblocking error fix. * Willy Konynenberg : Transparent proxying support. * Mike McLagan : Routing by source * David S. Miller : New socket lookup architecture. * Last socket cache retained as it * does have a high hit rate. * Olaf Kirch : Don't linearise iovec on sendmsg. * Andi Kleen : Some cleanups, cache destination entry * for connect. * Vitaly E. Lavrov : Transparent proxy revived after year coma. * Melvin Smith : Check msg_name not msg_namelen in sendto(), * return ENOTCONN for unconnected sockets (POSIX) * Janos Farkas : don't deliver multi/broadcasts to a different * bound-to-device socket * Hirokazu Takahashi : HW checksumming for outgoing UDP * datagrams. * Hirokazu Takahashi : sendfile() on UDP works now. * Arnaldo C. Melo : convert /proc/net/udp to seq_file * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which * Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind * a single port at the same time. * Derek Atkins <derek@ihtfp.com>: Add Encapulation Support * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <asm/system.h>#include <asm/uaccess.h>#include <asm/ioctls.h>#include <linux/types.h>#include <linux/fcntl.h>#include <linux/module.h>#include <linux/socket.h>#include <linux/sockios.h>#include <linux/in.h>#include <linux/errno.h>#include <linux/timer.h>#include <linux/mm.h>#include <linux/config.h>#include <linux/inet.h>#include <linux/ipv6.h>#include <linux/netdevice.h>#include <net/snmp.h>#include <net/tcp.h>#include <net/protocol.h>#include <linux/skbuff.h>#include <linux/proc_fs.h>#include <linux/seq_file.h>#include <net/sock.h>#include <net/udp.h>#include <net/icmp.h>#include <net/route.h>#include <net/inet_common.h>#include <net/checksum.h>#include <net/xfrm.h>/* * Snmp MIB for the UDP layer */DEFINE_SNMP_STAT(struct udp_mib, udp_statistics);struct hlist_head udp_hash[UDP_HTABLE_SIZE];rwlock_t udp_hash_lock = RW_LOCK_UNLOCKED;/* Shared by v4/v6 udp. */int udp_port_rover;static int udp_v4_get_port(struct sock *sk, unsigned short snum){ struct hlist_node *node; struct sock *sk2; struct inet_opt *inet = inet_sk(sk); write_lock_bh(&udp_hash_lock); if (snum == 0) { int best_size_so_far, best, result, i; if (udp_port_rover > sysctl_local_port_range[1] || udp_port_rover < sysctl_local_port_range[0]) udp_port_rover = sysctl_local_port_range[0]; best_size_so_far = 32767; best = result = udp_port_rover; for (i = 0; i < UDP_HTABLE_SIZE; i++, result++) { struct hlist_head *list; int size; list = &udp_hash[result & (UDP_HTABLE_SIZE - 1)]; if (hlist_empty(list)) { if (result > sysctl_local_port_range[1]) result = sysctl_local_port_range[0] + ((result - sysctl_local_port_range[0]) & (UDP_HTABLE_SIZE - 1)); goto gotit; } size = 0; sk_for_each(sk2, node, list) if (++size >= best_size_so_far) goto next; best_size_so_far = size; best = result; next:; } result = best; for(i = 0; i < (1 << 16) / UDP_HTABLE_SIZE; i++, result += UDP_HTABLE_SIZE) { if (result > sysctl_local_port_range[1]) result = sysctl_local_port_range[0] + ((result - sysctl_local_port_range[0]) & (UDP_HTABLE_SIZE - 1)); if (!udp_lport_inuse(result)) break; } if (i >= (1 << 16) / UDP_HTABLE_SIZE) goto fail;gotit: udp_port_rover = snum = result; } else { sk_for_each(sk2, node, &udp_hash[snum & (UDP_HTABLE_SIZE - 1)]) { struct inet_opt *inet2 = inet_sk(sk2); if (inet2->num == snum && sk2 != sk && !ipv6_only_sock(sk2) && (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) && (!inet2->rcv_saddr || !inet->rcv_saddr || inet2->rcv_saddr == inet->rcv_saddr) && (!sk2->sk_reuse || !sk->sk_reuse)) goto fail; } } inet->num = snum; if (sk_unhashed(sk)) { struct hlist_head *h = &udp_hash[snum & (UDP_HTABLE_SIZE - 1)]; sk_add_node(sk, h); sock_prot_inc_use(sk->sk_prot); } write_unlock_bh(&udp_hash_lock); return 0;fail: write_unlock_bh(&udp_hash_lock); return 1;}static void udp_v4_hash(struct sock *sk){ BUG();}static void udp_v4_unhash(struct sock *sk){ write_lock_bh(&udp_hash_lock); if (sk_del_node_init(sk)) { inet_sk(sk)->num = 0; sock_prot_dec_use(sk->sk_prot); } write_unlock_bh(&udp_hash_lock);}/* UDP is nearly always wildcards out the wazoo, it makes no sense to try * harder than this. -DaveM */struct sock *udp_v4_lookup_longway(u32 saddr, u16 sport, u32 daddr, u16 dport, int dif){ struct sock *sk, *result = NULL; struct hlist_node *node; unsigned short hnum = ntohs(dport); int badness = -1; sk_for_each(sk, node, &udp_hash[hnum & (UDP_HTABLE_SIZE - 1)]) { struct inet_opt *inet = inet_sk(sk); if (inet->num == hnum && !ipv6_only_sock(sk)) { int score = (sk->sk_family == PF_INET ? 1 : 0); if (inet->rcv_saddr) { if (inet->rcv_saddr != daddr) continue; score+=2; } if (inet->daddr) { if (inet->daddr != saddr) continue; score+=2; } if (inet->dport) { if (inet->dport != sport) continue; score+=2; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) continue; score+=2; } if(score == 9) { result = sk; break; } else if(score > badness) { result = sk; badness = score; } } } return result;}__inline__ struct sock *udp_v4_lookup(u32 saddr, u16 sport, u32 daddr, u16 dport, int dif){ struct sock *sk; read_lock(&udp_hash_lock); sk = udp_v4_lookup_longway(saddr, sport, daddr, dport, dif); if (sk) sock_hold(sk); read_unlock(&udp_hash_lock); return sk;}static inline struct sock *udp_v4_mcast_next(struct sock *sk, u16 loc_port, u32 loc_addr, u16 rmt_port, u32 rmt_addr, int dif){ struct hlist_node *node; struct sock *s = sk; unsigned short hnum = ntohs(loc_port); sk_for_each_from(s, node) { struct inet_opt *inet = inet_sk(s); if (inet->num != hnum || (inet->daddr && inet->daddr != rmt_addr) || (inet->dport != rmt_port && inet->dport) || (inet->rcv_saddr && inet->rcv_saddr != loc_addr) || ipv6_only_sock(s) || (s->sk_bound_dev_if && s->sk_bound_dev_if != dif)) continue; if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif)) continue; goto found; } s = NULL;found: return s;}/* * This routine is called by the ICMP module when it gets some * sort of error condition. If err < 0 then the socket should * be closed and the error returned to the user. If err > 0 * it's just the icmp type << 8 | icmp code. * Header points to the ip header of the error packet. We move * on past this. Then (as it used to claim before adjustment) * header points to the first 8 bytes of the udp header. We need * to find the appropriate port. */void udp_err(struct sk_buff *skb, u32 info){ struct inet_opt *inet; struct iphdr *iph = (struct iphdr*)skb->data; struct udphdr *uh = (struct udphdr*)(skb->data+(iph->ihl<<2)); int type = skb->h.icmph->type; int code = skb->h.icmph->code; struct sock *sk; int harderr; int err; sk = udp_v4_lookup(iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex); if (sk == NULL) { ICMP_INC_STATS_BH(ICMP_MIB_INERRORS); return; /* No socket for error */ } err = 0; harderr = 0; inet = inet_sk(sk); switch (type) { default: case ICMP_TIME_EXCEEDED: err = EHOSTUNREACH; break; case ICMP_SOURCE_QUENCH: goto out; case ICMP_PARAMETERPROB: err = EPROTO; harderr = 1; break; case ICMP_DEST_UNREACH: if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */ if (inet->pmtudisc != IP_PMTUDISC_DONT) { err = EMSGSIZE; harderr = 1; break; } goto out; } err = EHOSTUNREACH; if (code <= NR_ICMP_UNREACH) { harderr = icmp_err_convert[code].fatal; err = icmp_err_convert[code].errno; } break; } /* * RFC1122: OK. Passes ICMP errors back to application, as per * 4.1.3.3. */ if (!inet->recverr) { if (!harderr || sk->sk_state != TCP_ESTABLISHED) goto out; } else { ip_icmp_error(sk, skb, err, uh->dest, info, (u8*)(uh+1)); } sk->sk_err = err; sk->sk_error_report(sk);out: sock_put(sk);}/* * Throw away all pending data and cancel the corking. Socket is locked. */static void udp_flush_pending_frames(struct sock *sk){ struct udp_opt *up = udp_sk(sk); if (up->pending) { up->len = 0; up->pending = 0; ip_flush_pending_frames(sk); }}/* * Push out all pending data as one UDP datagram. Socket is locked. */static int udp_push_pending_frames(struct sock *sk, struct udp_opt *up){ struct inet_opt *inet = inet_sk(sk); struct flowi *fl = &inet->cork.fl; struct sk_buff *skb; struct udphdr *uh; int err = 0; /* Grab the skbuff where UDP header space exists. */ if ((skb = skb_peek(&sk->sk_write_queue)) == NULL) goto out; /* * Create a UDP header */ uh = skb->h.uh; uh->source = fl->fl_ip_sport; uh->dest = fl->fl_ip_dport; uh->len = htons(up->len); uh->check = 0; if (sk->sk_no_check == UDP_CSUM_NOXMIT) { skb->ip_summed = CHECKSUM_NONE; goto send; } if (skb_queue_len(&sk->sk_write_queue) == 1) { /* * Only one fragment on the socket. */ if (skb->ip_summed == CHECKSUM_HW) { skb->csum = offsetof(struct udphdr, check); uh->check = ~csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst, up->len, IPPROTO_UDP, 0); } else { skb->csum = csum_partial((char *)uh, sizeof(struct udphdr), skb->csum); uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst, up->len, IPPROTO_UDP, skb->csum); if (uh->check == 0) uh->check = -1; } } else { unsigned int csum = 0; /* * HW-checksum won't work as there are two or more * fragments on the socket so that all csums of sk_buffs * should be together. */ if (skb->ip_summed == CHECKSUM_HW) { int offset = (unsigned char *)uh - skb->data; skb->csum = skb_checksum(skb, offset, skb->len - offset, 0); skb->ip_summed = CHECKSUM_NONE; } else { skb->csum = csum_partial((char *)uh, sizeof(struct udphdr), skb->csum); } skb_queue_walk(&sk->sk_write_queue, skb) { csum = csum_add(csum, skb->csum); } uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst, up->len, IPPROTO_UDP, csum); if (uh->check == 0) uh->check = -1; }send: err = ip_push_pending_frames(sk);out: up->len = 0; up->pending = 0; return err;}static unsigned short udp_check(struct udphdr *uh, int len, unsigned long saddr, unsigned long daddr, unsigned long base){ return(csum_tcpudp_magic(saddr, daddr, len, IPPROTO_UDP, base));}int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len){ struct inet_opt *inet = inet_sk(sk); struct udp_opt *up = udp_sk(sk); int ulen = len; struct ipcm_cookie ipc; struct rtable *rt = NULL; int free = 0; int connected = 0; u32 daddr, faddr, saddr; u16 dport; u8 tos; int err; int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; if (len > 0xFFFF) return -EMSGSIZE; /* * Check the flags. */ if (msg->msg_flags&MSG_OOB) /* Mirror BSD error message compatibility */ return -EOPNOTSUPP; ipc.opt = NULL; if (up->pending) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -