CSDN博客

img collide

IP包的生成和发送接口

发表于2004/10/8 9:55:00  5543人阅读

分类: linux network

著名软件中国镜像: Apache| Php| Debian| Mysql| Proftp| Qmail| Samba| Squid| Xfree86| CPAN| LDP| GNU|

中国Linux论坛首页 技术论坛| 文章荟萃| 藏经阁| 会员信箱| 项目计划| 在线调查| 软件仓库| 关于本站|

Linux 高级应用
   >> Linux内核技术
此话题阅读次数: 3137

  打印
opera
(enthusiast)
05/22/01 14:00
IP包的生成和发送接口  


IP包的生成和发送接口
====================
(1) Linux内核中有3种基本的IP包生成器, 它们分别为ip_build_xmit(), ip_queue_xmit(),
ip_build_and_send_pkt(). ip_build_and_send_pkt()是一简单的IP包头封装接口,
它接照输入包的路由添加一个IP包头后直接输出,不进行分片处理, 用于tcp_v4_send_synack()中.
ip_send_reply()是基于ip_build_xmit()的一个函数,
用于tcp_v4_send_ack()和tcp_v4_send_reset()中.

(2) ip_build_xmit()使用用户定义的回调函数直接读取用户数据片段生成IP包输出.
如果需要分片,ip_build_xmit()按照最后一个片段到第一个片段的顺序来生成IP包,
这是因为第一个IP包片段的数据区可能包含对整个IP包数据区的校验码,
在回调函数中用户可能会计算输出数据的校验码,
采用从后向前的输出顺序可使校验码自然地写到第一个片段中.

(3) ip_queue_xmit()完成面向连接套接字输出包的路由和IP包头封装. 当套接字处于连接状态时,
所有从套接字发出的包都具有确定的路由, 无需为每一个输出包查询它的目的入口,
可将套接字直接绑定到路由入口上, 这由套接字的目的缓冲指针(dst_cache)来完成.
ip_queue_xmit()首先为输入包建立IP包头, 经过本地包过滤器后,
再将IP包分片输出(ip_fragment), 如果需要的话.

(4) IP包生成器的输出经过本地包过滤器后输入包的路由入口, 对于点播地址来说,
输入到IP输出器中(ip_output); 对于广播或同播地址来说, 输入到IP同播输出器(ip_mc_output).
在IP输出器中, 再经过路由后过滤器,
进入路由的"邻居"入口(dst->neighbour->output)或硬件帧头缓冲入口(dst->hh->hh_output).
邻居是指与主机自已在网络接口设备层次上直达的相邻主机.
邻居负责解析输出包的硬件投送地址, 将包投递给相邻的目的主机或网关主机.
当邻居成功解析包的硬件投送地址时, 将在包的目的入口上创建硬件帧头缓冲结构(dst->hh),
使得后继包可以直接使用组装好的帧头, 直接将包传递给包调度器(dev_queue_xmit).
包调度器按照包的优先级进行重排, 最后将包提交给设备驱动程序发送(dev->hard_start_xmit).


IP包生成接口
------------
; net/ipv4/ip_output.c:

int sysctl_ip_default_ttl = IPDEFTTL; 缺省的IP包生存期为64

/*
* Add an ip header to a skbuff and send it out.
*/
int ip_build_and_send_pkt(struct sk_buff *skb, struct sock *sk,
对包的数据体添加IP头后直接输出
u32 saddr, u32 daddr, struct ip_options *opt)
{
struct rtable *rt = (struct rtable *)skb->dst;
struct iphdr *iph;

/* Build the IP header. */
if (opt)
iph=(struct iphdr *)skb_push(skb,sizeof(struct iphdr) + opt->optlen);
else
iph=(struct iphdr *)skb_push(skb,sizeof(struct iphdr));

iph->version = 4;
iph->ihl = 5;
iph->tos = sk->protinfo.af_inet.tos;
iph->frag_off = 0;
if (ip_dont_fragment(sk, &rt->u.dst)) 如果IP包的目的入口禁止分片
iph->frag_off |= htons(IP_DF);
iph->ttl = sk->protinfo.af_inet.ttl; 取套接字协议选项中的生存期
iph->daddr = rt->rt_dst; 取IP包路由的目的地址
iph->saddr = rt->rt_src; 取IP包路由的源地址
iph->protocol = sk->protocol; 取套接字IP协议代码
iph->tot_len = htons(skb->len); IP包总长度
ip_select_ident(iph, &rt->u.dst); 为IP包分配标识号, 禁止分片的IP包标识为零
skb->nh.iph = iph;

if (opt && opt->optlen) {
iph->ihl += opt->optlen>>2;
ip_options_build(skb, opt, daddr, rt, 0); 设置IP选项区
}
ip_send_check(iph); 设置IP包头的校验和

/* Send it out. */
return NF_HOOK(PF_INET, NF_IP_LOCAL_OUT, skb, NULL, rt->u.dst.dev,
output_maybe_reroute); 过滤输出并且目的路径可能会被改变
}

