libutil: add O_NOCTTY back to old pty open code
[minix.git] / lib / libc / sys-minix / socket.c
blobe4e29dc21db299ca80f393ebda460cf79923e93d
1 #include <sys/cdefs.h>
2 #include "namespace.h"
4 #ifdef __weak_alias
5 __weak_alias(socket, _socket)
6 #endif
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <signal.h>
11 #include <stdio.h>
12 #include <unistd.h>
13 #include <sys/socket.h>
14 #include <sys/ioc_net.h>
16 #include <net/netlib.h>
17 #include <netinet/in.h>
19 #define DEBUG 0
21 static int _tcp_socket(int protocol);
22 static int _udp_socket(int protocol);
23 static int _uds_socket(int type, int protocol);
25 int socket(int domain, int type, int protocol)
27 #if DEBUG
28 fprintf(stderr, "socket: domain %d, type %d, protocol %d\n",
29 domain, type, protocol);
30 #endif
31 if (domain != AF_INET && domain != AF_UNIX)
33 #if DEBUG
34 fprintf(stderr, "socket: bad domain %d\n", domain);
35 #endif
36 errno= EAFNOSUPPORT;
37 return -1;
40 if (domain == AF_UNIX && (type == SOCK_STREAM ||
41 type == SOCK_DGRAM || type == SOCK_SEQPACKET))
42 return _uds_socket(type, protocol);
44 if (domain == AF_INET && type == SOCK_STREAM)
45 return _tcp_socket(protocol);
47 if (domain == AF_INET && type == SOCK_DGRAM)
48 return _udp_socket(protocol);
50 #if DEBUG
51 fprintf(stderr, "socket: nothing for domain %d, type %d, protocol %d\n",
52 domain, type, protocol);
53 #endif
54 errno= EPROTOTYPE;
55 return -1;
58 static int _tcp_socket(int protocol)
60 int fd;
61 if (protocol != 0 && protocol != IPPROTO_TCP)
63 #if DEBUG
64 fprintf(stderr, "socket(tcp): bad protocol %d\n", protocol);
65 #endif
66 errno= EPROTONOSUPPORT;
67 return -1;
69 fd= open(TCP_DEVICE, O_RDWR);
70 return fd;
73 static int _udp_socket(int protocol)
75 int r, fd, t_errno;
76 struct sockaddr_in sin;
78 if (protocol != 0 && protocol != IPPROTO_UDP)
80 #if DEBUG
81 fprintf(stderr, "socket(udp): bad protocol %d\n", protocol);
82 #endif
83 errno= EPROTONOSUPPORT;
84 return -1;
86 fd= open(UDP_DEVICE, O_RDWR);
87 if (fd == -1)
88 return fd;
90 /* Bind is implict for UDP sockets? */
91 sin.sin_family= AF_INET;
92 sin.sin_addr.s_addr= INADDR_ANY;
93 sin.sin_port= 0;
94 r= bind(fd, (struct sockaddr *)&sin, sizeof(sin));
95 if (r != 0)
97 t_errno= errno;
98 close(fd);
99 errno= t_errno;
100 return -1;
102 return fd;
105 static int _uds_socket(int type, int protocol)
107 int fd, r;
108 if (protocol != 0)
110 #if DEBUG
111 fprintf(stderr, "socket(uds): bad protocol %d\n", protocol);
112 #endif
113 errno= EPROTONOSUPPORT;
114 return -1;
117 fd= open(UDS_DEVICE, O_RDWR);
118 if (fd == -1) {
119 return fd;
122 /* set the type for the socket via ioctl (SOCK_DGRAM,
123 * SOCK_STREAM, SOCK_SEQPACKET, etc)
125 r= ioctl(fd, NWIOSUDSTYPE, &type);
126 if (r == -1) {
127 int ioctl_errno;
129 /* if that failed rollback socket creation */
130 ioctl_errno= errno;
131 close(fd);
133 /* return the error thrown by the call to ioctl */
134 errno= ioctl_errno;
135 return -1;
138 return fd;