幽灵狼

狼团队中的每一位成员,共同承担团体生存的责任, 并为此付出自己的独特技能和力量。 我是狼, 相信自己, 相信伙伴。
  IT博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

2006年2月25日

http://www.cs.mun.ca/~rod/ncurses/ncurses.html

posted @ 2006-02-25 10:51 幽灵狼 阅读(938) | 评论 (6)编辑 收藏

2006年2月18日

在搜索框上输入: “index of/ ”  inurl:lib

再按搜索你将进入许多图书馆,并且一定能下载自己喜欢的书籍。


在搜索框上输入: “index of /”  cnki

再按搜索你就可以找到许多图书馆的CNKI、VIP、超星等入口!
 

在搜索框上输入: “index of /”  ppt

再按搜索你就可以突破网站入口下载powerpint作品!


在搜索框上输入: “index of /”  mp3

再按搜索你就可以突破网站入口下载mp3、rm等影视作品!


在搜索框上输入: “index of /”  swf

再按搜索你就可以突破网站入口下载flash作品!


在搜索框上输入: “index of /”  要下载的软件名

再按搜索你就可以突破网站入口下载软件!


注意引号应是英文的!


再透露一下,如果你输入:


“index of /”  AVI

你会找到什么呢?同理,把AVI换为MPEG看看又会找到什么呢?呵呵!接下来不用我再教了吧?

posted @ 2006-02-18 09:30 幽灵狼 阅读(337) | 评论 (0)编辑 收藏

2005年12月22日

Anti-trojan Software Reviews

    Anti-trojans - how we reviewed   What is a Trojan Horse?    About us    Anti-trojan suggestions

A survey of the best anti-trojan programs
from Tech Support Alert

Most folk harbor the belief that they are totally protected from malicious trojan horses by their anti-virus scanner.

The bad news is that many anti-virus scanners give only limited protection against trojans. Just how limited can be gauged from the fact that Norton Anti-Virus 2004  missed every single trojan in the test data set we used in these series of reviews.  Other anti-virus programs didn't do much better.

For the best protection against trojans you really need a specialist anti-trojan program in addition to your anti-virus software. Simple as that.

At Tech Support Alert we identified 44 currently available anti-trojan / trojan remover programs. After a lot of culling and testing we ended up with only eight products we felt were worth reviewing in detail. On completing detailed reviews of these, we felt we could only recommend five products. To see how we reviewed, click here. 

All the recommended products listed below, offer good protection against trojans and have powerful trojan removal capabilities. All would make valuable adjuncts to your anti-virus program and firewall in providing your PC with maximum protection against a hostile attack.

We've made recommendations on the products that impressed us most, but we suggest you read the reviews and make your own decision.  Without doubt, the best product is the one that best suits YOUR needs.

trojan remover gold awardOutstanding Anti-trojan Programs

 

Trojan Hunter Editors Choice: Best for most users 
Trojan Hunter's sophisticated multifaceted detection capabilities allow it to detect insidious modern trojans with an ease that is only bettered by TDS-3. Unlike TDS-3, it has a friendly user interface which means that it can be used even by inexperienced users. As a trojan remover its performance was outstanding. Add to that the fact that it's fast, technically sophisticated and is very well supported and you have a winning combination.  Click here for full review

Ewido
Ewido is a new product that managed to impress us immensely with its a technically sophisticated design yet is relative ease to use. It detects trojans almost as well as Trojan Hunter, has a fast scanner and has an excellent trojan remover as well.  As an added bonus it has proved to be an excellent performer in removing some difficult-to-remove spyware products. The only thing that stopped us awarding this product the Editor's choice rating was the lack of an in-product help system and meager web based support resources. Click here for full review

TDS-3   Note: This product was discontinued by the developer on 22nd July, 2005
If you want the highest level of protection against trojans that is currently available, then you need TDS-3. However be prepared to pay for its extraordinary level of security in terms of product complexity and resource usage.  TDS-3 is a reassuring product for experienced users but a daunting one for many others. Click here for full review.

anti-trojan silver award Highly Recommended

A Squared (a2)
We liked a2 a lot but unfortunately some of its most attractive features are yet to be fully implemented. When these are delivered in the upcoming version 2 we anticipate a2 will leap directly into our "outstanding" category. As of the moment though, it is a work in progress. Click here for full review

The Cleaner 
This is a well established and easy to use product. The folks behind The Cleaner have, in the last 12 months, put a lot of work in expanding the product's signature database and this shows in markedly improved detection rate. However its slow scan speed will  be a problem for some users. Click here for full review.

Other Programs Reviewed

BOClean 
A few years back BOClean was arguably the best anti-trojan monitor on the market and attracted a loyal following even though it lacked an on-demand scanner. Now other anti-trojan vendors offer monitors that perform just as as well as BOClean and include an on-demand scanner as well for the same selling price. However for those prepared to trade convenience for ultimate protection, BoClean is still a viable option. Click here for full  review.

Tauscan
Tauscan is a is an easy to use program with a very fast scanner. It  offers reasonable detection capabilities though well below the top products. We can't help feeling that Tauscan is looking a little dated compared to new products like Ewido. Click here for full review. 

