libsocket : Updated sockets to add poll function, also added wrappers for external use
[nit.git] / lib / socket / socket_c.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Low-level socket functionalities
18 module socket_c
19
20 in "C Header" `{
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <string.h>
25 #include <sys/socket.h>
26 #include <sys/types.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 #include <netdb.h>
30 #include <sys/poll.h>
31 #include <errno.h>
32
33 typedef int S_DESCRIPTOR;
34 typedef struct sockaddr_in S_ADDR_IN;
35 typedef struct sockaddr S_ADDR;
36 typedef struct in_addr S_IN_ADDR;
37 typedef struct hostent S_HOSTENT;
38 typedef struct timeval S_TIMEVAL;
39 typedef struct sockaccept_result { S_ADDR_IN addr_in; S_DESCRIPTOR s_desc; } S_ACCEPT_RESULT;
40 typedef fd_set S_FD_SET;
41 typedef socklen_t S_LEN;
42 `}
43
44 # Wrapper for the data structure PollFD used for polling on a socket
45 class PollFD
46
47 # The PollFD object
48 private var poll_struct: FFSocketPollFD
49
50 # A collection of the events to be watched
51 var events: Array[FFSocketPollValues]
52
53 init(pid: Int, events: Array[FFSocketPollValues])
54 do
55 assert events.length >= 1
56 self.events = events
57
58 var events_in_one = events[0]
59
60 for i in [1 .. events.length-1] do
61 events_in_one += events[i]
62 end
63
64 self.poll_struct = new FFSocketPollFD(pid, events_in_one)
65 end
66
67 # Reads the response and returns an array with the type of events that have been found
68 private fun check_response(response: Int): Array[FFSocketPollValues]
69 do
70 var resp_array = new Array[FFSocketPollValues]
71 for i in events do
72 if c_check_resp(response, i) != 0 then
73 resp_array.push(i)
74 end
75 end
76 return resp_array
77 end
78
79 # Checks if the poll call has returned true for a particular type of event
80 private fun c_check_resp(response: Int, mask: FFSocketPollValues): Int
81 `{
82 return response & mask;
83 `}
84
85 end
86
87 # Data structure used by the poll function
88 private extern FFSocketPollFD `{ struct pollfd `}
89 # File descriptor id
90 private fun fd: Int `{ return recv.fd; `}
91 # List of events to be watched
92 private fun events: Int `{ return recv.events; `}
93 # List of events received by the last poll function
94 private fun revents: Int `{ return recv.revents; `}
95
96 new (pid: Int, events: FFSocketPollValues) `{
97 struct pollfd poll;
98 poll.fd = pid;
99 poll.events = events;
100 return poll;
101 `}
102
103 end
104
105 extern FFSocket `{ S_DESCRIPTOR* `}
106 new socket(domain: FFSocketAddressFamilies, socketType: FFSocketTypes, protocol: FFSocketProtocolFamilies) `{
107 S_DESCRIPTOR *d = NULL; d = (S_DESCRIPTOR*) malloc( sizeof(S_DESCRIPTOR) );
108 int ds = socket(domain, socketType, protocol);
109 memcpy(d, &ds, sizeof(ds));
110 return d;
111 `}
112 fun destroy `{ free(recv); `}
113 fun close: Int `{ return close( *recv ); `}
114 fun descriptor: Int `{ return *recv; `}
115 fun errno: Int `{ return errno; `}
116
117 fun gethostbyname(n: String): FFSocketHostent import String::to_cstring `{ return gethostbyname(String_to_cstring(n)); `}
118 fun connect(addrIn: FFSocketAddrIn): Int `{ return connect( *recv, (S_ADDR*)addrIn, sizeof(*addrIn) ); `}
119 fun write(buffer: String): Int import String::to_cstring, String::length `{ return write(*recv, (char*)String_to_cstring(buffer), String_length(buffer)); `}
120
121 fun read: String `{
122 char c[1024];
123 int n = read(*recv, c, (sizeof(c)-1));
124 if(n < 0) exit(-1);
125 c[n] = '\0';
126 return new_String_from_cstring(c);
127 `}
128
129 fun bind(addrIn: FFSocketAddrIn): Int `{ return bind(*recv, (S_ADDR*)addrIn, sizeof(*addrIn)); `}
130 fun listen(size: Int): Int `{ return listen(*recv, size); `}
131
132 # Checks if the buffer is ready for any event specified when creating the pollfd structure
133 fun socket_poll(filedesc: PollFD, timeout: Int): Array[FFSocketPollValues]
134 do
135 var result = i_poll(filedesc.poll_struct, timeout)
136 assert result != -1
137 return filedesc.check_response(result)
138 end
139
140 # Call to the poll function of the C socket
141 #
142 # Signature :
143 # int poll(struct pollfd fds[], nfds_t nfds, int timeout);
144 #
145 # Official documentation of the poll function :
146 #
147 # The poll() function provides applications with a mechanism for multiplexing input/output over a set of file descriptors.
148 # For each member of the array pointed to by fds, poll() shall examine the given file descriptor for the event(s) specified in events.
149 # The number of pollfd structures in the fds array is specified by nfds.
150 # The poll() function shall identify those file descriptors on which an application can read or write data, or on which certain events have occurred.
151 # The fds argument specifies the file descriptors to be examined and the events of interest for each file descriptor.
152 # It is a pointer to an array with one member for each open file descriptor of interest.
153 # The array's members are pollfd structures within which fd specifies an open file descriptor and events and revents are bitmasks constructed by
154 # OR'ing a combination of the pollfd flags.
155 private fun i_poll(filedesc: FFSocketPollFD, timeout: Int): Int `{
156 int poll_return = poll(&filedesc, 1, timeout);
157 return poll_return;
158 `}
159
160 private fun i_accept(addrIn: FFSocketAddrIn): FFSocket `{
161 S_LEN s = sizeof(S_ADDR);
162 S_DESCRIPTOR *d = NULL;
163 d = malloc(sizeof(S_DESCRIPTOR*));
164 *d = accept(*recv,(S_ADDR*)addrIn, &s);
165 return d;
166 `}
167 fun accept: FFSocketAcceptResult
168 do
169 var addrIn = new FFSocketAddrIn
170 var s = i_accept(addrIn)
171 return new FFSocketAcceptResult(s, addrIn)
172 end
173 end
174
175 extern FFSocketAcceptResult `{ S_ACCEPT_RESULT* `}
176 new (socket: FFSocket, addrIn: FFSocketAddrIn) `{
177 S_ACCEPT_RESULT *sar = NULL;
178 sar = malloc( sizeof(S_ACCEPT_RESULT*) );
179 sar->s_desc = *socket;
180 sar->addr_in = *addrIn;
181 return sar;
182 `}
183 fun socket: FFSocket `{ return &recv->s_desc; `}
184 fun addrIn: FFSocketAddrIn `{ return &recv->addr_in; `}
185 fun destroy `{ free(recv); `}
186 end
187
188 extern FFSocketAddrIn `{ S_ADDR_IN* `}
189 new `{
190 S_ADDR_IN *sai = NULL;
191 sai = malloc( sizeof(S_ADDR_IN*) );
192 return sai;
193 `}
194 new with(port: Int, family: FFSocketAddressFamilies) `{
195 S_ADDR_IN *sai = NULL;
196 sai = malloc( sizeof(S_ADDR_IN*) );
197 sai->sin_family = family;
198 sai->sin_port = htons(port);
199 sai->sin_addr.s_addr = INADDR_ANY;
200 return sai;
201 `}
202 new with_hostent(hostent: FFSocketHostent, port: Int) `{
203 S_ADDR_IN *sai = NULL;
204 sai = malloc( sizeof(S_ADDR_IN*) );
205 sai->sin_family = hostent->h_addrtype;
206 sai->sin_port = htons(port);
207 memcpy( (char*)&sai->sin_addr.s_addr, (char*)hostent->h_addr, hostent->h_length );
208 return sai;
209 `}
210 fun address: String `{ return new_String_from_cstring( (char*)inet_ntoa(recv->sin_addr) ); `}
211 fun family: FFSocketAddressFamilies `{ return recv->sin_family; `}
212 fun port: Int `{ return ntohs(recv->sin_port); `}
213 fun destroy `{ free(recv); `}
214 end
215
216 extern FFSocketHostent `{ S_HOSTENT* `}
217 private fun i_h_aliases(i: Int): String `{ return new_String_from_cstring(recv->h_aliases[i]); `}
218 private fun i_h_aliases_reachable(i: Int): Bool `{ return (recv->h_aliases[i] != NULL); `}
219 fun h_aliases: Array[String]
220 do
221 var i=0
222 var d=new Array[String]
223 loop
224 d.add(i_h_aliases(i))
225 if i_h_aliases_reachable(i+1) == false then break
226 i += 1
227 end
228 return d
229 end
230 fun h_addr: String `{ return new_String_from_cstring( (char*)inet_ntoa(*(S_IN_ADDR*)recv->h_addr) ); `}
231 fun h_addrtype: Int `{ return recv->h_addrtype; `}
232 fun h_length: Int `{ return recv->h_length; `}
233 fun h_name: String `{ return new_String_from_cstring(recv->h_name); `}
234 end
235
236 extern FFTimeval `{ S_TIMEVAL* `}
237 new (seconds: Int, microseconds: Int) `{
238 S_TIMEVAL* tv = NULL;
239 tv = malloc( sizeof(S_TIMEVAL*) );
240 tv->tv_sec = seconds;
241 tv->tv_usec = microseconds;
242 return tv;
243 `}
244 fun seconds: Int `{ return recv->tv_sec; `}
245 fun microseconds: Int `{ return recv->tv_usec; `}
246 fun destroy `{ free( recv ); `}
247 end
248
249 extern FFSocketSet `{ S_FD_SET* `}
250 new `{
251 S_FD_SET *f = NULL;
252 f = malloc( sizeof(S_FD_SET*) );
253 return f;
254 `}
255 fun set(s: FFSocket) `{ FD_SET( *s, recv ); `}
256 fun is_set(s: FFSocket): Bool `{ return FD_ISSET( *s, recv ); `}
257 fun zero `{ FD_ZERO( recv ); `}
258 fun clear(s: FFSocket) `{ FD_CLR( *s, recv ); `}
259 fun destroy `{ free( recv ); `}
260 end
261
262 class FFSocketObserver
263 fun select(max: FFSocket, reads: nullable FFSocketSet, write: nullable FFSocketSet,
264 except: nullable FFSocketSet, timeout: FFTimeval): Int `{
265 S_FD_SET *rds, *wts, *exs = NULL;
266 S_TIMEVAL *tm = NULL;
267 if(reads != NULL) rds = (S_FD_SET*)reads;
268 if(write != NULL) wts = (S_FD_SET*)write;
269 if(except != NULL) exs = (S_FD_SET*)except;
270 if(timeout != NULL) tm = (S_TIMEVAL*)timeout;
271 return select(*max, rds, wts, exs, tm);
272 `}
273 end
274
275 extern FFSocketTypes `{ int `}
276 new sock_stream `{ return SOCK_STREAM; `}
277 new sock_dgram `{ return SOCK_DGRAM; `}
278 new sock_raw `{ return SOCK_RAW; `}
279 new sock_seqpacket `{ return SOCK_SEQPACKET; `}
280 end
281 extern FFSocketAddressFamilies `{ int `}
282 new af_null `{ return 0; `}
283 new af_unspec `{ return AF_UNSPEC; `} # unspecified
284 new af_unix `{ return AF_UNIX; `} # local to host (pipes)
285 new af_local `{ return AF_LOCAL; `} # backward compatibility
286 new af_inet `{ return AF_INET; `} # internetwork: UDP, TCP, etc.
287 new af_sna `{ return AF_SNA; `} # IBM SNA
288 new af_decnet `{ return AF_DECnet; `} # DECnet
289 new af_route `{ return AF_ROUTE; `} # Internal Routing Protocol
290 new af_ipx `{ return AF_IPX; `} # Novell Internet Protocol
291 new af_isdn `{ return AF_ISDN; `} # Integrated Services Digital Network
292 new af_inet6 `{ return AF_INET6; `} # IPv6
293 new af_max `{ return AF_MAX; `}
294 end
295 extern FFSocketProtocolFamilies `{ int `}
296 new pf_null `{ return 0; `}
297 new pf_unspec `{ return PF_UNSPEC; `}
298 new pf_local `{ return PF_LOCAL; `}
299 new pf_unix `{ return PF_UNIX; `}
300 new pf_inet `{ return PF_INET; `}
301 new pf_sna `{ return PF_SNA; `}
302 new pf_decnet `{ return PF_DECnet; `}
303 new pf_route `{ return PF_ROUTE; `}
304 new pf_ipx `{ return PF_IPX; `}
305 new pf_isdn `{ return PF_ISDN; `}
306 new pf_key `{ return PF_KEY; `}
307 new pf_inet6 `{ return PF_INET6; `}
308 new pf_max `{ return PF_MAX; `}
309 end
310
311 # Used for the poll function of a socket, mix several Poll values to check for events on more than one type of event
312 extern FFSocketPollValues `{ int `}
313 new pollin `{ return POLLIN; `} # Data other than high-priority data may be read without blocking.
314 new pollrdnorm `{ return POLLRDNORM; `} # Normal data may be read without blocking.
315 new pollrdband `{ return POLLRDBAND; `} # Priority data may be read without blocking.
316 new pollpri `{ return POLLPRI; `} # High-priority data may be read without blocking.
317 new pollout `{ return POLLOUT; `} # Normal data may be written without blocking.
318 new pollwrnorm `{ return POLLWRNORM; `} # Equivalent to POLLOUT
319 new pollwrband `{ return POLLWRBAND; `} # Priority data may be written.
320 new pollerr `{ return POLLERR; `} # An error has occurred on the device or stream. This flag is only valid in the revents bitmask; it shall be ignored in the events member.
321 new pollhup `{ return POLLHUP; `} # The device has been disconnected. This event and POLLOUT are mutually-exclusive; a stream can never be writable if a hangup has occurred. However, this event and POLLIN, POLLRDNORM, POLLRDBAND, or POLLPRI are not mutually-exclusive. This flag is only valid in the revents bitmask; it shall be ignored in the events member.
322 new pollnval `{ return POLLNVAL; `} # The specified fd value is invalid. This flag is only valid in the revents member; it shall ignored in the events member.
323
324 # Combines two FFSocketPollValues
325 private fun +(other: FFSocketPollValues): FFSocketPollValues `{
326 return recv | other;
327 `}
328 end