int ip_build_xmit(struct sock *sk,
int getfrag (const void *,
char *,
unsigned int,
unsigned int), 取数据片段的函数指针
const void *frag, 以上函数的调用参数
unsigned length,
struct ipcm_cookie *ipc, IP包配置信息
struct rtable *rt,
int flags) 从用户数据建立IP包
{
int err;
struct sk_buff *skb;
int df;
struct iphdr *iph;

/*
* Try the simple case first. This leaves fragmented frames, and by
* choice RAW frames within 20 bytes of maximum size(rare) to the long path
*/

if (!sk->protinfo.af_inet.hdrincl) { 如果IP包头不由用户创建
length += sizeof(struct iphdr); 取IP包总长

/*
* Check for slow path.
*/
if (length > rt->u.dst.pmtu || ipc->opt != NULL) 如果包长度大于目的入口的最大片断长
return ip_build_xmit_slow(sk,getfrag,frag,length,ipc,rt,flags);
} else {
if (length > rt->u.dst.dev->mtu) { 如果包长大于目的入口设备的最大片段长
ip_local_error(sk, EMSGSIZE, rt->rt_dst, sk->dport, rt->u.dst.dev->mtu);
return -EMSGSIZE;
}
}
if (flags&MSG_PROBE) 测试操作
goto out;

/*
* Do path mtu discovery if needed.
*/
df = 0;
if (ip_dont_fragment(sk, &rt->u.dst)) 如果禁止分片
df = htons(IP_DF);

/*
* Fast path for unfragmented frames without options.
*/
{
int hh_len = (rt->u.dst.dev->hard_header_len + 15)&~15;

skb = sock_alloc_send_skb(sk, length+hh_len+15,
0, flags&MSG_DONTWAIT, &err); 为套接字分配发送包
if(skb==NULL)
goto error;
skb_reserve(skb, hh_len); 保留硬件帧头空间
}

skb->priority = sk->priority; 取套接字的优先级
skb->dst = dst_clone(&rt->u.dst); 取路由的目的入口

skb->nh.iph = iph = (struct iphdr *)skb_put(skb, length);

if(!sk->protinfo.af_inet.hdrincl) {
iph->version=4;
iph->ihl=5;
iph->tos=sk->protinfo.af_inet.tos;
iph->tot_len = htons(length);
iph->frag_off = df;
iph->ttl=sk->protinfo.af_inet.mc_ttl;
ip_select_ident(iph, &rt->u.dst);
if (rt->rt_type != RTN_MULTICAST)
iph->ttl=sk->protinfo.af_inet.ttl;
iph->protocol=sk->protocol;
iph->saddr=rt->rt_src;
iph->daddr=rt->rt_dst;
iph->check=0;
iph->check = ip_fast_csum((unsigned char *)iph, iph->ihl);
err = getfrag(frag, ((char *)iph)+iph->ihl*4,0, length-iph->ihl*4);
; 读取用户一片数据
}
else 如果IP包头由用户创建, 直接将用户数据读入IP头所在位置
err = getfrag(frag, (void *)iph, 0, length);

if (err)
goto error_fault;

err = NF_HOOK(PF_INET, NF_IP_LOCAL_OUT, skb, NULL, rt->u.dst.dev,
output_maybe_reroute);
if (err > 0)
err = sk->protinfo.af_inet.recverr ? net_xmit_errno(err) : 0;
if (err)
goto error;
out:
return 0;

error_fault:
err = -EFAULT;
kfree_skb(skb);
error:
IP_INC_STATS(IpOutDiscards);
return err;
}
static int ip_build_xmit_slow(struct sock *sk,
int getfrag (const void *,
char *,
unsigned int,
unsigned int),
const void *frag,
unsigned length,
struct ipcm_cookie *ipc,
struct rtable *rt,
int flags) 建立IP选项区或者分片输出
{
unsigned int fraglen, maxfraglen, fragheaderlen;
int err;
int offset, mf;
int mtu;
u16 id = 0;

int hh_len = (rt->u.dst.dev->hard_header_len + 15)&~15;
int nfrags=0;
struct ip_options *opt = ipc->opt;
int df = 0;

mtu = rt->u.dst.pmtu;
if (ip_dont_fragment(sk, &rt->u.dst))
df = htons(IP_DF);

length -= sizeof(struct iphdr);

if (opt) {
fragheaderlen = sizeof(struct iphdr) + opt->optlen;
maxfraglen = ((mtu-sizeof(struct iphdr)-opt->optlen) & ~7) + fragheaderlen;
} else {
fragheaderlen = sizeof(struct iphdr);

/*
* Fragheaderlen is the size of 'overhead' on each buffer. Now work
* out the size of the frames to send.
*/

maxfraglen = ((mtu-sizeof(struct iphdr)) & ~7) + fragheaderlen;
} 求最大IP包长

if (length + fragheaderlen > 0xFFFF) {
ip_local_error(sk, EMSGSIZE, rt->rt_dst, sk->dport, mtu);
return -EMSGSIZE;
}

/*
* Start at the end of the frame by handling the remainder.
*/

offset = length - (length % (maxfraglen - fragheaderlen));
取最后一个片段的数据偏移量

/*
* Amount of memory to allocate for final fragment.
*/

fraglen = length - offset + fragheaderlen; 求取后一个片段IP包全长

if (length-offset==0) { 如果用户数据恰好是最大单片数据长度的整数倍
fraglen = maxfraglen;
offset -= maxfraglen-fragheaderlen;
}

/*
* The last fragment will not have MF (more fragments) set.
*/

mf = 0;

/*
* Don't fragment packets for path mtu discovery.
*/

if (offset > 0 && sk->protinfo.af_inet.pmtudisc==IP_PMTUDISC_DO) {
ip_local_error(sk, EMSGSIZE, rt->rt_dst, sk->dport, mtu);
return -EMSGSIZE;
}
if (flags&MSG_PROBE)
goto out;

/*
* Begin outputting the bytes.
*/

do {
char *data;
struct sk_buff * skb;

/*
* Get the memory we require with some space left for alignment.
*/

skb = sock_alloc_send_skb(sk, fraglen+hh_len+15, 0, flags&MSG_DONTWAIT, &err);
if (skb == NULL)
goto error;

/*
* Fill in the control structures
*/

skb->priority = sk->priority;
skb->dst = dst_clone(&rt->u.dst);
skb_reserve(skb, hh_len);

/*
* Find where to start putting bytes.
*/

data = skb_put(skb, fraglen);
skb->nh.iph = (struct iphdr *)data;

/*
* Only write IP header onto non-raw packets
*/

{
struct iphdr *iph = (struct iphdr *)data;

iph->version = 4;
iph->ihl = 5;
if (opt) {
iph->ihl += opt->optlen>>2;
ip_options_build(skb, opt,
ipc->addr, rt, offset);
}
iph->tos = sk->protinfo.af_inet.tos;
iph->tot_len = htons(fraglen - fragheaderlen + iph->ihl*4);
iph->frag_off = htons(offset>>3)|mf|df;
iph->id = id;
if (!mf) {
if (offset || !df) {
/* Select an unpredictable ident only
* for packets without DF or having
* been fragmented.
*/
__ip_select_ident(iph, &rt->u.dst);
id = iph->id;
}

/*
* Any further fragments will have MF set.
*/
mf = htons(IP_MF);
}
if (rt->rt_type == RTN_MULTICAST)
iph->ttl = sk->protinfo.af_inet.mc_ttl;
else
iph->ttl = sk->protinfo.af_inet.ttl;
iph->protocol = sk->protocol;
iph->check = 0;
iph->saddr = rt->rt_src;
iph->daddr = rt->rt_dst;
iph->check = ip_fast_csum((unsigned char *)iph, iph->ihl);
data += iph->ihl*4;
}

/*
* User data callback
*/

if (getfrag(frag, data, offset, fraglen-fragheaderlen)) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}

offset -= (maxfraglen-fragheaderlen); 片段从后向前进行分割, 是为了方便TCP包的校验
fraglen = maxfraglen;

nfrags++;

err = NF_HOOK(PF_INET, NF_IP_LOCAL_OUT, skb, NULL,
skb->dst->dev, output_maybe_reroute);
if (err) {
if (err > 0)
err = sk->protinfo.af_inet.recverr ? net_xmit_errno(err) : 0;
if (err)
goto error;
}
} while (offset >= 0);

