lib/socket: Bugfix, tried to free a static variable, this provoked a warning when...
[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
32 typedef int S_DESCRIPTOR;
33 typedef struct sockaddr_in S_ADDR_IN;
34 typedef struct sockaddr S_ADDR;
35 typedef struct in_addr S_IN_ADDR;
36 typedef struct hostent S_HOSTENT;
37 typedef struct timeval S_TIMEVAL;
38 typedef struct sockaccept_result { S_ADDR_IN addr_in; S_DESCRIPTOR s_desc; } S_ACCEPT_RESULT;
39 typedef fd_set S_FD_SET;
40 typedef socklen_t S_LEN;
41 `}
42
43 # Wrapper for the data structure PollFD used for polling on a socket
44 class PollFD
45
46 # The PollFD object
47 private var poll_struct: FFSocketPollFD
48
49 # A collection of the events to be watched
50 var events: Array[FFSocketPollValues]
51
52 init(pid: Int, events: Array[FFSocketPollValues])
53 do
54 assert events.length >= 1
55 self.events = events
56
57 var events_in_one = events[0]
58
59 for i in [1 .. events.length-1] do
60 events_in_one += events[i]
61 end
62
63 self.poll_struct = new FFSocketPollFD(pid, events_in_one)
64 end
65
66 # Reads the response and returns an array with the type of events that have been found
67 private fun check_response(response: Int): Array[FFSocketPollValues]
68 do
69 var resp_array = new Array[FFSocketPollValues]
70 for i in events do
71 if c_check_resp(response, i) != 0 then
72 resp_array.push(i)
73 end
74 end
75 return resp_array
76 end
77
78 # Checks if the poll call has returned true for a particular type of event
79 private fun c_check_resp(response: Int, mask: FFSocketPollValues): Int
80 `{
81 return response & mask;
82 `}
83
84 end
85
86 # Data structure used by the poll function
87 private extern FFSocketPollFD `{ struct pollfd `}
88 # File descriptor id
89 private fun fd: Int `{ return recv.fd; `}
90 # List of events to be watched
91 private fun events: Int `{ return recv.events; `}
92 # List of events received by the last poll function
93 private fun revents: Int `{ return recv.revents; `}
94
95 new (pid: Int, events: FFSocketPollValues) `{
96 struct pollfd poll;
97 poll.fd = pid;
98 poll.events = events;
99 return poll;
100 `}
101
102 end
103
104 extern FFSocket `{ S_DESCRIPTOR* `}
105 new socket(domain: FFSocketAddressFamilies, socketType: FFSocketTypes, protocol: FFSocketProtocolFamilies) `{
106 S_DESCRIPTOR *d = NULL; d = (S_DESCRIPTOR*) malloc( sizeof(S_DESCRIPTOR) );
107 int ds = socket(domain, socketType, protocol);
108 if(ds == -1){
109 free(d);
110 return NULL;
111 }
112 memcpy(d, &ds, sizeof(ds));
113 return d;
114 `}
115 fun destroy `{ free(recv); `}
116 fun close: Int `{ return close( *recv ); `}
117 fun descriptor: Int `{ return *recv; `}
118
119 fun gethostbyname(n: String): FFSocketHostent import String.to_cstring `{ return gethostbyname(String_to_cstring(n)); `}
120 fun connect(addrIn: FFSocketAddrIn): Int `{ return connect( *recv, (S_ADDR*)addrIn, sizeof(*addrIn) ); `}
121 fun write(buffer: String): Int import String.to_cstring, String.length `{ return write(*recv, (char*)String_to_cstring(buffer), String_length(buffer)); `}
122
123 fun read: String import NativeString.to_s_with_length `{
124 static char c[1024];
125 int n = read(*recv, c, 1024);
126 if(n < 0) {
127 return NativeString_to_s_with_length("",0);
128 }
129 char* ret = malloc(n + 1);
130 memcpy(ret, c, n);
131 ret[n] = '\0';
132 return NativeString_to_s_with_length(ret, n);
133 `}
134
135 # Sets an option for the socket
136 fun setsockopt(level: FFSocketOptLevels, option_name: FFSocketOptNames, option_value: Int) `{
137 int err = setsockopt(*recv, level, option_name, &option_value, sizeof(int));
138 if(err != 0){
139 perror("Error on setsockopts : ");
140 exit(1);
141 }
142 `}
143
144 fun bind(addrIn: FFSocketAddrIn): Int `{ return bind(*recv, (S_ADDR*)addrIn, sizeof(*addrIn)); `}
145 fun listen(size: Int): Int `{ return listen(*recv, size); `}
146
147 # Checks if the buffer is ready for any event specified when creating the pollfd structure
148 fun socket_poll(filedesc: PollFD, timeout: Int): Array[FFSocketPollValues]
149 do
150 var result = i_poll(filedesc.poll_struct, timeout)
151 assert result != -1
152 return filedesc.check_response(result)
153 end
154
155 # Call to the poll function of the C socket
156 #
157 # Signature :
158 # int poll(struct pollfd fds[], nfds_t nfds, int timeout);
159 #
160 # Official documentation of the poll function :
161 #
162 # The poll() function provides applications with a mechanism for multiplexing input/output over a set of file descriptors.
163 # For each member of the array pointed to by fds, poll() shall examine the given file descriptor for the event(s) specified in events.
164 # The number of pollfd structures in the fds array is specified by nfds.
165 # The poll() function shall identify those file descriptors on which an application can read or write data, or on which certain events have occurred.
166 # The fds argument specifies the file descriptors to be examined and the events of interest for each file descriptor.
167 # It is a pointer to an array with one member for each open file descriptor of interest.
168 # The array's members are pollfd structures within which fd specifies an open file descriptor and events and revents are bitmasks constructed by
169 # OR'ing a combination of the pollfd flags.
170 private fun i_poll(filedesc: FFSocketPollFD, timeout: Int): Int `{
171 int poll_return = poll(&filedesc, 1, timeout);
172 return poll_return;
173 `}
174
175 private fun i_accept(addrIn: FFSocketAddrIn): FFSocket `{
176 S_LEN s = sizeof(S_ADDR);
177 S_DESCRIPTOR *d = NULL;
178 d = malloc(sizeof(S_DESCRIPTOR));
179 *d = accept(*recv,(S_ADDR*)addrIn, &s);
180 return d;
181 `}
182 fun accept: FFSocketAcceptResult
183 do
184 var addrIn = new FFSocketAddrIn
185 var s = i_accept(addrIn)
186 return new FFSocketAcceptResult(s, addrIn)
187 end
188 end
189
190 extern FFSocketAcceptResult `{ S_ACCEPT_RESULT* `}
191 new (socket: FFSocket, addrIn: FFSocketAddrIn) `{
192 S_ACCEPT_RESULT *sar = NULL;
193 sar = malloc( sizeof(S_ACCEPT_RESULT) );
194 sar->s_desc = *socket;
195 sar->addr_in = *addrIn;
196 return sar;
197 `}
198 fun socket: FFSocket `{ return &recv->s_desc; `}
199 fun addrIn: FFSocketAddrIn `{ return &recv->addr_in; `}
200 fun destroy `{ free(recv); `}
201 end
202
203 extern FFSocketAddrIn `{ S_ADDR_IN* `}
204 new `{
205 S_ADDR_IN *sai = NULL;
206 sai = malloc( sizeof(S_ADDR_IN) );
207 return sai;
208 `}
209 new with(port: Int, family: FFSocketAddressFamilies) `{
210 S_ADDR_IN *sai = NULL;
211 sai = malloc( sizeof(S_ADDR_IN) );
212 sai->sin_family = family;
213 sai->sin_port = htons(port);
214 sai->sin_addr.s_addr = INADDR_ANY;
215 return sai;
216 `}
217 new with_hostent(hostent: FFSocketHostent, port: Int) `{
218 S_ADDR_IN *sai = NULL;
219 sai = malloc( sizeof(S_ADDR_IN) );
220 sai->sin_family = hostent->h_addrtype;
221 sai->sin_port = htons(port);
222 memcpy( (char*)&sai->sin_addr.s_addr, (char*)hostent->h_addr, hostent->h_length );
223 return sai;
224 `}
225 fun address: String import NativeString.to_s `{ return NativeString_to_s( (char*)inet_ntoa(recv->sin_addr) ); `}
226 fun family: FFSocketAddressFamilies `{ return recv->sin_family; `}
227 fun port: Int `{ return ntohs(recv->sin_port); `}
228 fun destroy `{ free(recv); `}
229 end
230
231 extern FFSocketHostent `{ S_HOSTENT* `}
232 private fun i_h_aliases(i: Int): String import NativeString.to_s `{ return NativeString_to_s(recv->h_aliases[i]); `}
233 private fun i_h_aliases_reachable(i: Int): Bool `{ return (recv->h_aliases[i] != NULL); `}
234 fun h_aliases: Array[String]
235 do
236 var i=0
237 var d=new Array[String]
238 loop
239 d.add(i_h_aliases(i))
240 if i_h_aliases_reachable(i+1) == false then break
241 i += 1
242 end
243 return d
244 end
245 fun h_addr: String import NativeString.to_s `{ return NativeString_to_s( (char*)inet_ntoa(*(S_IN_ADDR*)recv->h_addr) ); `}
246 fun h_addrtype: Int `{ return recv->h_addrtype; `}
247 fun h_length: Int `{ return recv->h_length; `}
248 fun h_name: String import NativeString.to_s `{ return NativeString_to_s(recv->h_name); `}
249 end
250
251 extern FFTimeval `{ S_TIMEVAL* `}
252 new (seconds: Int, microseconds: Int) `{
253 S_TIMEVAL* tv = NULL;
254 tv = malloc( sizeof(S_TIMEVAL) );
255 tv->tv_sec = seconds;
256 tv->tv_usec = microseconds;
257 return tv;
258 `}
259 fun seconds: Int `{ return recv->tv_sec; `}
260 fun microseconds: Int `{ return recv->tv_usec; `}
261 fun destroy `{ free( recv ); `}
262 end
263
264 extern FFSocketSet `{ S_FD_SET* `}
265 new `{
266 S_FD_SET *f = NULL;
267 f = malloc( sizeof(S_FD_SET) );
268 return f;
269 `}
270 fun set(s: FFSocket) `{ FD_SET( *s, recv ); `}
271 fun is_set(s: FFSocket): Bool `{ return FD_ISSET( *s, recv ); `}
272 fun zero `{ FD_ZERO( recv ); `}
273 fun clear(s: FFSocket) `{ FD_CLR( *s, recv ); `}
274 fun destroy `{ free( recv ); `}
275 end
276
277 class FFSocketObserver
278 fun select(max: FFSocket, reads: nullable FFSocketSet, write: nullable FFSocketSet,
279 except: nullable FFSocketSet, timeout: FFTimeval): Int `{
280 S_FD_SET *rds, *wts, *exs = NULL;
281 S_TIMEVAL *tm = NULL;
282 if(reads != NULL) rds = (S_FD_SET*)reads;
283 if(write != NULL) wts = (S_FD_SET*)write;
284 if(except != NULL) exs = (S_FD_SET*)except;
285 if(timeout != NULL) tm = (S_TIMEVAL*)timeout;
286 return select(*max, rds, wts, exs, tm);
287 `}
288 end
289
290 extern FFSocketTypes `{ int `}
291 new sock_stream `{ return SOCK_STREAM; `}
292 new sock_dgram `{ return SOCK_DGRAM; `}
293 new sock_raw `{ return SOCK_RAW; `}
294 new sock_seqpacket `{ return SOCK_SEQPACKET; `}
295 end
296 extern FFSocketAddressFamilies `{ int `}
297 new af_null `{ return 0; `}
298 new af_unspec `{ return AF_UNSPEC; `} # unspecified
299 new af_unix `{ return AF_UNIX; `} # local to host (pipes)
300 new af_local `{ return AF_LOCAL; `} # backward compatibility
301 new af_inet `{ return AF_INET; `} # internetwork: UDP, TCP, etc.
302 new af_sna `{ return AF_SNA; `} # IBM SNA
303 new af_decnet `{ return AF_DECnet; `} # DECnet
304 new af_route `{ return AF_ROUTE; `} # Internal Routing Protocol
305 new af_ipx `{ return AF_IPX; `} # Novell Internet Protocol
306 new af_isdn `{ return AF_ISDN; `} # Integrated Services Digital Network
307 new af_inet6 `{ return AF_INET6; `} # IPv6
308 new af_max `{ return AF_MAX; `}
309 end
310 extern FFSocketProtocolFamilies `{ int `}
311 new pf_null `{ return 0; `}
312 new pf_unspec `{ return PF_UNSPEC; `}
313 new pf_local `{ return PF_LOCAL; `}
314 new pf_unix `{ return PF_UNIX; `}
315 new pf_inet `{ return PF_INET; `}
316 new pf_sna `{ return PF_SNA; `}
317 new pf_decnet `{ return PF_DECnet; `}
318 new pf_route `{ return PF_ROUTE; `}
319 new pf_ipx `{ return PF_IPX; `}
320 new pf_isdn `{ return PF_ISDN; `}
321 new pf_key `{ return PF_KEY; `}
322 new pf_inet6 `{ return PF_INET6; `}
323 new pf_max `{ return PF_MAX; `}
324 end
325 # Level on which to set options
326 extern FFSocketOptLevels `{ int `}
327 # Dummy for IP (As defined in C)
328 new ip `{ return IPPROTO_IP;`}
329 # Control message protocol
330 new icmp `{ return IPPROTO_ICMP;`}
331 # Use TCP
332 new tcp `{ return IPPROTO_TCP; `}
333 # Socket level options
334 new socket `{ return SOL_SOCKET; `}
335 end
336 # Options for socket, use with setsockopt
337 extern FFSocketOptNames `{ int `}
338 # Enables debugging information
339 new debug `{ return SO_DEBUG; `}
340 # Authorizes the broadcasting of messages
341 new broadcast `{ return SO_BROADCAST; `}
342 # Authorizes the reuse of the local address
343 new reuseaddr `{ return SO_REUSEADDR; `}
344 # Authorizes the use of keep-alive packets in a connection
345 new keepalive `{ return SO_KEEPALIVE; `}
346 end
347 # Used for the poll function of a socket, mix several Poll values to check for events on more than one type of event
348 extern FFSocketPollValues `{ int `}
349 new pollin `{ return POLLIN; `} # Data other than high-priority data may be read without blocking.
350 new pollrdnorm `{ return POLLRDNORM; `} # Normal data may be read without blocking.
351 new pollrdband `{ return POLLRDBAND; `} # Priority data may be read without blocking.
352 new pollpri `{ return POLLPRI; `} # High-priority data may be read without blocking.
353 new pollout `{ return POLLOUT; `} # Normal data may be written without blocking.
354 new pollwrnorm `{ return POLLWRNORM; `} # Equivalent to POLLOUT
355 new pollwrband `{ return POLLWRBAND; `} # Priority data may be written.
356 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.
357 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.
358 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.
359
360 # Combines two FFSocketPollValues
361 private fun +(other: FFSocketPollValues): FFSocketPollValues `{
362 return recv | other;
363 `}
364 end