tools/testing/selftests/net/getsockopt_iter.c

Source file repositories/reference/linux-study-clean/tools/testing/selftests/net/getsockopt_iter.c

File Facts

System
Linux kernel
Corpus path
tools/testing/selftests/net/getsockopt_iter.c
Extension
.c
Size
6280 bytes
Lines
301
Domain
Support Tooling And Documentation
Bucket
tools
Inferred role
Support Tooling And Documentation: implementation source
Status
source implementation candidate

Why This File Exists

Repository support layer: documentation, build tooling, samples, user-space helper tools, generated initramfs support, licenses, and validation utilities.

Dependency Surface

Detected Declarations

Annotated Snippet

// SPDX-License-Identifier: GPL-2.0
/*
 * Quick test for getsockopt{_iter} tests.
 *
 * Each fixture targets one converted protocol and pins down the
 * returned-length / errno semantics across buffer-size variations,
 * an unknown optname and a bogus level.
 *
 * - netlink: NETLINK_PKTINFO covers the flag-style int path; the
 *   NETLINK_LIST_MEMBERSHIPS cases cover the size-discovery path
 *   that always reports the required buffer length back via optlen,
 *   even when the user buffer is too small to receive any group bits.
 * - vsock:   SO_VM_SOCKETS_BUFFER_SIZE covers the u64 path.
 *
 * Author: Breno Leitao <leitao@debian.org>
 */

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/time_types.h>
#include <linux/vm_sockets.h>
#include <sys/socket.h>
#include "kselftest_harness.h"

#ifndef AF_VSOCK
#define AF_VSOCK 40
#endif

/* ---------- netlink ---------- */

FIXTURE(netlink)
{
	int fd;
};

FIXTURE_SETUP(netlink)
{
	int group = RTNLGRP_LINK;

	self->fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
	if (self->fd < 0)
		SKIP(return, "AF_NETLINK socket: %s", strerror(errno));

	/* Joining a multicast group grows nlk->ngroups so the
	 * NETLINK_LIST_MEMBERSHIPS path has a non-zero size to report.
	 */
	if (setsockopt(self->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
		       &group, sizeof(group)) < 0)
		SKIP(return, "NETLINK_ADD_MEMBERSHIP: %s", strerror(errno));
}

FIXTURE_TEARDOWN(netlink)
{
	if (self->fd >= 0)
		close(self->fd);
}

TEST_F(netlink, pktinfo_exact)
{
	socklen_t optlen;
	int val = -1;

	optlen = sizeof(val);

	ASSERT_EQ(0, getsockopt(self->fd, SOL_NETLINK, NETLINK_PKTINFO,
				&val, &optlen));
	ASSERT_EQ(sizeof(int), optlen);
	ASSERT_TRUE(val == 0 || val == 1);
}

TEST_F(netlink, pktinfo_oversize_clamped)
{
	char buf[16] = {};
	socklen_t optlen;

	optlen = sizeof(buf);

	ASSERT_EQ(0, getsockopt(self->fd, SOL_NETLINK, NETLINK_PKTINFO,
				buf, &optlen));
	ASSERT_EQ(sizeof(int), optlen);
}

TEST_F(netlink, pktinfo_undersize)
{
	char buf[2] = {};

Annotation

Implementation Notes