if (nfrags>1)
ip_statistics[smp_processor_id()*2 + !in_softirq()].IpFragCreates += nfrags;
out:
return 0;

error:
IP_INC_STATS(IpOutDiscards);
if (nfrags>1)
ip_statistics[smp_processor_id()*2 + !in_softirq()].IpFragCreates += nfrags;
return err;
}

/*
* Generic function to send a packet as reply to another packet.
* Used to send TCP resets so far. ICMP should use this function too.
*
* Should run single threaded per socket because it uses the sock
* structure to pass arguments.
*/
void ip_send_reply(struct sock *sk, struct sk_buff *skb, struct ip_reply_arg *arg,
unsigned int len)
{
struct {
struct ip_options opt;
char data[40]; 存放IP选项块
} replyopts;
struct ipcm_cookie ipc;
u32 daddr;
struct rtable *rt = (struct rtable*)skb->dst;

if (ip_options_echo(&replyopts.opt, skb)) 将包skb的IP选项刷新到replyopts结构中
return;

daddr = ipc.addr = rt->rt_src;
ipc.opt = NULL;

if (replyopts.opt.optlen) {
ipc.opt = &replyopts.opt;

if (ipc.opt->srr)
daddr = replyopts.opt.faddr;
}

if (ip_route_output(&rt, daddr, rt->rt_spec_dst, RT_TOS(skb->nh.iph->tos), 0))
return;

/* And let IP do all the hard work.

This chunk is not reenterable, hence spinlock.
Note that it uses the fact, that this function is called
with locally disabled BH and that sk cannot be already spinlocked.
*/
bh_lock_sock(sk);
sk->protinfo.af_inet.tos = skb->nh.iph->tos;
sk->priority = skb->priority;
sk->protocol = skb->nh.iph->protocol;
ip_build_xmit(sk, ip_reply_glue_bits, arg, len, &ipc, rt, MSG_DONTWAIT);
bh_unlock_sock(sk);

ip_rt_put(rt);
}
struct ip_reply_arg {
struct iovec iov[2];
int n_iov; /* redundant */
u32 csum;
int csumoffset; /* u16 offset of csum in iov[0].iov_base */
/* -1 if not needed */
};
/*
* Fetch data from kernel space and fill in checksum if needed.
*/
static int ip_reply_glue_bits(const void *dptr, char *to, unsigned int offset,
unsigned int fraglen)
{
struct ip_reply_arg *dp = (struct ip_reply_arg*)dptr;
u16 *pktp = (u16 *)to;
struct iovec *iov;
int len;
int hdrflag = 1;

iov = &dp->iov[0];
if (offset >= iov->iov_len) {
offset -= iov->iov_len;
iov++;
hdrflag = 0;
}
len = iov->iov_len - offset;
if (fraglen > len) { /* overlapping. */
dp->csum = csum_partial_copy_nocheck(iov->iov_base+offset, to, len,
dp->csum);
offset = 0;
fraglen -= len;
to += len;
iov++;
}

dp->csum = csum_partial_copy_nocheck(iov->iov_base+offset, to, fraglen,
dp->csum);

if (hdrflag && dp->csumoffset)
*(pktp + dp->csumoffset) = csum_fold(dp->csum); /* fill in checksum */
return 0;
}

