Socket Basic Framework
0.1. socket type
socket is a widely used in kernel/net. There are many kind of sockets with different ‘family/proto’. They can be divided by family, and under each family, there are many kinds of proto. such as inet(ipv4)/stream, netlink/(xfrm, rt).
0.2. Data struct && method
0.2.1. net_proto_family
The net_proto_family is used to register a socket family.
1 | |
such as inet(ipv4), netlink, unix_socket, pf_packet(tcpdump socket) …
EX: netlink family
1 | |
All the socket families are registered to net_families by int sock_register(const struct net_proto_family *ops)
1 | |
See later section for detail.
0.2.2. struct proto_ops
proto_ops is used to define the detail operation, such as bind/connect/accept and so on. every socket has a specificed proto_ops.
1 | |
0.2.3. struct proto
1 | |
Currently, I only found the obj_size/slab is useful.
1 | |
When create a socket in socket_create, we alloc a struct sock, in fact, we alloc a memory whose size is obj_size from the slab.
ex:netlink_sock, its first element is struct sock sk;, thus we can use nlk_sk to get a struct netlink_sock from a struct sock.
1 | |
1 | |
sometimes struct proto_ops will call the struct proto
ex: .getsockopt (todo)
0.2.4. socket vs sock
What is sock used for? sock is the internel representation “network layer representation of sockets” Which is used in kernel internel.
What is socket used for? “struct socket – general BSD socket” It is a very high layer abtractation, has very little and common information, such as: state, file(socket is a file for user space), flag, ops(proto ops). each of them has a pointer in its struct which points to peer.
PIC for sock and socket
0.2.5. socket->sk
struct socket - general BSD socket
1 | |
0.2.6. void sock_init_data(struct socket *sock, struct sock *sk)
1 | |
0.3. Socket Related Initialization
0.3.1. net_families and socket_register
each of the socket family initialization, sock_register is called to register a handler.
1 | |
1 | |
0.4. socket related system call
0.4.1. syscall
In kennel(ver 3.4), the syscall are defined in net/socket.c
1 | |
ex: netlink socket register.
1 | |
0.4.2. socket system call socket
sock_create is a very basic and important method.
When create a socket, we dedicate the its family/proto, The create method of the corresponding net_proto_family is called, and set the socket->ops with corresponding struct proto_ops.
1 | |
See detail:
0.4.3. SYSCALL_DEFINE3(socket
1 | |
0.4.3.1. int sock_create(...)
1 | |
1 | |
NOTE:
1 | |
What is pf->create(…)?
For netlink socket, pf->create is netlink_create.
0.4.4. socket system call listen
Most of them are simple, and just call respond function by ops->xxx.
ex: listen
1 | |
The import ops is inited in function sock_create
ex: the ops in netlink socket.
1 | |
1 | |
0.4.5. other socket system call
the socket related sytem call has similar source, just like sock->ops->listen(…)