// SPDX-License-Identifier: GPL-2.0-or-later /* * 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. * * PF_INET protocol family socket handler. * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Florian La Roche, <flla@stud.uni-sb.de> * Alan Cox, <A.Cox@swansea.ac.uk> * * Changes (see also sock.c) * * piggy, * Karl Knutson : Socket protocol table * A.N.Kuznetsov : Socket death error in accept(). * John Richardson : Fix non blocking error in connect() * so sockets that fail to connect * don't return -EINPROGRESS. * Alan Cox : Asynchronous I/O support * Alan Cox : Keep correct socket pointer on sock * structures * when accept() ed * Alan Cox : Semantics of SO_LINGER aren't state * moved to close when you look carefully. * With this fixed and the accept bug fixed * some RPC stuff seems happier. * Niibe Yutaka : 4.4BSD style write async I/O * Alan Cox, * Tony Gale : Fixed reuse semantics. * Alan Cox : bind() shouldn't abort existing but dead * sockets. Stops FTP netin:.. I hope. * Alan Cox : bind() works correctly for RAW sockets. * Note that FreeBSD at least was broken * in this respect so be careful with * compatibility tests... * Alan Cox : routing cache support * Alan Cox : memzero the socket structure for * compactness. * Matt Day : nonblock connect error handler * Alan Cox : Allow large numbers of pending sockets * (eg for big web sites), but only if * specifically application requested. * Alan Cox : New buffering throughout IP. Used * dumbly. * Alan Cox : New buffering now used smartly. * Alan Cox : BSD rather than common sense * interpretation of listen. * Germano Caronni : Assorted small races. * Alan Cox : sendmsg/recvmsg basic support. * Alan Cox : Only sendmsg/recvmsg now supported. * Alan Cox : Locked down bind (see security list). * Alan Cox : Loosened bind a little. * Mike McLagan : ADD/DEL DLCI Ioctls * Willy Konynenberg : Transparent proxying support. * David S. Miller : New socket lookup architecture. * Some other random speedups. * Cyrus Durgin : Cleaned up file for kmod hacks. * Andi Kleen : Fix inet_stream_connect TCP race.
*/
/* The inetsw table contains everything that inet_create needs to * build a new socket.
*/ staticstruct list_head inetsw[SOCK_MAX]; static DEFINE_SPINLOCK(inetsw_lock);
/* * The routines beyond this point handle the behaviour of an AF_INET * socket object. Mostly it punts to the subprotocols of IP to do * the work.
*/
/* * Automatically bind an unbound socket.
*/
staticint inet_autobind(struct sock *sk)
{ struct inet_sock *inet; /* We may need to bind the socket. */
lock_sock(sk);
inet = inet_sk(sk); if (!inet->inet_num) { if (sk->sk_prot->get_port(sk, 0)) {
release_sock(sk); return -EAGAIN;
}
inet->inet_sport = htons(inet->inet_num);
}
release_sock(sk); return 0;
}
int __inet_listen_sk(struct sock *sk, int backlog)
{ unsignedchar old_state = sk->sk_state; int err, tcp_fastopen;
if (!((1 << old_state) & (TCPF_CLOSE | TCPF_LISTEN))) return -EINVAL;
WRITE_ONCE(sk->sk_max_ack_backlog, backlog); /* Really, if the socket is already in listen state * we can only allow the backlog to be adjusted.
*/ if (old_state != TCP_LISTEN) { /* Enable TFO w/o requiring TCP_FASTOPEN socket option. * Note that only TCP sockets (SOCK_STREAM) will reach here. * Also fastopen backlog may already been set via the option * because the socket was in TCP_LISTEN state previously but * was shutdown() rather than close().
*/
tcp_fastopen = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_fastopen); if ((tcp_fastopen & TFO_SERVER_WO_SOCKOPT1) &&
(tcp_fastopen & TFO_SERVER_ENABLE) &&
!inet_csk(sk)->icsk_accept_queue.fastopenq.max_qlen) {
fastopen_queue_tune(sk, backlog);
tcp_fastopen_init_key_once(sock_net(sk));
}
err = inet_csk_listen_start(sk); if (err) return err;
staticint inet_create(struct net *net, struct socket *sock, int protocol, int kern)
{ struct sock *sk; struct inet_protosw *answer; struct inet_sock *inet; struct proto *answer_prot; unsignedchar answer_flags; int try_loading_module = 0; int err;
if (protocol < 0 || protocol >= IPPROTO_MAX) return -EINVAL;
sock->state = SS_UNCONNECTED;
/* Look for the requested type/protocol pair. */
lookup_protocol:
err = -ESOCKTNOSUPPORT;
rcu_read_lock();
list_for_each_entry_rcu(answer, &inetsw[sock->type], list) {
err = 0; /* Check the non-wild match. */ if (protocol == answer->protocol) { if (protocol != IPPROTO_IP) break;
} else { /* Check for the two wild cases. */ if (IPPROTO_IP == protocol) {
protocol = answer->protocol; break;
} if (IPPROTO_IP == answer->protocol) break;
}
err = -EPROTONOSUPPORT;
}
if (unlikely(err)) { if (try_loading_module < 2) {
rcu_read_unlock(); /* * Be more specific, e.g. net-pf-2-proto-132-type-1 * (net-pf-PF_INET-proto-IPPROTO_SCTP-type-SOCK_STREAM)
*/ if (++try_loading_module == 1)
request_module("net-pf-%d-proto-%d-type-%d",
PF_INET, protocol, sock->type); /* * Fall back to generic, e.g. net-pf-2-proto-132 * (net-pf-PF_INET-proto-IPPROTO_SCTP)
*/ else
request_module("net-pf-%d-proto-%d",
PF_INET, protocol); goto lookup_protocol;
} else goto out_rcu_unlock;
}
if (inet->inet_num) { /* It assumes that any protocol which allows * the user to assign a number at socket * creation time automatically * shares.
*/
inet->inet_sport = htons(inet->inet_num); /* Add to protocol hash chains. */
err = sk->sk_prot->hash(sk); if (err) goto out_sk_release;
}
if (sk->sk_prot->init) {
err = sk->sk_prot->init(sk); if (err) goto out_sk_release;
}
/* * The peer socket should always be NULL (or else). When we call this * function we are destroying the object and from then on nobody * should refer to it.
*/ int inet_release(struct socket *sock)
{ struct sock *sk = sock->sk;
if (sk) { long timeout;
if (!sk->sk_kern_sock)
BPF_CGROUP_RUN_PROG_INET_SOCK_RELEASE(sk);
/* Applications forget to leave groups before exiting */
ip_mc_drop_socket(sk);
/* If linger is set, we don't return until the close * is complete. Otherwise we return immediately. The * actually closing is done the same either way. * * If the close is due to the process exiting, we never * linger..
*/
timeout = 0; if (sock_flag(sk, SOCK_LINGER) &&
!(current->flags & PF_EXITING))
timeout = sk->sk_lingertime;
sk->sk_prot->close(sk, timeout);
sock->sk = NULL;
} return 0;
}
EXPORT_SYMBOL(inet_release);
int inet_bind_sk(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
u32 flags = BIND_WITH_LOCK; int err;
/* If the socket has its own bind function then use it. (RAW) */ if (sk->sk_prot->bind) { return sk->sk_prot->bind(sk, uaddr, addr_len);
} if (addr_len < sizeof(struct sockaddr_in)) return -EINVAL;
/* BPF prog is run before any checks are done so that if the prog * changes context in a wrong way it will be caught.
*/
err = BPF_CGROUP_RUN_PROG_INET_BIND_LOCK(sk, uaddr, &addr_len,
CGROUP_INET4_BIND, &flags); if (err) return err;
return __inet_bind(sk, uaddr, addr_len, flags);
}
int inet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{ return inet_bind_sk(sock->sk, uaddr, addr_len);
}
EXPORT_SYMBOL(inet_bind);
int __inet_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len,
u32 flags)
{ struct sockaddr_in *addr = (struct sockaddr_in *)uaddr; struct inet_sock *inet = inet_sk(sk); struct net *net = sock_net(sk); unsignedshort snum; int chk_addr_ret;
u32 tb_id = RT_TABLE_LOCAL; int err;
if (addr->sin_family != AF_INET) { /* Compatibility games : accept AF_UNSPEC (mapped to AF_INET) * only if s_addr is INADDR_ANY.
*/
err = -EAFNOSUPPORT; if (addr->sin_family != AF_UNSPEC ||
addr->sin_addr.s_addr != htonl(INADDR_ANY)) goto out;
}
/* Not specified by any standard per-se, however it breaks too * many applications when removed. It is unfortunate since * allowing applications to make a non-local bind solves * several problems with systems using dynamic addressing. * (ie. your servers still start up even if your ISDN link * is temporarily down)
*/
err = -EADDRNOTAVAIL; if (!inet_addr_valid_or_nonlocal(net, inet, addr->sin_addr.s_addr,
chk_addr_ret)) goto out;
/* We keep a pair of addresses. rcv_saddr is the one * used by hash lookups, and saddr is used for transmit. * * In the BSD API these are the same except where it * would be illegal to use them (multicast/broadcast) in * which case the sending device address is used.
*/ if (flags & BIND_WITH_LOCK)
lock_sock(sk);
/* Check these errors (active socket, double bind). */
err = -EINVAL; if (sk->sk_state != TCP_CLOSE || inet->inet_num) goto out_release_sock;
inet->inet_rcv_saddr = inet->inet_saddr = addr->sin_addr.s_addr; if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
inet->inet_saddr = 0; /* Use device */
/* Make sure we are allowed to bind here. */ if (snum || !(inet_test_bit(BIND_ADDRESS_NO_PORT, sk) ||
(flags & BIND_FORCE_ADDRESS_NO_PORT))) {
err = sk->sk_prot->get_port(sk, snum); if (err) {
inet->inet_saddr = inet->inet_rcv_saddr = 0; goto out_release_sock;
} if (!(flags & BIND_FROM_BPF)) {
err = BPF_CGROUP_RUN_PROG_INET4_POST_BIND(sk); if (err) {
inet->inet_saddr = inet->inet_rcv_saddr = 0; if (sk->sk_prot->put_port)
sk->sk_prot->put_port(sk); goto out_release_sock;
}
}
}
int inet_dgram_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags)
{ struct sock *sk = sock->sk; conststruct proto *prot; int err;
if (addr_len < sizeof(uaddr->sa_family)) return -EINVAL;
/* IPV6_ADDRFORM can change sk->sk_prot under us. */
prot = READ_ONCE(sk->sk_prot);
if (uaddr->sa_family == AF_UNSPEC) return prot->disconnect(sk, flags);
if (BPF_CGROUP_PRE_CONNECT_ENABLED(sk)) {
err = prot->pre_connect(sk, uaddr, addr_len); if (err) return err;
}
/* Basic assumption: if someone sets sk->sk_err, he _must_ * change state of the socket from TCP_SYN_*. * Connect() does not allow to get error notifications * without closing the socket.
*/ while ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
release_sock(sk);
timeo = wait_woken(&wait, TASK_INTERRUPTIBLE, timeo);
lock_sock(sk); if (signal_pending(current) || !timeo) break;
}
remove_wait_queue(sk_sleep(sk), &wait);
sk->sk_write_pending -= writebias; return timeo;
}
/* * Connect to a remote host. There is regrettably still a little * TCP 'magic' in here.
*/ int __inet_stream_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags, int is_sendmsg)
{ struct sock *sk = sock->sk; int err; long timeo;
/* * uaddr can be NULL and addr_len can be 0 if: * sk is a TCP fastopen active socket and * TCP_FASTOPEN_CONNECT sockopt is set and * we already have a valid cookie for this socket. * In this case, user can call write() after connect(). * write() will invoke tcp_sendmsg_fastopen() which calls * __inet_stream_connect().
*/ if (uaddr) { if (addr_len < sizeof(uaddr->sa_family)) return -EINVAL;
switch (sock->state) { default:
err = -EINVAL; goto out; case SS_CONNECTED:
err = -EISCONN; goto out; case SS_CONNECTING: if (inet_test_bit(DEFER_CONNECT, sk))
err = is_sendmsg ? -EINPROGRESS : -EISCONN; else
err = -EALREADY; /* Fall out of switch with err, set for this state */ break; case SS_UNCONNECTED:
err = -EISCONN; if (sk->sk_state != TCP_CLOSE) goto out;
if (BPF_CGROUP_PRE_CONNECT_ENABLED(sk)) {
err = sk->sk_prot->pre_connect(sk, uaddr, addr_len); if (err) goto out;
}
if (!err && inet_test_bit(DEFER_CONNECT, sk)) goto out;
/* Just entered SS_CONNECTING state; the only * difference is that return value in non-blocking * case is EINPROGRESS, rather than EALREADY.
*/
err = -EINPROGRESS; break;
}
timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) { int writebias = (sk->sk_protocol == IPPROTO_TCP) &&
tcp_sk(sk)->fastopen_req &&
tcp_sk(sk)->fastopen_req->data ? 1 : 0; int dis = sk->sk_disconnects;
/* Error code is set above */ if (!timeo || !inet_wait_for_connect(sk, timeo, writebias)) goto out;
err = sock_intr_errno(timeo); if (signal_pending(current)) goto out;
/* Connection was closed by RST, timeout, ICMP error * or another process disconnected us.
*/ if (sk->sk_state == TCP_CLOSE) goto sock_error;
/* sk->sk_err may be not zero now, if RECVERR was ordered by user * and error was received after socket entered established state. * Hence, it is handled normally after connect() return successfully.
*/
/* * This does both peername and sockname.
*/ int inet_getname(struct socket *sock, struct sockaddr *uaddr, int peer)
{ struct sock *sk = sock->sk; struct inet_sock *inet = inet_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_in *, sin, uaddr); int sin_addr_len = sizeof(*sin);
int inet_shutdown(struct socket *sock, int how)
{ struct sock *sk = sock->sk; int err = 0;
/* This should really check to make sure * the socket is a TCP socket. (WHY AC...)
*/
how++; /* maps 0->1 has the advantage of making bit 1 rcvs and 1->2 bit 2 snds.
2->3 */ if ((how & ~SHUTDOWN_MASK) || !how) /* MAXINT->0 */ return -EINVAL;
switch (sk->sk_state) { case TCP_CLOSE:
err = -ENOTCONN; /* Hack to wake up other listeners, who can poll for
EPOLLHUP, even on eg. unconnected UDP sockets -- RR */
fallthrough; default:
WRITE_ONCE(sk->sk_shutdown, sk->sk_shutdown | how); if (sk->sk_prot->shutdown)
sk->sk_prot->shutdown(sk, how); break;
/* Remaining two branches are temporary solution for missing * close() in multithreaded environment. It is _not_ a good idea, * but we have no choice until close() is repaired at VFS level.
*/ case TCP_LISTEN: if (!(how & RCV_SHUTDOWN)) break;
fallthrough; case TCP_SYN_SENT:
err = sk->sk_prot->disconnect(sk, O_NONBLOCK);
sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED; break;
}
/* Wake up anyone sleeping in poll. */
sk->sk_state_change(sk);
release_sock(sk); return err;
}
EXPORT_SYMBOL(inet_shutdown);
/* * ioctl() calls you can issue on an INET socket. Most of these are * device configuration and stuff and very rarely used. Some ioctls * pass on to the socket itself. * * NOTE: I like the idea of a module for the config stuff. ie ifconfig * loads the devconfigure module does its configuring and unloads it. * There's a good 20K of config code hanging around the kernel.
*/
switch (cmd) { case SIOCADDRT: case SIOCDELRT: if (copy_from_user(&rt, p, sizeof(struct rtentry))) return -EFAULT;
err = ip_rt_ioctl(net, cmd, &rt); break; case SIOCRTMSG:
err = -EINVAL; break; case SIOCDARP: case SIOCGARP: case SIOCSARP:
err = arp_ioctl(net, cmd, (void __user *)arg); break; case SIOCGIFADDR: case SIOCGIFBRDADDR: case SIOCGIFNETMASK: case SIOCGIFDSTADDR: case SIOCGIFPFLAGS: if (get_user_ifreq(&ifr, NULL, p)) return -EFAULT;
err = devinet_ioctl(net, cmd, &ifr); if (!err && put_user_ifreq(&ifr, p))
err = -EFAULT; break;
case SIOCSIFADDR: case SIOCSIFBRDADDR: case SIOCSIFNETMASK: case SIOCSIFDSTADDR: case SIOCSIFPFLAGS: case SIOCSIFFLAGS: if (get_user_ifreq(&ifr, NULL, p)) return -EFAULT;
err = devinet_ioctl(net, cmd, &ifr); break; default: if (sk->sk_prot->ioctl)
err = sk_ioctl(sk, cmd, (void __user *)arg); else
err = -ENOIOCTLCMD; break;
} return err;
}
EXPORT_SYMBOL(inet_ioctl);
/* Upon startup we insert all the elements in inetsw_array[] into * the linked list inetsw.
*/ staticstruct inet_protosw inetsw_array[] =
{
{
.type = SOCK_STREAM,
.protocol = IPPROTO_TCP,
.prot = &tcp_prot,
.ops = &inet_stream_ops,
.flags = INET_PROTOSW_PERMANENT |
INET_PROTOSW_ICSK,
},
/* If we are trying to override a permanent protocol, bail. */
last_perm = &inetsw[p->type];
list_for_each(lh, &inetsw[p->type]) {
answer = list_entry(lh, struct inet_protosw, list); /* Check only the non-wild match. */ if ((INET_PROTOSW_PERMANENT & answer->flags) == 0) break; if (protocol == answer->protocol) goto out_permanent;
last_perm = lh;
}
/* Add the new entry after the last permanent entry if any, so that * the new entry does not override a permanent entry when matched with * a wild-card protocol. But it is allowed to override any existing * non-permanent entry. This means that when we remove this entry, the * system automatically returns to the old behavior.
*/
list_add_rcu(&p->list, last_perm);
out:
spin_unlock_bh(&inetsw_lock);
return;
out_permanent:
pr_err("Attempt to override permanent protocol %d\n", protocol); goto out;
out_illegal:
pr_err("Ignoring attempt to register invalid socket type %d\n",
p->type); goto out;
}
EXPORT_SYMBOL(inet_register_protosw);
if (READ_ONCE(sock_net(sk)->ipv4.sysctl_ip_dynaddr) > 1) {
pr_info("%s(): shifting inet->saddr from %pI4 to %pI4\n",
__func__, &old_saddr, &new_saddr);
}
/* * XXX The only one ugly spot where we need to * XXX really change the sockets identity after * XXX it has entered the hashes. -DaveM * * Besides that, it does not check for connection * uniqueness. Wait for troubles.
*/ return __sk_prot_rehash(sk);
}
iph2 = (struct iphdr *)(p->data + off); /* The above works because, with the exception of the top * (inner most) layer, we only aggregate pkts with the same * hdr length so all the hdrs we'll need to verify will start * at the same offset.
*/ if ((iph->protocol ^ iph2->protocol) |
((__force u32)iph->saddr ^ (__force u32)iph2->saddr) |
((__force u32)iph->daddr ^ (__force u32)iph2->daddr)) {
NAPI_GRO_CB(p)->same_flow = 0; continue;
}
}
/* Note : No need to call skb_gro_postpull_rcsum() here, * as we already checked checksum over ipv4 header was 0
*/
skb_gro_pull(skb, sizeof(*iph));
skb_set_transport_header(skb, skb_gro_offset(skb));
ops = rcu_dereference(inet_offloads[proto]); if (WARN_ON(!ops || !ops->callbacks.gro_complete)) goto out;
/* Only need to add sizeof(*iph) to get to the next hdr below * because any hdr with option will have been flushed in * inet_gro_receive().
*/
err = INDIRECT_CALL_2(ops->callbacks.gro_complete,
tcp4_gro_complete, udp4_gro_complete,
skb, nhoff + sizeof(*iph));
int inet_ctl_sock_create(struct sock **sk, unsignedshort family, unsignedshort type, unsignedchar protocol, struct net *net)
{ struct socket *sock; int rc = sock_create_kern(net, family, type, protocol, &sock);
if (rc == 0) {
*sk = sock->sk;
(*sk)->sk_allocation = GFP_ATOMIC;
(*sk)->sk_use_task_frag = false; /* * Unhash it so that IP input processing does not even see it, * we do not wish this socket to see incoming packets.
*/
(*sk)->sk_prot->unhash(*sk);
} return rc;
}
EXPORT_SYMBOL_GPL(inet_ctl_sock_create);
unsignedlong snmp_fold_field(void __percpu *mib, int offt)
{ unsignedlong res = 0; int i;
for_each_possible_cpu(i)
res += snmp_get_cpu_field(mib, i, offt); return res;
}
EXPORT_SYMBOL_GPL(snmp_fold_field);
#if BITS_PER_LONG==32
u64 snmp_get_cpu_field64(void __percpu *mib, int cpu, int offt,
size_t syncp_offset)
{ void *bhptr; struct u64_stats_sync *syncp;
u64 v; unsignedint start;
bhptr = per_cpu_ptr(mib, cpu);
syncp = (struct u64_stats_sync *)(bhptr + syncp_offset); do {
start = u64_stats_fetch_begin(syncp);
v = *(((u64 *)bhptr) + offt);
} while (u64_stats_fetch_retry(syncp, start));
static __net_init int inet_init_net(struct net *net)
{ /* * Set defaults for local port range
*/
net->ipv4.ip_local_ports.range = 60999u << 16 | 32768u;
seqlock_init(&net->ipv4.ping_group_range.lock); /* * Sane defaults - nobody may create ping sockets. * Boot scripts should set this to distro-specific group.
*/
net->ipv4.ping_group_range.range[0] = make_kgid(&init_user_ns, 1);
net->ipv4.ping_group_range.range[1] = make_kgid(&init_user_ns, 0);
/* Default values for sysctl-controlled parameters. * We set them here, in case sysctl is not compiled.
*/
net->ipv4.sysctl_ip_default_ttl = IPDEFTTL;
net->ipv4.sysctl_ip_fwd_update_priority = 1;
net->ipv4.sysctl_ip_dynaddr = 0;
net->ipv4.sysctl_ip_early_demux = 1;
net->ipv4.sysctl_udp_early_demux = 1;
net->ipv4.sysctl_tcp_early_demux = 1;
net->ipv4.sysctl_nexthop_compat_mode = 1; #ifdef CONFIG_SYSCTL
net->ipv4.sysctl_ip_prot_sock = PROT_SOCK; #endif
/* Some igmp sysctl, whose values are always used */
net->ipv4.sysctl_igmp_max_memberships = 20;
net->ipv4.sysctl_igmp_max_msf = 10; /* IGMP reports for link-local multicast groups are enabled by default */
net->ipv4.sysctl_igmp_llm_reports = 1;
net->ipv4.sysctl_igmp_qrv = 2;
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.