int ip_queue_xmit(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
struct ip_options *opt = sk->protinfo.af_inet.opt;
struct rtable *rt;
struct iphdr *iph;

/* Make sure we can route this packet. */
rt = (struct rtable *)__sk_dst_check(sk, 0); 取套接字所缓冲的发送包的目的路由入口
if (rt == NULL) { 如果尚未缓冲
u32 daddr;

/* Use correct destination address if we have options. */
daddr = sk->daddr; 取套接字的对端地址作为目的地址
if(opt && opt->srr) 如果具有信源路由选项
daddr = opt->faddr; 取信源路由的转发地址作为目的地址

/* If this fails, retransmit mechanism of transport layer will
* keep trying until route appears or the connection times itself
* out.
*/
if (ip_route_output(&rt, daddr, sk->saddr,
RT_TOS(sk->protinfo.af_inet.tos) | RTO_CONN | sk->localroute,
sk->bound_dev_if)) 查询目的地址的路由目的入口
goto no_route;
__sk_dst_set(sk, &rt->u.dst); 将该路由入口缓冲到套接字上
}
skb->dst = dst_clone(&rt->u.dst); 将路由入口绑定到发送包

if (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway)
goto no_route; 如果是指定严格信源路由并且其转发地址不等于网关地址,则操作失败

/* OK, we know where to send it, allocate and build IP header. */
iph = (struct iphdr *) skb_push(skb, sizeof(struct iphdr) + (opt ? opt->optlen :
0));
*((__u16 *)iph) = htons((4 << 12) | (5 << 8) | (sk->protinfo.af_inet.tos & 0xff));
iph->tot_len = htons(skb->len);
iph->frag_off = 0;
iph->ttl = sk->protinfo.af_inet.ttl;
iph->protocol = sk->protocol;
iph->saddr = rt->rt_src;
iph->daddr = rt->rt_dst;
skb->nh.iph = iph;
/* Transport layer set skb->h.foo itself. */

if(opt && opt->optlen) { 建立IP选项区
iph->ihl += opt->optlen >> 2;
ip_options_build(skb, opt, sk->daddr, rt, 0);
}

return NF_HOOK(PF_INET, NF_IP_LOCAL_OUT, skb, NULL, rt->u.dst.dev,
ip_queue_xmit2); 过滤输出

no_route:
IP_INC_STATS(IpOutNoRoutes);
kfree_skb(skb);
return -EHOSTUNREACH;
}

/* Queues a packet to be sent, and starts the transmitter if necessary.
* This routine also needs to put in the total length and compute the
* checksum. We use to do this in two stages, ip_build_header() then
* this, but that scheme created a mess when routes disappeared etc.
* So we do it all here, and the TCP send engine has been changed to
* match. (No more unroutable FIN disasters, etc. wheee...) This will
* most likely make other reliable transport layers above IP easier
* to implement under Linux.
*/
static inline int ip_queue_xmit2(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
struct rtable *rt = (struct rtable *)skb->dst;
struct net_device *dev;
struct iphdr *iph = skb->nh.iph;

dev = rt->u.dst.dev;

/* This can happen when the transport layer has segments queued
* with a cached route, and by the time we get here things are
* re-routed to a device with a different MTU than the original
* device. Sick, but we must cover it.
*/
if (skb_headroom(skb) < dev->hard_header_len && dev->hard_header) {
如果包可用的硬件帧头空间不足
struct sk_buff *skb2;

skb2 = skb_realloc_headroom(skb, (dev->hard_header_len + 15) & ~15);
复制并重新分配原包
kfree_skb(skb);
if (skb2 == NULL)
return -ENOMEM;
if (sk)
skb_set_owner_w(skb2, sk); 设置包的拥有套接字
skb = skb2;
iph = skb->nh.iph;
}

if (skb->len > rt->u.dst.pmtu)
goto fragment;

if (ip_dont_fragment(sk, &rt->u.dst))
iph->frag_off |= __constant_htons(IP_DF);

ip_select_ident(iph, &rt->u.dst);

/* Add an IP checksum. */
ip_send_check(iph);

skb->priority = sk->priority;
return skb->dst->output(skb);

fragment:
if (ip_dont_fragment(sk, &rt->u.dst)) {
/* Reject packet ONLY if TCP might fragment
* it itself, if were careful enough.
*/
iph->frag_off |= __constant_htons(IP_DF);
NETDEBUG(printk(KERN_DEBUG "sending pkt_too_big to self/n"));

icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,
htonl(rt->u.dst.pmtu));
kfree_skb(skb);
return -EMSGSIZE;
}
ip_select_ident(iph, &rt->u.dst);
return ip_fragment(skb, skb->dst->output);
}

/*
* This IP datagram is too large to be sent in one piece. Break it up into
* smaller pieces (each of size equal to IP header plus
* a block of the data of the original IP data part) that will yet fit in a
* single device frame, and queue such a frame for sending.
*
* Yes this is inefficient, feel free to submit a quicker one.
*/