Pest Patrol 
This program does a lot more than detect and remove trojans; it will also detects spyware, adware and a variety of other undesirable pests. However when it comes to the specific task of detecting trojans, PestPatrol is largely outclassed by the dedicated anti-trojan products covered in this review.  Click here for full review.

posted @ 2005-12-22 20:19 幽灵狼 阅读(541) | 评论 (0)编辑 收藏

     摘要: The 46 Best-ever Freeware Utilities There are a lot of great freeware products out there. Many are as good or even better than their commerci...  阅读全文

posted @ 2005-12-22 20:15 幽灵狼 阅读(647) | 评论 (0)编辑 收藏

2005年12月17日

Netlink Sockets are the method that the Linux Kernel uses to pass Routing, Interface and other miscellaneous networking information around, both within the kernel and between the kernel and userspace. It replaces the old ioctl(2) based method and is far far superior - infact as soon as the kernel receives a networking ioctl it is converted to a netlink message before being shipped off for further processing.

Basic Introduction

The netlink protocol uses a special type of socket(2) to communicate with the Linux kernel. This socket is called a "Netlink Socket" surprisingly enough and can be created by specifing AF_NETLINK as the first argument to a socket(2) call, The socket type (second argument) can be either SOCK_DGRAM or SOCK_RAW, it makes absolutely no difference!, the third argument (netlink family) specifies which part of the linux networking stack you want to modify, for example NETLINK_ROUTE can be specified to modify the routing table (including interfaces), or NETLINK_ARPD can be specified to allow the arp table to be manipulated. A full list of available netlink families is found in netlink(7).

NETLINK_ROUTE is the most commonly used netlink family as it is used to add, delete and modify routes from the kernels routing table and can also be used to add, delete and modify the interfaces on the machine.

Some of the basic Netlink principles are documented in [link]RFC:3549.

There is somewhat of a lack of easy to read documentation regarding how to program using netlink sockets, however the information is all there in the end. As a start try the netlink(3), netlink(7), rtnetlink(3) and rtnetlink(7) manpages which provide a very technical description of the netlink protocol, all the information that you need to write a program using netlink is contained in these manpages.... should be easy from here right?

The iproute2 package is the base implementation of the netlink interface, it replaces all the old linux networking utilities (ifconfig, route, etc) into a single binary called ip which performs all of the tasks using the netlink interface. I highly recommend that you use this package as a reference when coding netlink related applications. In particular iproute2 contains a netlink library (libnetlink) which deals with much of the low level protocol interactions between your application and the kernel. Unfortunately the library is not seperately packaged and you'll have to spend some time extracting it from the iproute2 package before it is useful.

Coming Soon - Some basic examples of how to program using libnetlink -- Talk to MattBrown if you want them and they're not here yet!

