1 // SPDX-License-Identifier: GPL-2.0-or-later
2
3 /*
4 * Copyright (c) International Business Machines Corp., 2001
5 */
6
7 #include <stdio.h>
8 #include <unistd.h>
9 #include <errno.h>
10 #include <fcntl.h>
11
12 #include <sys/types.h>
13 #include <sys/socket.h>
14 #include <sys/un.h>
15
16 #include <netinet/in.h>
17
18 #include "tst_test.h"
19
20 int inet_socket;
21 int dev_null;
22
23 struct sockaddr_in sin1, sin2, sin3;
24 struct sockaddr_un sun;
25
26 static struct test_case {
27 int *socket_fd;
28 struct sockaddr *sockaddr;
29 socklen_t salen;
30 int retval;
31 int experrno;
32 char *desc;
33 } tcases[] = {
34 { &inet_socket, (struct sockaddr *)&sin1, 3, -1,
35 EINVAL, "invalid salen" },
36 { &dev_null, (struct sockaddr *)&sin1, sizeof(sin1), -1,
37 ENOTSOCK, "invalid socket" },
38 { &inet_socket, (struct sockaddr *)&sin2, sizeof(sin2), 0,
39 0, "INADDR_ANYPORT"},
40 { &inet_socket, (struct sockaddr *)&sun, sizeof(sun), -1,
41 EAFNOSUPPORT, "UNIX-domain of current directory" },
42 { &inet_socket, (struct sockaddr *)&sin3, sizeof(sin3), -1,
43 EADDRNOTAVAIL, "non-local address" },
44 };
45
verify_bind(unsigned int nr)46 void verify_bind(unsigned int nr)
47 {
48 struct test_case *tcase = &tcases[nr];
49
50 if (tcase->experrno) {
51 TST_EXP_FAIL(bind(*tcase->socket_fd, tcase->sockaddr, tcase->salen),
52 tcase->experrno, "%s", tcase->desc);
53 } else {
54 TST_EXP_PASS(bind(*tcase->socket_fd, tcase->sockaddr, tcase->salen),
55 "%s", tcase->desc);
56 SAFE_CLOSE(inet_socket);
57 inet_socket = SAFE_SOCKET(PF_INET, SOCK_STREAM, 0);
58 }
59 }
60
test_setup(void)61 void test_setup(void)
62 {
63 /* initialize sockaddr's */
64 sin1.sin_family = AF_INET;
65 /* this port must be unused! */
66 sin1.sin_port = TST_GET_UNUSED_PORT(AF_INET, SOCK_STREAM);
67 sin1.sin_addr.s_addr = INADDR_ANY;
68
69 sin2.sin_family = AF_INET;
70 sin2.sin_port = 0;
71 sin2.sin_addr.s_addr = INADDR_ANY;
72
73 sin3.sin_family = AF_INET;
74 sin3.sin_port = 0;
75 /* assumes 10.255.254.253 is not a local interface address! */
76 sin3.sin_addr.s_addr = htonl(0x0AFFFEFD);
77
78 sun.sun_family = AF_UNIX;
79 strncpy(sun.sun_path, ".", sizeof(sun.sun_path));
80
81 inet_socket = SAFE_SOCKET(PF_INET, SOCK_STREAM, 0);
82 dev_null = SAFE_OPEN("/dev/null", O_WRONLY);
83 }
84
test_cleanup(void)85 void test_cleanup(void)
86 {
87 SAFE_CLOSE(inet_socket);
88 SAFE_CLOSE(dev_null);
89 }
90
91 static struct tst_test test = {
92 .tcnt = ARRAY_SIZE(tcases),
93 .setup = test_setup,
94 .cleanup = test_cleanup,
95 .test = verify_bind,
96 };
97