int ip_fragment(struct sk_buff *skb, int (*output)(struct sk_buff*))
{
struct iphdr *iph;
unsigned char *raw;
unsigned char *ptr;
struct net_device *dev;
struct sk_buff *skb2;
unsigned int mtu, hlen, left, len;
int offset;
int not_last_frag;
struct rtable *rt = (struct rtable*)skb->dst;
int err = 0;

dev = rt->u.dst.dev;

/*
* Point into the IP datagram header.
*/

raw = skb->nh.raw;
iph = (struct iphdr*)raw;

/*
* Setup starting values.
*/

hlen = iph->ihl * 4;
left = ntohs(iph->tot_len) - hlen; /* Space per frame */
mtu = rt->u.dst.pmtu - hlen; /* Size of data space */
ptr = raw + hlen; /* Where to start from */

/*
* Fragment the datagram.
*/

offset = (ntohs(iph->frag_off) & IP_OFFSET) << 3;
not_last_frag = iph->frag_off & htons(IP_MF);

/*
* Keep copying data until we run out.
*/

while(left > 0) {
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending upto and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/*
* Allocate buffer.
*/

if ((skb2 = alloc_skb(len+hlen+dev->hard_header_len+15,GFP_ATOMIC)) == NULL) {
NETDEBUG(printk(KERN_INFO "IP: frag: no memory for new fragment!/n"));
err = -ENOMEM;
goto fail;
}

/*
* Set up data on packet
*/

skb2->pkt_type = skb->pkt_type;
skb2->priority = skb->priority;
skb_reserve(skb2, (dev->hard_header_len+15)&~15);
skb_put(skb2, len + hlen);
skb2->nh.raw = skb2->data;
skb2->h.raw = skb2->data + hlen;

/*
* Charge the memory for the fragment to any owner
* it might possess
*/

if (skb->sk)
skb_set_owner_w(skb2, skb->sk);
skb2->dst = dst_clone(skb->dst);
skb2->dev = skb->dev;

/*
* Copy the packet header into the new buffer.
*/

memcpy(skb2->nh.raw, raw, hlen);

/*
* Copy a block of the IP datagram.
*/
memcpy(skb2->h.raw, ptr, len);
left -= len;

/*
* Fill in the new header fields.
*/
iph = skb2->nh.iph;
iph->frag_off = htons((offset >> 3));

/* ANK: dirty, but effective trick. Upgrade options only if
* the segment to be fragmented was THE FIRST (otherwise,
* options are already fixed) and make it ONCE
* on the initial skb, so that all the following fragments
* will inherit fixed options.
*/
if (offset == 0)
ip_options_fragment(skb);

/*
* Added AC : If we are fragmenting a fragment that's not the
* last fragment then keep MF on each bit
*/
if (left > 0 || not_last_frag)
iph->frag_off |= htons(IP_MF);
ptr += len;
offset += len;

#ifdef CONFIG_NETFILTER
/* Connection association is same as pre-frag packet */
skb2->nfct = skb->nfct;
nf_conntrack_get(skb2->nfct);
#ifdef CONFIG_NETFILTER_DEBUG
skb2->nf_debug = skb->nf_debug;
#endif
#endif

/*
* Put this fragment into the sending queue.
*/

IP_INC_STATS(IpFragCreates);

iph->tot_len = htons(len + hlen);

ip_send_check(iph);

err = output(skb2);
if (err)
goto fail;
}
kfree_skb(skb);
IP_INC_STATS(IpFragOKs);
return err;

fail:
kfree_skb(skb);
IP_INC_STATS(IpFragFails);
return err;
}

IP包的输出接口
--------------

/* Don't just hand NF_HOOK skb->dst->output, in case netfilter hook
changes route */
static inline int 发送包的目的入口指针可能被包过滤器所改变,
因此不能向包过滤器直接提供目的入口的输出函数
output_maybe_reroute(struct sk_buff *skb)
{
return skb->dst->output(skb); 通过目的入口输出, 对于点播(UNICAST)地址来说,
指向ip_output()
}

int ip_output(struct sk_buff *skb) 点播地址的IP包输出口
{
#ifdef CONFIG_IP_ROUTE_NAT
struct rtable *rt = (struct rtable*)skb->dst;
#endif

IP_INC_STATS(IpOutRequests);

#ifdef CONFIG_IP_ROUTE_NAT
if (rt->rt_flags&RTCF_NAT)
ip_do_nat(skb);
#endif

return ip_finish_output(skb);
}
__inline__ int ip_finish_output(struct sk_buff *skb)
{
struct net_device *dev = skb->dst->dev;

skb->dev = dev; 设置包的输出设备
skb->protocol = __constant_htons(ETH_P_IP); 设置包的帧类型

return NF_HOOK(PF_INET, NF_IP_POST_ROUTING, skb, NULL, dev,
ip_finish_output2);
}
static inline int ip_finish_output2(struct sk_buff *skb)
{
struct dst_entry *dst = skb->dst; 取IP包绑定的目的入口
struct hh_cache *hh = dst->hh; 取目的入口的硬件帧头缓冲结构

#ifdef CONFIG_NETFILTER_DEBUG
nf_debug_ip_finish_output2(skb);
#endif /*CONFIG_NETFILTER_DEBUG*/

if (hh) { 如果帧头缓冲结构存在
read_lock_bh(&hh->hh_lock);
memcpy(skb->data - 16, hh->hh_data, 16); 直接拷贝硬件帧头
read_unlock_bh(&hh->hh_lock);
skb_push(skb, hh->hh_len);
return hh->hh_output(skb); 通过帧头缓冲输出, 一般指向dev_queue_xmit()
} else if (dst->neighbour) 通过邻居结构(设备硬件地址解析和缓冲结构)输出
return dst->neighbour->output(skb); 指向neigh_resolve_output()
; 关于neighbour结构和arp过程可看自已"Linux硬件地址解析过程"的帖子
printk(KERN_DEBUG "khm/n");
kfree_skb(skb);
return -EINVAL;
}

IP包创建过程中选项区的操作
--------------------------

; net/ipv4/ip_options.c:

