1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3* Copyright (c) Ulrich Drepper <drepper@redhat.com>
4* Copyright (c) International Business Machines Corp., 2009
5*/
6
7/*
8* Test Name:	socket02
9*
10* Description:
11* This program tests the new flag SOCK_CLOEXEC and SOCK_NONBLOCK introduced
12* in socket() in kernel 2.6.27.
13*/
14
15#include <stdio.h>
16#include <unistd.h>
17#include <netinet/in.h>
18#include <sys/socket.h>
19#include "lapi/fcntl.h"
20#include "tst_test.h"
21
22static int fd;
23
24static struct tcase {
25	int type;
26	int flag;
27	int fl_flag;
28	char *des;
29} tcases[] = {
30	{SOCK_STREAM, 0, F_GETFD, "no close-on-exec"},
31	{SOCK_STREAM | SOCK_CLOEXEC, FD_CLOEXEC, F_GETFD, "close-on-exec"},
32	{SOCK_STREAM, 0, F_GETFL, "no non-blocking"},
33	{SOCK_STREAM | SOCK_NONBLOCK, O_NONBLOCK, F_GETFL, "non-blocking"}
34};
35
36static void verify_socket(unsigned int n)
37{
38	int res;
39	struct tcase *tc = &tcases[n];
40
41	fd = socket(PF_INET, tc->type, 0);
42	if (fd == -1)
43		tst_brk(TFAIL | TERRNO, "socket() failed");
44
45	res = SAFE_FCNTL(fd, tc->fl_flag);
46
47	if (tc->flag != 0 && (res & tc->flag) == 0) {
48		tst_res(TFAIL, "socket() failed to set %s flag", tc->des);
49		return;
50	}
51
52	if (tc->flag == 0 && (res & tc->flag) != 0) {
53		tst_res(TFAIL, "socket() failed to set %s flag", tc->des);
54		return;
55	}
56
57	tst_res(TPASS, "socket() passed to set %s flag", tc->des);
58
59	SAFE_CLOSE(fd);
60}
61
62static void cleanup(void)
63{
64	if (fd > 0)
65		SAFE_CLOSE(fd);
66}
67
68static struct tst_test test = {
69	.tcnt = ARRAY_SIZE(tcases),
70	.test = verify_socket,
71	.cleanup = cleanup
72};
73