⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 udp.c

📁 linux 内核源代码
💻 C
📖 第 1 页 / 共 3 页
字号:
/* * 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 *		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 *	James Chapman		:	Add L2TP encapsulation type. * * *		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/igmp.h>#include <linux/in.h>#include <linux/errno.h>#include <linux/timer.h>#include <linux/mm.h>#include <linux/inet.h>#include <linux/netdevice.h>#include <net/tcp_states.h>#include <linux/skbuff.h>#include <linux/proc_fs.h>#include <linux/seq_file.h>#include <net/net_namespace.h>#include <net/icmp.h>#include <net/route.h>#include <net/checksum.h>#include <net/xfrm.h>#include "udp_impl.h"/* *	Snmp MIB for the UDP layer */DEFINE_SNMP_STAT(struct udp_mib, udp_statistics) __read_mostly;struct hlist_head udp_hash[UDP_HTABLE_SIZE];DEFINE_RWLOCK(udp_hash_lock);static inline int __udp_lib_lport_inuse(__u16 num,					const struct hlist_head udptable[]){	struct sock *sk;	struct hlist_node *node;	sk_for_each(sk, node, &udptable[num & (UDP_HTABLE_SIZE - 1)])		if (sk->sk_hash == num)			return 1;	return 0;}/** *  __udp_lib_get_port  -  UDP/-Lite port lookup for IPv4 and IPv6 * *  @sk:          socket struct in question *  @snum:        port number to look up *  @udptable:    hash list table, must be of UDP_HTABLE_SIZE *  @saddr_comp:  AF-dependent comparison of bound local IP addresses */int __udp_lib_get_port(struct sock *sk, unsigned short snum,		       struct hlist_head udptable[],		       int (*saddr_comp)(const struct sock *sk1,					 const struct sock *sk2 )    ){	struct hlist_node *node;	struct hlist_head *head;	struct sock *sk2;	int    error = 1;	write_lock_bh(&udp_hash_lock);	if (!snum) {		int i, low, high, remaining;		unsigned rover, best, best_size_so_far;		inet_get_local_port_range(&low, &high);		remaining = (high - low) + 1;		best_size_so_far = UINT_MAX;		best = rover = net_random() % remaining + low;		/* 1st pass: look for empty (or shortest) hash chain */		for (i = 0; i < UDP_HTABLE_SIZE; i++) {			int size = 0;			head = &udptable[rover & (UDP_HTABLE_SIZE - 1)];			if (hlist_empty(head))				goto gotit;			sk_for_each(sk2, node, head) {				if (++size >= best_size_so_far)					goto next;			}			best_size_so_far = size;			best = rover;		next:			/* fold back if end of range */			if (++rover > high)				rover = low + ((rover - low)					       & (UDP_HTABLE_SIZE - 1));		}		/* 2nd pass: find hole in shortest hash chain */		rover = best;		for (i = 0; i < (1 << 16) / UDP_HTABLE_SIZE; i++) {			if (! __udp_lib_lport_inuse(rover, udptable))				goto gotit;			rover += UDP_HTABLE_SIZE;			if (rover > high)				rover = low + ((rover - low)					       & (UDP_HTABLE_SIZE - 1));		}		/* All ports in use! */		goto fail;gotit:		snum = rover;	} else {		head = &udptable[snum & (UDP_HTABLE_SIZE - 1)];		sk_for_each(sk2, node, head)			if (sk2->sk_hash == snum                             &&			    sk2 != sk                                        &&			    (!sk2->sk_reuse        || !sk->sk_reuse)         &&			    (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if			     || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&			    (*saddr_comp)(sk, sk2)                             )				goto fail;	}	inet_sk(sk)->num = snum;	sk->sk_hash = snum;	if (sk_unhashed(sk)) {		head = &udptable[snum & (UDP_HTABLE_SIZE - 1)];		sk_add_node(sk, head);		sock_prot_inc_use(sk->sk_prot);	}	error = 0;fail:	write_unlock_bh(&udp_hash_lock);	return error;}int udp_get_port(struct sock *sk, unsigned short snum,			int (*scmp)(const struct sock *, const struct sock *)){	return  __udp_lib_get_port(sk, snum, udp_hash, scmp);}int ipv4_rcv_saddr_equal(const struct sock *sk1, const struct sock *sk2){	struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2);	return 	( !ipv6_only_sock(sk2)  &&		  (!inet1->rcv_saddr || !inet2->rcv_saddr ||		   inet1->rcv_saddr == inet2->rcv_saddr      ));}static inline int udp_v4_get_port(struct sock *sk, unsigned short snum){	return udp_get_port(sk, snum, ipv4_rcv_saddr_equal);}/* UDP is nearly always wildcards out the wazoo, it makes no sense to try * harder than this. -DaveM */static struct sock *__udp4_lib_lookup(__be32 saddr, __be16 sport,				      __be32 daddr, __be16 dport,				      int dif, struct hlist_head udptable[]){	struct sock *sk, *result = NULL;	struct hlist_node *node;	unsigned short hnum = ntohs(dport);	int badness = -1;	read_lock(&udp_hash_lock);	sk_for_each(sk, node, &udptable[hnum & (UDP_HTABLE_SIZE - 1)]) {		struct inet_sock *inet = inet_sk(sk);		if (sk->sk_hash == 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;			}		}	}	if (result)		sock_hold(result);	read_unlock(&udp_hash_lock);	return result;}static inline struct sock *udp_v4_mcast_next(struct sock *sk,					     __be16 loc_port, __be32 loc_addr,					     __be16 rmt_port, __be32 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_sock *inet = inet_sk(s);		if (s->sk_hash != 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 __udp4_lib_err(struct sk_buff *skb, u32 info, struct hlist_head udptable[]){	struct inet_sock *inet;	struct iphdr *iph = (struct iphdr*)skb->data;	struct udphdr *uh = (struct udphdr*)(skb->data+(iph->ihl<<2));	const int type = icmp_hdr(skb)->type;	const int code = icmp_hdr(skb)->code;	struct sock *sk;	int harderr;	int err;	sk = __udp4_lib_lookup(iph->daddr, uh->dest, iph->saddr, uh->source,			       skb->dev->ifindex, udptable		    );	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);}void udp_err(struct sk_buff *skb, u32 info){	return __udp4_lib_err(skb, info, udp_hash);}/* * Throw away all pending data and cancel the corking. Socket is locked. */static void udp_flush_pending_frames(struct sock *sk){	struct udp_sock *up = udp_sk(sk);	if (up->pending) {		up->len = 0;		up->pending = 0;		ip_flush_pending_frames(sk);	}}/** * 	udp4_hwcsum_outgoing  -  handle outgoing HW checksumming * 	@sk: 	socket we are sending on * 	@skb: 	sk_buff containing the filled-in UDP header * 	        (checksum field must be zeroed out) */static void udp4_hwcsum_outgoing(struct sock *sk, struct sk_buff *skb,				 __be32 src, __be32 dst, int len      ){	unsigned int offset;	struct udphdr *uh = udp_hdr(skb);	__wsum csum = 0;	if (skb_queue_len(&sk->sk_write_queue) == 1) {		/*		 * Only one fragment on the socket.		 */		skb->csum_start = skb_transport_header(skb) - skb->head;		skb->csum_offset = offsetof(struct udphdr, check);		uh->check = ~csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, 0);	} else {		/*		 * 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		 */		offset = skb_transport_offset(skb);		skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);		skb->ip_summed = CHECKSUM_NONE;		skb_queue_walk(&sk->sk_write_queue, skb) {			csum = csum_add(csum, skb->csum);		}		uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum);		if (uh->check == 0)			uh->check = CSUM_MANGLED_0;	}}/* * Push out all pending data as one UDP datagram. Socket is locked. */static int udp_push_pending_frames(struct sock *sk){	struct udp_sock  *up = udp_sk(sk);	struct inet_sock *inet = inet_sk(sk);	struct flowi *fl = &inet->cork.fl;	struct sk_buff *skb;	struct udphdr *uh;	int err = 0;	__wsum csum = 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 = udp_hdr(skb);	uh->source = fl->fl_ip_sport;	uh->dest = fl->fl_ip_dport;	uh->len = htons(up->len);	uh->check = 0;	if (up->pcflag)  				 /*     UDP-Lite      */		csum  = udplite_csum_outgoing(sk, skb);	else if (sk->sk_no_check == UDP_CSUM_NOXMIT) {   /* UDP csum disabled */		skb->ip_summed = CHECKSUM_NONE;		goto send;	} else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */		udp4_hwcsum_outgoing(sk, skb, fl->fl4_src,fl->fl4_dst, up->len);		goto send;	} else						 /*   `normal' UDP    */		csum = udp_csum_outgoing(sk, skb);	/* add protocol-dependent pseudo-header */	uh->check = csum_tcpudp_magic(fl->fl4_src, fl->fl4_dst, up->len,				      sk->sk_protocol, csum             );	if (uh->check == 0)		uh->check = CSUM_MANGLED_0;send:	err = ip_push_pending_frames(sk);out:	up->len = 0;	up->pending = 0;	if (!err)		UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS, up->pcflag);	return err;}int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,		size_t len){	struct inet_sock *inet = inet_sk(sk);	struct udp_sock *up = udp_sk(sk);	int ulen = len;	struct ipcm_cookie ipc;	struct rtable *rt = NULL;	int free = 0;	int connected = 0;	__be32 daddr, faddr, saddr;	__be16 dport;	u8  tos;	int err, is_udplite = up->pcflag;	int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;	int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);	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) {		/*		 * There are pending frames.		 * The socket lock must be held while it's corked.		 */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -