some coverity fixes.
[minix.git] / lib / libc / sys-minix / socketpair.c
blobac1d901d781e791d94834a486e626b58ed0f4df5
1 #include <sys/cdefs.h>
2 #include "namespace.h"
4 #include <errno.h>
5 #include <stdio.h>
6 #include <fcntl.h>
7 #include <unistd.h>
8 #include <net/netlib.h>
9 #include <sys/ioc_net.h>
10 #include <sys/socket.h>
11 #include <sys/stat.h>
12 #include <sys/un.h>
14 #ifdef __weak_alias
15 __weak_alias(socketpair, _socketpair)
16 #endif
18 #define DEBUG 0
20 static int _uds_socketpair(int type, int protocol, int sv[2]);
23 * Create a pair of connected sockets
25 int socketpair(int domain, int type, int protocol, int sv[2]) {
27 #if DEBUG
28 fprintf(stderr, "socketpair: domain %d, type %d, protocol %d\n",
29 domain, type, protocol);
30 #endif
32 if (domain != AF_UNIX)
34 errno = EAFNOSUPPORT;
35 return -1;
38 if (domain == AF_UNIX &&
39 (type == SOCK_STREAM || type == SOCK_SEQPACKET))
40 return _uds_socketpair(type, protocol, sv);
42 #if DEBUG
43 fprintf(stderr,
44 "socketpair: nothing for domain %d, type %d, protocol %d\n",
45 domain, type, protocol);
46 #endif
48 errno= EPROTOTYPE;
49 return -1;
52 static int _uds_socketpair(int type, int protocol, int sv[2])
54 dev_t dev;
55 int r, i;
56 struct stat sbuf;
58 if (protocol != 0)
60 #if DEBUG
61 fprintf(stderr, "socketpair(uds): bad protocol %d\n", protocol);
62 #endif
63 errno= EPROTONOSUPPORT;
64 return -1;
67 /* in this 'for' loop two unconnected sockets are created */
68 for (i = 0; i < 2; i++) {
69 sv[i]= open(UDS_DEVICE, O_RDWR);
70 if (sv[i] == -1) {
71 int open_errno = errno;
73 if (i == 1) {
74 /* if we failed to open() the 2nd
75 * socket, we need to close the 1st
77 close(sv[0]);
78 errno = open_errno;
81 return -1;
84 /* set the type for the socket via ioctl
85 * (SOCK_STREAM, SOCK_SEQPACKET, etc)
87 r= ioctl(sv[i], NWIOSUDSTYPE, &type);
88 if (r == -1) {
89 int ioctl_errno;
91 /* if that failed rollback socket creation */
92 ioctl_errno= errno;
93 close(sv[i]);
95 if (i == 1) {
96 /* if we just closed the 2nd socket, we
97 * need to close the 1st
99 close(sv[0]);
102 /* return the error thrown by the call to ioctl */
103 errno= ioctl_errno;
104 return -1;
108 r= fstat(sv[1], &sbuf);
109 if (r == -1) {
110 int fstat_errno;
112 /* if that failed rollback socket creation */
113 fstat_errno= errno;
115 close(sv[0]);
116 close(sv[1]);
118 /* return the error thrown by the call to fstat */
119 errno= fstat_errno;
120 return -1;
123 dev = sbuf.st_dev;
125 /* connect the sockets sv[0] and sv[1] */
126 r= ioctl(sv[0], NWIOSUDSPAIR, &dev);
127 if (r == -1) {
128 int ioctl_errno;
130 /* if that failed rollback socket creation */
131 ioctl_errno= errno;
133 close(sv[0]);
134 close(sv[1]);
136 /* return the error thrown by the call to ioctl */
137 errno= ioctl_errno;
138 return -1;
142 return 0;