struct ip_options { IP选项区索引结构, 当接收到IP包时,
包缓冲的控制块(cb)前部即为此结构
__u32 faddr; /* Saved first hop address */
unsigned char optlen;
unsigned char srr;
unsigned char rr;
unsigned char ts;
unsigned char is_setbyuser:1, /* Set by setsockopt? */
is_data:1, /* Options in __data, rather than skb */
is_strictroute:1, /* Strict source route */
srr_is_hit:1, /* Packet destination addr was our one */
is_changed:1, /* IP checksum more not valid */
rr_needaddr:1, /* Need to record addr of outgoing dev */
ts_needtime:1, /* Need to record timestamp */
ts_needaddr:1; /* Need to record addr of outgoing dev */
unsigned char router_alert;
unsigned char __pad1;
unsigned char __pad2;
unsigned char __data[0];
};
struct inet_skb_parm
{
struct ip_options opt; /* Compiled IP options */
unsigned char flags;

#define IPSKB_MASQUERADED 1
#define IPSKB_TRANSLATED 2
#define IPSKB_FORWARDED 4
};

#define IPCB(skb) ((struct inet_skb_parm*)((skb)->cb))

/*
* Options "fragmenting", just fill options not
* allowed in fragments with NOOPs.
* Simple and stupid 8), but the most efficient way.
*/

void ip_options_fragment(struct sk_buff * skb)
{
unsigned char * optptr = skb->nh.raw; ??? 不是指向IP头吗,怎么用作IP选项区???
struct ip_options * opt = &(IPCB(skb)->opt); 取包缓冲控制块(cb)
int l = opt->optlen;
int optlen;

while (l > 0) {
switch (*optptr) {
case IPOPT_END:
return;
case IPOPT_NOOP:
l--;
optptr++;
continue;
}
optlen = optptr[1];
if (optlen<2 || optlen>l)
return;
if (!IPOPT_COPIED(*optptr)) 将所有没有片断复制标志的选项置换成空选项
memset(optptr, IPOPT_NOOP, optlen);
l -= optlen;
optptr += optlen;
}
opt->ts = 0;
opt->rr = 0;
opt->rr_needaddr = 0;
opt->ts_needaddr = 0;
opt->ts_needtime = 0;
return;
}

/*
* Write options to IP header, record destination address to
* source route option, address of outgoing interface
* (we should already know it, so that this function is allowed be
* called only after routing decision) and timestamp,
* if we originate this datagram.
*
* daddr is real destination address, next hop is recorded in IP header.
* saddr is address of outgoing interface.
*/

void ip_options_build(struct sk_buff * skb, struct ip_options * opt,
u32 daddr, struct rtable *rt, int is_frag)
{
unsigned char * iph = skb->nh.raw;

memcpy(&(IPCB(skb)->opt), opt, sizeof(struct ip_options));
将IP选项参数复制到包缓冲上
memcpy(iph+sizeof(struct iphdr), opt->__data, opt->optlen);
将IP选项数据块复制到IP包选项区
opt = &(IPCB(skb)->opt);
opt->is_data = 0;

if (opt->srr) 将地址daddr拷贝到信源路由选项表的最后一项
memcpy(iph+opt->srr+iph[opt->srr+1]-4, &daddr, 4);

if (!is_frag) { 如果不是片段
if (opt->rr_needaddr) 记录输出设备的地址
ip_rt_get_source(iph+opt->rr+iph[opt->rr+2]-5, rt);
if (opt->ts_needaddr) 记录时戳地址
ip_rt_get_source(iph+opt->ts+iph[opt->ts+2]-9, rt);
if (opt->ts_needtime) { 记录时戳
struct timeval tv;
__u32 midtime;
do_gettimeofday(&tv);
midtime = htonl((tv.tv_sec % 86400) * 1000 + tv.tv_usec / 1000);
memcpy(iph+opt->ts+iph[opt->ts+2]-5, &midtime, 4);
}
return;
}
if (opt->rr) { 填充成空选项
memset(iph+opt->rr, IPOPT_NOP, iph[opt->rr+1]);
opt->rr = 0;
opt->rr_needaddr = 0;
}
if (opt->ts) {
memset(iph+opt->ts, IPOPT_NOP, iph[opt->ts+1]);
opt->ts = 0;
opt->ts_needaddr = opt->ts_needtime = 0;
}
}

/*
* Provided (sopt, skb) points to received options,
* build in dopt compiled option set appropriate for answering.
* i.e. invert SRR option, copy anothers,
* and grab room in RR/TS options.
*
* NOTE: dopt cannot point to skb.
*/