(ha! It's been ages and you've not put up any examples! So I've written one that shows route add/del events, see LinuxNetlinkSocketExample --PerryLorier).

Random notes (things I wish were documented somewhere but aren't)

  • if you want to recieve RTM_NEWNEIGH messages, you need /proc/sys/net/ipv{4,6}/neigh/*/app_probes to be non 0.

I don't know why. They might have been drunk at the time -- PerryLorier
The reason why is that much of the system parameters are moving this way and they were just too lazy to convert other ones too I suspect -- IanMcDonald

URL for this article: http://www.wlug.org.nz/LinuxNetlinkSockets

posted @ 2005-12-17 17:46 幽灵狼 阅读(1313) | 评论 (0)编辑 收藏

This is a sample program that uses a netlink socket to listen to route change events and prints out some rudimentary information about them. It's very simple and boring, but hopefully useful.

This being a wiki, I also expect everyone to hack on this code and make it nicer, this is pretty hideous, but I want to get on with my real program now. So if you're reading this page your mission (if you choose to accept it) is to clean up the below code a little bit (doesn't need to be much).

See LinuxNetlinkSockets


#include <asm/types.h>

#include <sys/socket.h>
#include <unistd.h>
#include <err.h>
#include <stdio.h>
#include <netinet/in.h>

#include <linux/netlink.h>
#include <linux/rtnetlink.h>

#if 0
//#define MYPROTO NETLINK_ARPD
#define MYMGRP RTMGRP_NEIGH
// if you want the above you'll find that the kernel must be compiled with CONFIG_ARPD, and
// that you need MYPROTO=NETLINK_ROUTE, since the kernel arp code {re,ab}uses rtnl (NETLINK_ROUTE)

#else
#define MYPROTO NETLINK_ROUTE
#define MYMGRP RTMGRP_IPV4_ROUTE
#endif

struct msgnames_t {
int id;
char *msg;
} typenames[] = {
#define MSG(x) { x, #x }
MSG(RTM_NEWROUTE),
MSG(RTM_DELROUTE),
MSG(RTM_GETROUTE),
#undef MSG
{0,0}
};

char *lookup_name(struct msgnames_t *db,int id)
{
static char name[512];
struct msgnames_t *msgnamesiter;
for(msgnamesiter=db;msgnamesiter->msg;++msgnamesiter) {
if (msgnamesiter->id == id)
break;
}
if (msgnamesiter->msg) {
return msgnamesiter->msg;
}
snprintf(name,sizeof(name),"#%i",id);
return name;
}

int open_netlink()
{
int sock = socket(AF_NETLINK,SOCK_RAW,MYPROTO);
struct sockaddr_nl addr;

memset((void *)&addr, 0, sizeof(addr));

if (sock<0)
return sock;
addr.nl_family = AF_NETLINK;
addr.nl_pid = getpid();
addr.nl_groups = MYMGRP;
if (bind(sock,(struct sockaddr *)&addr,sizeof(addr))<0)
return -1;
return sock;
}

int read_event(int sock)
{
struct sockaddr_nl nladdr;
struct msghdr msg;
struct iovec iov[2];
struct nlmsghdr nlh;
char buffer[65536];
int ret;
iov[0].iov_base = (void *)&nlh;
iov[0].iov_len = sizeof(nlh);
iov[1].iov_base = (void *)buffer;
iov[1].iov_len = sizeof(buffer);
msg.msg_name = (void *)&(nladdr);
msg.msg_namelen = sizeof(nladdr);
msg.msg_iov = iov;
msg.msg_iovlen = sizeof(iov)/sizeof(iov[0]);
ret=recvmsg(sock, &msg, 0);
if (ret<0) {
return ret;
}
printf("Type: %i (%s)\n",(nlh.nlmsg_type),lookup_name(typenames,nlh.nlmsg_type));
printf("Flag:");
#define FLAG(x) if (nlh.nlmsg_type & x) printf(" %s",#x)
FLAG(NLM_F_REQUEST);
FLAG(NLM_F_MULTI);
FLAG(NLM_F_ACK);
FLAG(NLM_F_ECHO);
FLAG(NLM_F_REPLACE);
FLAG(NLM_F_EXCL);
FLAG(NLM_F_CREATE);
FLAG(NLM_F_APPEND);
#undef FLAG
printf("\n");
printf("Seq : %i\n",nlh.nlmsg_seq);
printf("Pid : %i\n",nlh.nlmsg_pid);
printf("\n");
return 0;
}

int main(int argc, char *argv[])
{ int nls = open_netlink();
if (nls<0) {
err(1,"netlink");
}
while (1)
read_event(nls);
return 0;
}

posted @ 2005-12-17 17:37 幽灵狼 阅读(2539) | 评论 (0)编辑 收藏

Kernel Korner - Why and How to Use Netlink Socket

SysAdmin Use this bidirectional, versatile method to pass data between kernel and user space.

Due to the complexity of developing and maintaining the kernel, only the most essential and performance-critical code are placed in the kernel. Other things, such as GUI, management and control code, typically are programmed as user-space applications. This practice of splitting the implementation of certain features between kernel and user space is quite common in Linux. Now the question is how can kernel code and user-space code communicate with each other?

The answer is the various IPC methods that exist between kernel and user space, such as system call, ioctl, proc filesystem or netlink socket. This article discusses netlink socket and reveals its advantages as a network feature-friendly IPC.

Introduction

Netlink socket is a special IPC used for transferring information between kernel and user-space processes. It provides a full-duplex communication link between the two by way of standard socket APIs for user-space processes and a special kernel API for kernel modules. Netlink socket uses the address family AF_NETLINK, as compared to AF_INET used by TCP/IP socket. Each netlink socket feature defines its own protocol type in the kernel header file include/linux/netlink.h.

The following is a subset of features and their protocol types currently supported by the netlink socket:

  • NETLINK_ROUTE: communication channel between user-space routing dæmons, such as BGP, OSPF, RIP and kernel packet forwarding module. User-space routing dæmons update the kernel routing table through this netlink protocol type.

  • NETLINK_FIREWALL: receives packets sent by the IPv4 firewall code.

  • NETLINK_NFLOG: communication channel for the user-space iptable management tool and kernel-space Netfilter module.

  • NETLINK_ARPD: for managing the arp table from user space.

Why do the above features use netlink instead of system calls, ioctls or proc filesystems for communication between user and kernel worlds? It is a nontrivial task to add system calls, ioctls or proc files for new features; we risk polluting the kernel and damaging the stability of the system. Netlink socket is simple, though: only a constant, the protocol type, needs to be added to netlink.h. Then, the kernel module and application can talk using socket-style APIs immediately.

Netlink is asynchronous because, as with any other socket API, it provides a socket queue to smooth the burst of messages. The system call for sending a netlink message queues the message to the receiver's netlink queue and then invokes the receiver's reception handler. The receiver, within the reception handler's context, can decide whether to process the message immediately or leave the message in the queue and process it later in a different context. Unlike netlink, system calls require synchronous processing. Therefore, if we use a system call to pass a message from user space to the kernel, the kernel scheduling granularity may be affected if the time to process that message is long.

The code implementing a system call in the kernel is linked statically to the kernel in compilation time; thus, it is not appropriate to include system call code in a loadable module, which is the case for most device drivers. With netlink socket, no compilation time dependency exists between the netlink core of Linux kernel and the netlink application living in loadable kernel modules.

Netlink socket supports multicast, which is another benefit over system calls, ioctls and proc. One process can multicast a message to a netlink group address, and any number of other processes can listen to that group address. This provides a near-perfect mechanism for event distribution from kernel to user space.

System call and ioctl are simplex IPCs in the sense that a session for these IPCs can be initiated only by user-space applications. But, what if a kernel module has an urgent message for a user-space application? There is no way of doing that directly using these IPCs. Normally, applications periodically need to poll the kernel to get the state changes, although intensive polling is expensive. Netlink solves this problem gracefully by allowing the kernel to initiate sessions too. We call it the duplex characteristic of the netlink socket.

Finally, netlink socket provides a BSD socket-style API that is well understood by the software development community. Therefore, training costs are less as compared to using the rather cryptic system call APIs and ioctls.

Relating to the BSD Routing Socket

In BSD TCP/IP stack implementation, there is a special socket called the routing socket. It has an address family of AF_ROUTE, a protocol family of PF_ROUTE and a socket type of SOCK_RAW. The routing socket in BSD is used by processes to add or delete routes in the kernel routing table.

In Linux, the equivalent function of the routing socket is provided by the netlink socket protocol type NETLINK_ROUTE. Netlink socket provides a functionality superset of BSD's routing socket.

Netlink Socket APIs

The standard socket APIs-socket(), sendmsg(), recvmsg() and close()-can be used by user-space applications to access netlink socket. Consult the man pages for detailed definitions of these APIs. Here, we discuss how to choose parameters for these APIs only in the context of netlink socket. The APIs should be familiar to anyone who has written an ordinary network application using TCP/IP sockets.

To create a socket with socket(), enter:

int socket(int domain, int type, int protocol)


The socket domain (address family) is AF_NETLINK, and the type of socket is either SOCK_RAW or SOCK_DGRAM, because netlink is a datagram-oriented service.

The protocol (protocol type) selects for which netlink feature the socket is used. The following are some predefined netlink protocol types: NETLINK_ROUTE, NETLINK_FIREWALL, NETLINK_ARPD, NETLINK_ROUTE6 and NETLINK_IP6_FW. You also can add your own netlink protocol type easily.

Up to 32 multicast groups can be defined for each netlink protocol type. Each multicast group is represented by a bit mask, 1<<i, where 0<=i<=31. This is extremely useful when a group of processes and the kernel process coordinate to implement the same feature-sending multicast netlink messages can reduce the number of system calls used and alleviate applications from the burden of maintaining the multicast group membership.

bind()

As for a TCP/IP socket, the netlink bind() API associates a local (source) socket address with the opened socket. The netlink address structure is as follows:

struct sockaddr_nl
{
sa_family_t nl_family; /* AF_NETLINK */
unsigned short nl_pad; /* zero */
__u32 nl_pid; /* process pid */
__u32 nl_groups; /* mcast groups mask */
} nladdr;


When used with bind(), the nl_pid field of the sockaddr_nl can be filled with the calling process' own pid. The nl_pid serves here as the local address of this netlink socket. The application is responsible for picking a unique 32-bit integer to fill in nl_pid:

NL_PID Formula 1:  nl_pid = getpid();


Formula 1 uses the process ID of the application as nl_pid, which is a natural choice if, for the given netlink protocol type, only one netlink socket is needed for the process.

In scenarios where different threads of the same process want to have different netlink sockets opened under the same netlink protocol, Formula 2 can be used to generate the nl_pid:


NL_PID Formula 2: pthread_self() << 16 | getpid();


In this way, different pthreads of the same process each can have their own netlink socket for the same netlink protocol type. In fact, even within a single pthread it's possible to create multiple netlink sockets for the same protocol type. Developers need to be more creative, however, in generating a unique nl_pid, and we don't consider this to be a normal-use case.

If the application wants to receive netlink messages of the protocol type that are destined for certain multicast groups, the bitmasks of all the interested multicast groups should be ORed together to form the nl_groups field of sockaddr_nl. Otherwise, nl_groups should be zeroed out so the application receives only the unicast netlink message of the protocol type destined for the application. After filling in the nladdr, do the bind as follows:


bind(fd, (struct sockaddr*)&nladdr, sizeof(nladdr));


Sending a Netlink Message

In order to send a netlink message to the kernel or other user-space processes, another struct sockaddr_nl nladdr needs to be supplied as the destination address, the same as sending a UDP packet with sendmsg(). If the message is destined for the kernel, both nl_pid and nl_groups should be supplied with 0.

If the message is a unicast message destined for another process, the nl_pid is the other process' pid and nl_groups is 0, assuming nlpid Formula 1 is used in the system.

If the message is a multicast message destined for one or multiple multicast groups, the bitmasks of all the destination multicast groups should be ORed together to form the nl_groups field. We then can supply the netlink address to the struct msghdr msg for the sendmsg() API, as follows:


struct msghdr msg;
msg.msg_name = (void *)&(nladdr);
msg.msg_namelen = sizeof(nladdr);


The netlink socket requires its own message header as well. This is for providing a common ground for netlink messages of all protocol types.

Because the Linux kernel netlink core assumes the existence of the following header in each netlink message, an application must supply this header in each netlink message it sends:


struct nlmsghdr
{
__u32 nlmsg_len; /* Length of message */
__u16 nlmsg_type; /* Message type*/
__u16 nlmsg_flags; /* Additional flags */
__u32 nlmsg_seq; /* Sequence number */
__u32 nlmsg_pid; /* Sending process PID */
};


nlmsg_len has to be completed with the total length of the netlink message, including the header, and is required by netlink core. nlmsg_type can be used by applications and is an opaque value to netlink core. nlmsg_flags is used to give additional control to a message; it is read and updated by netlink core. nlmsg_seq and nlmsg_pid are used by applications to track the message, and they are opaque to netlink core as well.

A netlink message thus consists of nlmsghdr and the message payload. Once a message has been entered, it enters a buffer pointed to by the nlh pointer. We also can send the message to the struct msghdr msg:


struct iovec iov;
iov.iov_base = (void *)nlh;
iov.iov_len = nlh->nlmsg_len;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;


After the above steps, a call to sendmsg() kicks out the netlink message:


sendmsg(fd, &msg, 0);


Receiving Netlink Messages

A receiving application needs to allocate a buffer large enough to hold netlink message headers and message payloads. It then fills the struct msghdr msg as shown below and uses the standard recvmsg() to receive the netlink message, assuming the buffer is pointed to by nlh:


struct sockaddr_nl nladdr;
struct msghdr msg;
struct iovec iov;
iov.iov_base = (void *)nlh;
iov.iov_len = MAX_NL_MSG_LEN;
msg.msg_name = (void *)&(nladdr);
msg.msg_namelen = sizeof(nladdr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
recvmsg(fd, &msg, 0);


After the message has been received correctly, the nlh should point to the header of the just-received netlink message. nladdr should hold the destination address of the received message, which consists of the pid and the multicast groups to which the message is sent. And, the macro NLMSG_DATA(nlh), defined in netlink.h, returns a pointer to the payload of the netlink message. A call to close(fd) closes the netlink socket identified by file descriptor fd.

Kernel-Space Netlink APIs

The kernel-space netlink API is supported by the netlink core in the kernel, net/core/af_netlink.c. From the kernel side, the API is different from the user-space API. The API can be used by kernel modules to access the netlink socket and to communicate with user-space applications. Unless you leverage the existing netlink socket protocol types, you need to add your own protocol type by adding a constant to netlink.h. For example, we can add a netlink protocol type for testing purposes by inserting this line into netlink.h:

#define NETLINK_TEST  17


Afterward, you can reference the added protocol type anywhere in the Linux kernel.

In user space, we call socket() to create a netlink socket, but in kernel space, we call the following API:


struct sock *
netlink_kernel_create(int unit,
void (*input)(struct sock *sk, int len));


The parameter unit is, in fact, the netlink protocol type, such as NETLINK_TEST. The function pointer, input, is a callback function invoked when a message arrives at this netlink socket.

After the kernel has created a netlink socket for protocol NETLINK_TEST, whenever user space sends a netlink message of the NETLINK_TEST protocol type to the kernel, the callback function, input(), which is registered by netlink_kernel_create(), is invoked. The following is an example implementation of the callback function input:


void input (struct sock *sk, int len)
{
struct sk_buff *skb;
struct nlmsghdr *nlh = NULL;
u8 *payload = NULL;
while ((skb = skb_dequeue(&sk->receive_queue))
!= NULL) {
/* process netlink message pointed by skb->data */
nlh = (struct nlmsghdr *)skb->data;
payload = NLMSG_DATA(nlh);
/* process netlink message with header pointed by
* nlh and payload pointed by payload
*/
}
}


This input() function is called in the context of the sendmsg() system call invoked by the sending process. It is okay to process the netlink message inside input() if it's fast. When the processing of netlink message takes a long time, however, we want to keep it out of input() to avoid blocking other system calls from entering the kernel. Instead, we can use a dedicated kernel thread to perform the following steps indefinitely. Use skb = skb_recv_datagram(nl_sk) where nl_sk is the netlink socket returned by netlink_kernel_create(). Then, process the netlink message pointed to by skb->data.

This kernel thread sleeps when there is no netlink message in nl_sk. Thus, inside the callback function input(), we need to wake up only the sleeping kernel thread, like this:


void input (struct sock *sk, int len)
{
wake_up_interruptible(sk->sleep);
}


This is a more scalable communication model between user space and kernel. It also improves the granularity of context switches.

Sending Netlink Messages from the Kernel

Just as in user space, the source netlink address and destination netlink address need to be set when sending a netlink message. Assuming the socket buffer holding the netlink message to be sent is struct sk_buff *skb, the local address can be set with:


NETLINK_CB(skb).groups = local_groups;
NETLINK_CB(skb).pid = 0; /* from kernel */


The destination address can be set like this:


NETLINK_CB(skb).dst_groups = dst_groups;
NETLINK_CB(skb).dst_pid = dst_pid;


Such information is not stored in skb->data. Rather, it is stored in the netlink control block of the socket buffer, skb.

To send a unicast message, use:


int
netlink_unicast(struct sock *ssk, struct sk_buff
*skb, u32 pid, int nonblock);


where ssk is the netlink socket returned by netlink_kernel_create(), skb->data points to the netlink message to be sent and pid is the receiving application's pid, assuming NLPID Formula 1 is used. nonblock indicates whether the API should block when the receiving buffer is unavailable or immediately return a failure.

You also can send a multicast message. The following API delivers a netlink message to both the process specified by pid and the multicast groups specified by group:


void
netlink_broadcast(struct sock *ssk, struct sk_buff
*skb, u32 pid, u32 group, int allocation);


group is the ORed bitmasks of all the receiving multicast groups. allocation is the kernel memory allocation type. Typically, GFP_ATOMIC is used if from interrupt context; GFP_KERNEL if otherwise. This is due to the fact that the API may need to allocate one or many socket buffers to clone the multicast message.

Closing a Netlink Socket from the Kernel

Given the struct sock *nl_sk returned by netlink_kernel_create(), we can call the following kernel API to close the netlink socket in the kernel:


sock_release(nl_sk->socket);


So far, we have shown only the bare minimum code framework to illustrate the concept of netlink programming. We now will use our NETLINK_TEST netlink protocol type and assume it already has been added to the kernel header file. The kernel module code listed here contains only the netlink-relevant part, so it should be inserted into a complete kernel module skeleton, which you can find from many other reference sources.

Unicast Communication between Kernel and Application

In this example, a user-space process sends a netlink message to the kernel module, and the kernel module echoes the message back to the sending process. Here is the user-space code:


#include <sys/socket.h>
#include <linux/netlink.h>
#define MAX_PAYLOAD 1024 /* maximum payload size*/
struct sockaddr_nl src_addr, dest_addr;
struct nlmsghdr *nlh = NULL;
struct iovec iov;
int sock_fd;
void main() {
sock_fd = socket(PF_NETLINK, SOCK_RAW,NETLINK_TEST);
memset(&src_addr, 0, sizeof(src_addr));
src__addr.nl_family = AF_NETLINK;
src_addr.nl_pid = getpid(); /* self pid */
src_addr.nl_groups = 0; /* not in mcast groups */
bind(sock_fd, (struct sockaddr*)&src_addr,
sizeof(src_addr));
memset(&dest_addr, 0, sizeof(dest_addr));
dest_addr.nl_family = AF_NETLINK;
dest_addr.nl_pid = 0; /* For Linux Kernel */
dest_addr.nl_groups = 0; /* unicast */
nlh=(struct nlmsghdr *)malloc(
NLMSG_SPACE(MAX_PAYLOAD));
/* Fill the netlink message header */
nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
nlh->nlmsg_pid = getpid(); /* self pid */
nlh->nlmsg_flags = 0;
/* Fill in the netlink message payload */
strcpy(NLMSG_DATA(nlh), "Hello you!");
iov.iov_base = (void *)nlh;
iov.iov_len = nlh->nlmsg_len;
msg.msg_name = (void *)&dest_addr;
msg.msg_namelen = sizeof(dest_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
sendmsg(fd, &msg, 0);
/* Read message from kernel */
memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
recvmsg(fd, &msg, 0);
printf(" Received message payload: %s\n",
NLMSG_DATA(nlh));

/* Close Netlink Socket */
close(sock_fd);
}


And, here is the kernel code:


struct sock *nl_sk = NULL;
void nl_data_ready (struct sock *sk, int len)
{
wake_up_interruptible(sk->sleep);
}
void netlink_test() {
struct sk_buff *skb = NULL;
struct nlmsghdr *nlh = NULL;
int err;
u32 pid;
nl_sk = netlink_kernel_create(NETLINK_TEST,
nl_data_ready);
/* wait for message coming down from user-space */
skb = skb_recv_datagram(nl_sk, 0, 0, &err);
nlh = (struct nlmsghdr *)skb->data;
printk("%s: received netlink message payload:%s\n",
__FUNCTION__, NLMSG_DATA(nlh));
pid = nlh->nlmsg_pid; /*pid of sending process */
NETLINK_CB(skb).groups = 0; /* not in mcast group */
NETLINK_CB(skb).pid = 0; /* from kernel */
NETLINK_CB(skb).dst_pid = pid;
NETLINK_CB(skb).dst_groups = 0; /* unicast */
netlink_unicast(nl_sk, skb, pid, MSG_DONTWAIT);
sock_release(nl_sk->socket);
}


After loading the kernel module that executes the kernel code above, when we run the user-space executable, we should see the following dumped from the user-space program:

Received message payload: Hello you!


And, the following message should appear in the output of dmesg:

netlink_test: received netlink message payload: 
Hello you!


Multicast Communication between Kernel and Applications

In this example, two user-space applications are listening to the same netlink multicast group. The kernel module pops up a message through netlink socket to the multicast group, and all the applications receive it. Here is the user-space code:


#include <sys/socket.h>
#include <linux/netlink.h>
#define MAX_PAYLOAD 1024 /* maximum payload size*/
struct sockaddr_nl src_addr, dest_addr;
struct nlmsghdr *nlh = NULL;
struct iovec iov;
int sock_fd;
void main() {
sock_fd=socket(PF_NETLINK, SOCK_RAW, NETLINK_TEST);
memset(&src_addr, 0, sizeof(local_addr));
src_addr.nl_family = AF_NETLINK;
src_addr.nl_pid = getpid(); /* self pid */
/* interested in group 1<<0 */
src_addr.nl_groups = 1;
bind(sock_fd, (struct sockaddr*)&src_addr,
sizeof(src_addr));
memset(&dest_addr, 0, sizeof(dest_addr));
nlh = (struct nlmsghdr *)malloc(
NLMSG_SPACE(MAX_PAYLOAD));
memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));

iov.iov_base = (void *)nlh;
iov.iov_len = NLMSG_SPACE(MAX_PAYLOAD);
msg.msg_name = (void *)&dest_addr;
msg.msg_namelen = sizeof(dest_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
printf("Waiting for message from kernel\n");
/* Read message from kernel */
recvmsg(fd, &msg, 0);
printf(" Received message payload: %s\n",
NLMSG_DATA(nlh));
close(sock_fd);
}


And, here is the kernel code:


#define MAX_PAYLOAD 1024
struct sock *nl_sk = NULL;
void netlink_test() {
sturct sk_buff *skb = NULL;
struct nlmsghdr *nlh;
int err;
nl_sk = netlink_kernel_create(NETLINK_TEST,
nl_data_ready);
skb=alloc_skb(NLMSG_SPACE(MAX_PAYLOAD),GFP_KERNEL);
nlh = (struct nlmsghdr *)skb->data;
nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
nlh->nlmsg_pid = 0; /* from kernel */
nlh->nlmsg_flags = 0;
strcpy(NLMSG_DATA(nlh), "Greeting from kernel!");
/* sender is in group 1<<0 */
NETLINK_CB(skb).groups = 1;
NETLINK_CB(skb).pid = 0; /* from kernel */
NETLINK_CB(skb).dst_pid = 0; /* multicast */
/* to mcast group 1<<0 */
NETLINK_CB(skb).dst_groups = 1;
/*multicast the message to all listening processes*/
netlink_broadcast(nl_sk, skb, 0, 1, GFP_KERNEL);
sock_release(nl_sk->socket);
}


Assuming the user-space code is compiled into the executable nl_recv, we can run two instances of nl_recv:


./nl_recv &
Waiting for message from kernel
./nl_recv &
Waiting for message from kernel


Then, after we load the kernel module that executes the kernel-space code, both instances of nl_recv should receive the following message:

Received message payload: Greeting from kernel!
Received message payload: Greeting from kernel!


Conclusion

Netlink socket is a flexible interface for communication between user-space applications and kernel modules. It provides an easy-to-use socket API to both applications and the kernel. It provides advanced communication features, such as full-duplex, buffered I/O, multicast and asynchronous communication, which are absent in other kernel/user-space IPCs.

Kevin Kaichuan He (hek_u5@yahoo.com) is a principal software engineer at Solustek Corp. He currently is working on embedded system, device driver and networking protocols projects. His previous work experience includes senior software engineer at Cisco Systems and research assistant at CS, Purdue University. In his spare time, he enjoys digital photography, PS2 games and literature.

The URL of this article: http://www.linuxjournal.com/article/7356

posted @ 2005-12-17 17:31 幽灵狼 阅读(2726) | 评论 (1)编辑 收藏

2005年12月14日

buf(9) manual

posted @ 2005-12-14 11:19 幽灵狼 阅读(360) | 评论 (0)编辑 收藏

2005年11月20日

related url:
http://www.pingwales.co.uk/2005/07/15/Project-Evil.html
http://lists.freebsd.org/pipermail/freebsd-hardware/2004-January/001005.html

In this article:
Introducing Evil
How does it work?
Building the kernel modules
The old way
The new way

Introducing Evil

One of the problems plaguing the Free Software community is the availability of device drivers. Unless an operating system has a significant market share, it does not make economic sense for a manufacturer to write device drivers for that system. Many manufacturers won't even provide documentation allowing open source drivers to be written, claiming that it would require disclosure of valuable intellectual property.

In the case of WiFi cards, this can be a problem. It is very difficult to tell in advance which chipset is used in a given card - some manufacturers change the hardware completely without changing the model number - and so finding a WiFi card compatible with your favourite OS can be difficult.

OpenBSD has a strong ideological attitude in this respect. If a manufacturer is not willing to release documentation, then they will not include closed-source drivers. This argument makes sense from a security point of view - if the drivers are closed then you can't audit them and so they may end up compromising the base system.

FreeBSD is more pragmatic. They include Project Evil, a partial implementation of the Windows driver API, which allows Windows drivers to be used for network cards. While not quite as useful as a native driver, they are a significant improvement over no driver at all.

How does it work?

Project Evil provides a set of basic functions commonly used by Windows network drivers. These functions are then translated internally to the FreeBSD driver model. To the driver, it appears that it is running in a normal Windows environment. To the OS, it appears that a native FreeBSD kernel module containing the driver is present.

On Windows, a WiFi driver comes in three components. The driver itself usually has the extension .sys. There is also a .inf file which contains information about the driver, such as the device ID of the hardware. Finally there is a copy of the driver firmware.

Traditionally, the firmware - software embedded in the device - for a network interface would be burned into ROM and shipped with the card. Then it was realised that the ability to update the firmware was desirable and so it was put in Flash, or similar. In modern, low budget, cards, the Flash is left off, and the firmware is stored in RAM. This means that the driver must load it before the card can be used.

To make matters more complicated, some drivers have separate firmware for the ethernet controller and radio portions of the firmware. Firmware files usually have the .bin extension.

Building the kernel modules

You will need a copy of the Windows driver. This will probably be on a CD included with your network card, or available from the manufacturer&apos;s web site. You should copy everything with a .sys, .inf, or .bin extension to /sys/modules/if_ndis.

I will use the file names of my driver for the rest of this tutorial, but you should substitute your own. The files supplied for my card are:

Fw1130.bin
Network interface firmware.
FwRad16.bin
Radio firmware.
TNET1130.INF
Driver information file.
tnet1130.sys
Driver binary.

The way of generating Project Evil kernel modules changed between FreeBSD 5.3 and FreeBSD 5.4, and unfortunately the documentation shipped with 5.4 still reflects the 5.3 method which no longer works. I will explain both methods.

It might be worth upgrading to -STABLE before you start, as work on Project Evil is constantly in progress - my interface wouldn't work with FreeBSD 5.3, but it would with a snapshot of -STABLE a couple of weeks after the release.

The old way

Before you start you will need to have the kernel sources for the release you are running installed.

The old way of installing a Project Evil module required you to build three different modules - the ndis stub driver, a specific driver for your card, and a module containing the firmware. This can be done with the following commands:

# cd /sys/modules/ndis
# make depend
...
# make
...
# make install
...
# cd ../if_ndis
# ndiscvt -i TNET1130.INF -s tnet1130.sys 
-f Fw1130.bin -o ndis_driver_data.h
...
# make depend
...
# make
...
# make install
# ndiscvt -f FwRad16.bin
# cp FwRad16.bin.ko /boot/kernel

The driver should now be installed. The next step is to test it. The driver will not work if it can't find the firmware, so the order in which these are loaded is important.

# kldload FwRad16.bin
# kldload if_ndis

The driver should now be loaded. The easiest way to configure the adapter is to run /stand/sysinstall and follow the instructions.

If you want your driver to load every time you reboot (which you probably do) you can add it to /boot/loader.conf. You will need to add a line for each module, so you should end up with something that looks like this:

FwRad16.bin_load="YES"
if_ndis_load="YES"

The new way

The new way doesn&apos;t require the kernel sources installed. The ndis and if_ndis kernel modules should already be installed. You will need to create one module for your card, which will contain the driver and the firmware. This is handled by an undocumented wizard called ndisgen.

# ndisgen

This will ask you for the location of your driver and firmware files. Note that they are case-sensitive and require full paths. At the end, it will create a single .ko file. In my case, this was tnet1130_sys.ko. You need to move this module to a location where it can be found by kldload, and then load it.

# cp tnet1130_sys.ko /boot/kernel/
# kldload ndis
# kldload if_ndis
# kldload tnet1130_sys

Note the order of the kldload statements. It is very important that they be performed in this order. Attempting to load the network card driver before the ndis stub driver can result in a kernel panic.

As with the old way, you load the driver at boot by adding it to /boot/loader.conf. You will need to add a line for each module of the three modules, so you should end up with something that looks like this:

ndis_load="YES"
if_ndis_load="YES"
tnet1130_sys_load="YES"

You can now reboot and have your network card available at boot time. As before, use /stand/sysinstall to set up the interface.

If you've found this article helpful, and would like to see similar tutorials on a particular topic, send your suggestions and requests to &#x66&#x65&#x61t&#x75&#x72es@p&#x69&#x6Egwal&#x65s&#x2E&#x63&#x6F.uk

posted @ 2005-11-20 21:52 幽灵狼 阅读(435) | 评论 (0)编辑 收藏

2005年11月19日

(pronounced as separate letters) Short for demilitarized zone, a computer or small subnetwork that sits between a trusted internal network, such as a corporate private LAN, and an untrusted external network, such as the public Internet.

Typically, the DMZ contains devices accessible to Internet traffic, such as Web (HTTP ) servers, FTP servers, SMTP (e-mail) servers and DNS servers.

The term comes from military use, meaning a buffer area between two enemies.

posted @ 2005-11-19 10:28 幽灵狼 阅读(235) | 评论 (0)编辑 收藏