Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 #include <stdio.h>
0003 #include <errno.h>
0004 #include <unistd.h>
0005 #include <string.h>
0006 #include <sys/types.h>
0007 #include <sys/socket.h>
0008 #include <netinet/in.h>
0009 
0010 #include "../kselftest.h"
0011 
0012 struct socket_testcase {
0013     int domain;
0014     int type;
0015     int protocol;
0016 
0017     /* 0    = valid file descriptor
0018      * -foo = error foo
0019      */
0020     int expect;
0021 
0022     /* If non-zero, accept EAFNOSUPPORT to handle the case
0023      * of the protocol not being configured into the kernel.
0024      */
0025     int nosupport_ok;
0026 };
0027 
0028 static struct socket_testcase tests[] = {
0029     { AF_MAX,  0,           0,           -EAFNOSUPPORT,    0 },
0030     { AF_INET, SOCK_STREAM, IPPROTO_TCP, 0,                1  },
0031     { AF_INET, SOCK_DGRAM,  IPPROTO_TCP, -EPROTONOSUPPORT, 1  },
0032     { AF_INET, SOCK_DGRAM,  IPPROTO_UDP, 0,                1  },
0033     { AF_INET, SOCK_STREAM, IPPROTO_UDP, -EPROTONOSUPPORT, 1  },
0034 };
0035 
0036 #define ERR_STRING_SZ   64
0037 
0038 static int run_tests(void)
0039 {
0040     char err_string1[ERR_STRING_SZ];
0041     char err_string2[ERR_STRING_SZ];
0042     int i, err;
0043 
0044     err = 0;
0045     for (i = 0; i < ARRAY_SIZE(tests); i++) {
0046         struct socket_testcase *s = &tests[i];
0047         int fd;
0048 
0049         fd = socket(s->domain, s->type, s->protocol);
0050         if (fd < 0) {
0051             if (s->nosupport_ok &&
0052                 errno == EAFNOSUPPORT)
0053                 continue;
0054 
0055             if (s->expect < 0 &&
0056                 errno == -s->expect)
0057                 continue;
0058 
0059             strerror_r(-s->expect, err_string1, ERR_STRING_SZ);
0060             strerror_r(errno, err_string2, ERR_STRING_SZ);
0061 
0062             fprintf(stderr, "socket(%d, %d, %d) expected "
0063                 "err (%s) got (%s)\n",
0064                 s->domain, s->type, s->protocol,
0065                 err_string1, err_string2);
0066 
0067             err = -1;
0068             break;
0069         } else {
0070             close(fd);
0071 
0072             if (s->expect < 0) {
0073                 strerror_r(errno, err_string1, ERR_STRING_SZ);
0074 
0075                 fprintf(stderr, "socket(%d, %d, %d) expected "
0076                     "success got err (%s)\n",
0077                     s->domain, s->type, s->protocol,
0078                     err_string1);
0079 
0080                 err = -1;
0081                 break;
0082             }
0083         }
0084     }
0085 
0086     return err;
0087 }
0088 
0089 int main(void)
0090 {
0091     int err = run_tests();
0092 
0093     return err;
0094 }