int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb)
{
struct ip_options *sopt;
unsigned char *sptr, *dptr;
int soffset, doffset;
int optlen;
u32 daddr;

memset(dopt, 0, sizeof(struct ip_options)); 将输出选项区索引结构清零

dopt->is_data = 1;

sopt = &(IPCB(skb)->opt);

if (sopt->optlen == 0) {
dopt->optlen = 0;
return 0;
}

sptr = skb->nh.raw;
dptr = dopt->__data; 指向输出选项区开始

if (skb->dst)
daddr = ((struct rtable*)skb->dst)->rt_spec_dst;
else
daddr = skb->nh.iph->daddr;

if (sopt->rr) {
optlen = sptr[sopt->rr+1]; 取IP包路由记录表长度
soffset = sptr[sopt->rr+2]; 取当前地址记录索引
dopt->rr = dopt->optlen + sizeof(struct iphdr); 取输出选项区尾部
memcpy(dptr, sptr+sopt->rr, optlen); 复制路由记录表
if (sopt->rr_needaddr && soffset <= optlen) {
if (soffset + 3 > optlen)
return -EINVAL;
dptr[2] = soffset + 4; 更新地址记录索引
dopt->rr_needaddr = 1;
}
dptr += optlen; 更新选项区输出指针
dopt->optlen += optlen; 更新选项区长度变量
}
if (sopt->ts) {
optlen = sptr[sopt->ts+1]; 取时戳表选项长度
soffset = sptr[sopt->ts+2]; 取当前时戳记录索引
dopt->ts = dopt->optlen + sizeof(struct iphdr);
memcpy(dptr, sptr+sopt->ts, optlen); 复制时戳表
if (soffset <= optlen) {
if (sopt->ts_needaddr) {
if (soffset + 3 > optlen)
return -EINVAL;
dopt->ts_needaddr = 1;
soffset += 4;
}
if (sopt->ts_needtime) {
if (soffset + 3 > optlen)
return -EINVAL;
if ((dptr[3]&0xF) != IPOPT_TS_PRESPEC) {
dopt->ts_needtime = 1;
soffset += 4;
} else { 如果为取指定地址时戳
dopt->ts_needtime = 0;

if (soffset + 8 <= optlen) {
__u32 addr;

memcpy(&addr, sptr+soffset-1, 4);
if (inet_addr_type(addr) != RTN_LOCAL) {
dopt->ts_needtime = 1;
soffset += 8;
}
}
}
}
dptr[2] = soffset;
}
dptr += optlen;
dopt->optlen += optlen;
}
if (sopt->srr) {
unsigned char * start = sptr+sopt->srr;
u32 faddr;

optlen = start[1];
soffset = start[2];
doffset = 0;
if (soffset > optlen)
soffset = optlen + 1;
soffset -= 4;
if (soffset > 3) {
memcpy(&faddr, &start[soffset-1], 4);
for (soffset-=4, doffset=4; soffset > 3; soffset-=4, doffset+=4)
memcpy(&dptr[doffset-1], &start[soffset-1], 4);
/*
* RFC1812 requires to fix illegal source routes.
*/
if (memcmp(&skb->nh.iph->saddr, &start[soffset+3], 4) == 0)
doffset -= 4;
}
if (doffset > 3) {
memcpy(&start[doffset-1], &daddr, 4);
dopt->faddr = faddr;
dptr[0] = start[0];
dptr[1] = doffset+3;
dptr[2] = 4;
dptr += doffset+3;
dopt->srr = dopt->optlen + sizeof(struct iphdr);
dopt->optlen += doffset+3;
dopt->is_strictroute = sopt->is_strictroute;
}
}
while (dopt->optlen & 3) {
*dptr++ = IPOPT_END;
dopt->optlen++;
}
return 0;
}

其余一些相关函数
----------------

static inline struct dst_entry *
__sk_dst_check(struct sock *sk, u32 cookie) 校验套接字所缓冲的目的入口
{
struct dst_entry *dst = sk->dst_cache;

if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
sk->dst_cache = NULL;
return NULL;
}

return dst;
}
static struct dst_entry * ipv4_dst_check(struct dst_entry * dst, u32 cookie)
{ ; ipv4协议的目的入口校验函数
dst_release(dst);
return NULL;
}
static inline
int ip_dont_fragment(struct sock *sk, struct dst_entry *dst) 是否允许IP分片
{
return (sk->protinfo.af_inet.pmtudisc == IP_PMTUDISC_DO ||
(sk->protinfo.af_inet.pmtudisc == IP_PMTUDISC_WANT &&
!(dst->mxlock&(1<}
static inline void ip_select_ident(struct iphdr *iph, struct dst_entry *dst)
分配IP包标识号
{
if (iph->frag_off&__constant_htons(IP_DF))
iph->id = 0;
else
__ip_select_ident(iph, dst);
}

/* Generate a checksum for an outgoing IP datagram. */
__inline__ void ip_send_check(struct iphdr *iph) 校验IP包头
{
iph->check = 0;
iph->check = ip_fast_csum((unsigned char *)iph, iph->ihl);
}

#define SKB_EXT_ERR(skb) ((struct sock_exterr_skb *) ((skb)->cb))

void ip_local_error(struct sock *sk, int err, u32 daddr, u16 port, u32 info)
生成出错信息包
{
struct sock_exterr_skb *serr;
struct iphdr *iph;
struct sk_buff *skb;

if (!sk->protinfo.af_inet.recverr)
return;

skb = alloc_skb(sizeof(struct iphdr), GFP_ATOMIC);
if (!skb)
return;

iph = (struct iphdr*)skb_put(skb, sizeof(struct iphdr));
skb->nh.iph = iph;
iph->daddr = daddr;

serr = SKB_EXT_ERR(skb); 取包缓冲控制块(cb)
serr->ee.ee_errno = err; 错误码
serr->ee.ee_origin = SO_EE_ORIGIN_LOCAL; 错误来源
serr->ee.ee_type = 0;
serr->ee.ee_code = 0;
serr->ee.ee_pad = 0;
serr->ee.ee_info = info; 出错参数
serr->ee.ee_data = 0;
serr->addr_offset = (u8*)&iph->daddr - skb->nh.raw;
serr->port = port;

skb->h.raw = skb->tail;
skb_pull(skb, skb->tail - skb->data);

if (sock_queue_err_skb(sk, skb)) 加入套接字的出错信息包队列
kfree_skb(skb);
}
static inline int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
{
/* Cast skb->rcvbuf to unsigned... It's pointless, but reduces
number of warnings when compiling with -W --ANK
*/
if (atomic_read(&sk->rmem_alloc) + skb->truesize >= (unsigned)sk->rcvbuf)
return -ENOMEM;
skb_set_owner_r(skb, sk);
skb_queue_tail(&sk->error_queue,skb);
if (!sk->dead)
sk->data_ready(sk,skb->len); 唤醒套接字等待队列
return 0;
}

/*
* Queue a received datagram if it will fit. Stream and sequenced
* protocols can't normally use this as they need to fit buffers in
* and play with them.
*
* Inlined as it's very short and called for pretty much every
* packet ever received.
*/

static inline void skb_set_owner_w(struct sk_buff *skb, struct sock *sk)
设置发送包的拥有套接字
{
sock_hold(sk);
skb->sk = sk;
skb->destructor = sock_wfree;
atomic_add(skb->truesize, &sk->wmem_alloc); 刷新发送内存的分配量
}
static inline void skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
设置接收包的拥有套接字
{
skb->sk = sk;
skb->destructor = sock_rfree;
atomic_add(skb->truesize, &sk->rmem_alloc); 刷新接收内存的分配量
}
/*
* Write buffer destructor automatically called from kfree_skb.
*/
void sock_wfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;

/* In case it might be waiting for more memory. */
atomic_sub(skb->truesize, &sk->wmem_alloc);
sk->write_space(sk); 唤醒正在等待写的进程
sock_put(sk);
}

/*
* Read buffer destructor automatically called from kfree_skb.
*/
void sock_rfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;

atomic_sub(skb->truesize, &sk->rmem_alloc);
}

static inline long sock_sndtimeo(struct sock *sk, int noblock) 取套接字的发送超时
{
return noblock ? 0 : sk->sndtimeo;
}
static inline int sock_error(struct sock *sk) 读取并且复位套接字错误号
{
int err=xchg(&sk->err,0);
return -err;
}

/*
We do not cache source address of outgoing interface,
because it is used only by IP RR, TS and SRR options,
so that it out of fast path.

BTW remember: "addr" is allowed to be not aligned
in IP options!
*/

void ip_rt_get_source(u8 *addr, struct rtable *rt) 取路由输出设备的地址
{
u32 src;
struct fib_result res;

if (rt->key.iif == 0)
src = rt->rt_src;
else if (fib_lookup(&rt->key, &res) == 0) {
#ifdef CONFIG_IP_ROUTE_NAT
if (res.type == RTN_NAT)
src = inet_select_addr(rt->u.dst.dev, rt->rt_gateway, RT_SCOPE_UNIVERSE);
else
#endif
src = FIB_RES_PREFSRC(res);
fib_res_put(&res);
} else
src = inet_select_addr(rt->u.dst.dev, rt->rt_gateway, RT_SCOPE_UNIVERSE);
memcpy(addr, &src, 4);
}

struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size,
unsigned long fallback, int noblock, int *errcode) 分配套接字的发送包
{
int err;
struct sk_buff *skb;
long timeo;

timeo = sock_sndtimeo(sk, noblock); 取套接字的发送超时

while (1) {
unsigned long try_size = size;

err = sock_error(sk); 读取并且复位套接字的错误码
if (err != 0)
goto failure;

/*
* We should send SIGPIPE in these cases according to
* 1003.1g draft 6.4. If we (the user) did a shutdown()
* call however we should not.
*
* Note: This routine isnt just used for datagrams and
* anyway some datagram protocols have a notion of
* close down.
*/

err = -EPIPE;
if (sk->shutdown&SEND_SHUTDOWN)
goto failure;

if (atomic_read(&sk->wmem_alloc) < sk->sndbuf) {
如果分配给套接字的发送内存小于其发送缓冲区
if (fallback) {
/* The buffer get won't block, or use the atomic queue.
* It does produce annoying no free page messages still.
*/
skb = alloc_skb(size, GFP_BUFFER);
if (skb)
break;
try_size = fallback;
}
skb = alloc_skb(try_size, sk->allocation);
if (skb)
break;
err = -ENOBUFS;
goto failure;
}

/*
* This means we have too many buffers for this socket already.
*/

set_bit(SOCK_ASYNC_NOSPACE, &sk->socket->flags);
set_bit(SOCK_NOSPACE, &sk->socket->flags);
err = -EAGAIN;
if (!timeo)
goto failure;
if (signal_pending(current))
goto interrupted;
timeo = sock_wait_for_wmem(sk, timeo);
}

skb_set_owner_w(skb, sk);
return skb;

interrupted:
err = sock_intr_errno(timeo);
failure:
*errcode = err;
return NULL;
}
/* It is almost wait_for_tcp_memory minus release_sock/lock_sock.
I think, these locks should be removed for datagram sockets.
*/
static long sock_wait_for_wmem(struct sock * sk, long timeo)
等待套接字可分配的发送内存
{
DECLARE_WAITQUEUE(wait, current);

clear_bit(SOCK_ASYNC_NOSPACE, &sk->socket->flags);
add_wait_queue(sk->sleep, &wait);
for (;;) {
if (signal_pending(current))
break;
set_bit(SOCK_NOSPACE, &sk->socket->flags);
set_current_state(TASK_INTERRUPTIBLE);
if (atomic_read(&sk->wmem_alloc) < sk->sndbuf)
break;
if (sk->shutdown & SEND_SHUTDOWN)
break;
if (sk->err)
break;
timeo = schedule_timeout(timeo);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk->sleep, &wait);
return timeo;
}


Edited by lucian_yao on 07/02/01 02:38
PM.

文章选项: 打印

jiangk2001
(stranger)
12/30/02 16:43
Re: IP包的生成和发送接口 新 [re: opera]  

太精彩了

文章选项: 打印

  打印

前往讨论区

Contact Us LINUXFORUM.NET

阅读全文
0 0

相关文章推荐

img
取 消
img