lib/binary: intro read/write strings as blocks
[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
33 in "C" `{
34 #include <fcntl.h>
35 #include <netinet/tcp.h>
36 `}
37
38 # Wrapper for the data structure PollFD used for polling on a socket
39 class PollFD
40 super FinalizableOnce
41
42 # The PollFD object
43 private var poll_struct: NativeSocketPollFD
44
45 # A collection of the events to be watched
46 var events: Array[NativeSocketPollValues]
47
48 init(pid: Int, events: Array[NativeSocketPollValues])
49 do
50 assert events.length >= 1
51 self.events = events
52
53 var events_in_one = events[0]
54
55 for i in [1 .. events.length-1] do
56 events_in_one += events[i]
57 end
58
59 self.poll_struct = new NativeSocketPollFD(pid, events_in_one)
60 end
61
62 # Reads the response and returns an array with the type of events that have been found
63 private fun check_response(response: Int): Array[NativeSocketPollValues]
64 do
65 var resp_array = new Array[NativeSocketPollValues]
66 for i in events do
67 if c_check_resp(response, i) != 0 then
68 resp_array.push(i)
69 end
70 end
71 return resp_array
72 end
73
74 # Checks if the poll call has returned true for a particular type of event
75 private fun c_check_resp(response: Int, mask: NativeSocketPollValues): Int
76 `{
77 return response & mask;
78 `}
79
80 redef fun finalize_once
81 do
82 poll_struct.free
83 end
84 end
85
86 # Data structure used by the poll function
87 private extern class NativeSocketPollFD `{ struct pollfd * `}
88
89 # File descriptor
90 fun fd: Int `{ return recv->fd; `}
91
92 # List of events to be watched
93 fun events: Int `{ return recv->events; `}
94
95 # List of events received by the last poll function
96 fun revents: Int `{ return recv->revents; `}
97
98 new (pid: Int, events: NativeSocketPollValues) `{
99 struct pollfd *poll = malloc(sizeof(struct pollfd));
100 poll->fd = pid;
101 poll->events = events;
102 return poll;
103 `}
104 end
105
106 extern class NativeSocket `{ int* `}
107
108 new socket(domain: NativeSocketAddressFamilies, socketType: NativeSocketTypes, protocol: NativeSocketProtocolFamilies) `{
109 int ds = socket(domain, socketType, protocol);
110 if(ds == -1){
111 return NULL;
112 }
113 int *d = malloc(sizeof(int));
114 memcpy(d, &ds, sizeof(ds));
115 return d;
116 `}
117
118 fun destroy `{ free(recv); `}
119
120 fun close: Int `{ return close(*recv); `}
121
122 fun descriptor: Int `{ return *recv; `}
123
124 fun gethostbyname(n: String): NativeSocketHostent import String.to_cstring `{ return gethostbyname(String_to_cstring(n)); `}
125
126 fun connect(addrIn: NativeSocketAddrIn): Int `{
127 return connect(*recv, (struct sockaddr*)addrIn, sizeof(*addrIn));
128 `}
129
130 fun write(buffer: String): Int
131 import String.to_cstring, String.length `{
132 return write(*recv, (char*)String_to_cstring(buffer), String_length(buffer));
133 `}
134
135 # Write `value` as a single byte
136 fun write_byte(value: Int): Int `{
137 unsigned char byt = (unsigned char)value;
138 return write(*recv, &byt, 1);
139 `}
140
141 fun read: String import NativeString.to_s_with_length `{
142 static char c[1024];
143 int n = read(*recv, c, 1024);
144 if(n < 0) {
145 return NativeString_to_s_with_length("",0);
146 }
147 char* ret = malloc(n + 1);
148 memcpy(ret, c, n);
149 ret[n] = '\0';
150 return NativeString_to_s_with_length(ret, n);
151 `}
152
153 # Sets an option for the socket
154 #
155 # Returns `true` on success.
156 fun setsockopt(level: NativeSocketOptLevels, option_name: NativeSocketOptNames, option_value: Int): Bool `{
157 int err = setsockopt(*recv, level, option_name, &option_value, sizeof(int));
158 if(err != 0){
159 return 0;
160 }
161 return 1;
162 `}
163
164 fun bind(addrIn: NativeSocketAddrIn): Int `{ return bind(*recv, (struct sockaddr*)addrIn, sizeof(*addrIn)); `}
165
166 fun listen(size: Int): Int `{ return listen(*recv, size); `}
167
168 # Checks if the buffer is ready for any event specified when creating the pollfd structure
169 fun socket_poll(filedesc: PollFD, timeout: Int): Array[NativeSocketPollValues]
170 do
171 var result = native_poll(filedesc.poll_struct, timeout)
172 assert result != -1
173 return filedesc.check_response(result)
174 end
175
176 # Call to the poll function of the C socket
177 #
178 # Signature:
179 # int poll(struct pollfd fds[], nfds_t nfds, int timeout);
180 #
181 # Official documentation of the poll function:
182 #
183 # The poll() function provides applications with a mechanism for multiplexing input/output over a set of file descriptors.
184 # For each member of the array pointed to by fds, poll() shall examine the given file descriptor for the event(s) specified in events.
185 # The number of pollfd structures in the fds array is specified by nfds.
186 # The poll() function shall identify those file descriptors on which an application can read or write data, or on which certain events have occurred.
187 # The fds argument specifies the file descriptors to be examined and the events of interest for each file descriptor.
188 # It is a pointer to an array with one member for each open file descriptor of interest.
189 # The array's members are pollfd structures within which fd specifies an open file descriptor and events and revents are bitmasks constructed by
190 # OR'ing a combination of the pollfd flags.
191 private fun native_poll(filedesc: NativeSocketPollFD, timeout: Int): Int `{
192 int poll_return = poll(filedesc, 1, timeout);
193 return poll_return;
194 `}
195
196 private fun native_accept(addr_in: NativeSocketAddrIn): NativeSocket `{
197 socklen_t s = sizeof(struct sockaddr);
198 int socket = accept(*recv, (struct sockaddr*)addr_in, &s);
199 if (socket == -1) return NULL;
200
201 int *ptr = malloc(sizeof(int));
202 *ptr = socket;
203 return ptr;
204 `}
205
206 fun accept: nullable SocketAcceptResult
207 do
208 var addrIn = new NativeSocketAddrIn
209 var s = native_accept(addrIn)
210 if s.address_is_null then return null
211 return new SocketAcceptResult(s, addrIn)
212 end
213
214 # Set wether this socket is non blocking
215 fun non_blocking=(value: Bool) `{
216 int flags = fcntl(*recv, F_GETFL, 0);
217 if (flags == -1) flags = 0;
218
219 if (value) {
220 flags = flags | O_NONBLOCK;
221 } else if (flags & O_NONBLOCK) {
222 flags = flags - O_NONBLOCK;
223 } else {
224 return;
225 }
226 fcntl(*recv, F_SETFL, flags);
227 `}
228 end
229
230 # Result of a call to `NativeSocket::accept`
231 class SocketAcceptResult
232
233 # Opened socket
234 var socket: NativeSocket
235
236 # Address of the remote client
237 var addr_in: NativeSocketAddrIn
238 end
239
240 extern class NativeSocketAddrIn `{ struct sockaddr_in* `}
241 new `{
242 struct sockaddr_in *sai = NULL;
243 sai = malloc(sizeof(struct sockaddr_in));
244 return sai;
245 `}
246
247 new with_port(port: Int, family: NativeSocketAddressFamilies) `{
248 struct sockaddr_in *sai = NULL;
249 sai = malloc(sizeof(struct sockaddr_in));
250 sai->sin_family = family;
251 sai->sin_port = htons(port);
252 sai->sin_addr.s_addr = INADDR_ANY;
253 return sai;
254 `}
255
256 new with_hostent(hostent: NativeSocketHostent, port: Int) `{
257 struct sockaddr_in *sai = NULL;
258 sai = malloc(sizeof(struct sockaddr_in));
259 sai->sin_family = hostent->h_addrtype;
260 sai->sin_port = htons(port);
261 memcpy((char*)&sai->sin_addr.s_addr, (char*)hostent->h_addr, hostent->h_length);
262 return sai;
263 `}
264
265 fun address: String import NativeString.to_s `{ return NativeString_to_s((char*)inet_ntoa(recv->sin_addr)); `}
266
267 fun family: NativeSocketAddressFamilies `{ return recv->sin_family; `}
268
269 fun port: Int `{ return ntohs(recv->sin_port); `}
270
271 fun destroy `{ free(recv); `}
272 end
273
274 extern class NativeSocketHostent `{ struct hostent* `}
275 private fun native_h_aliases(i: Int): String import NativeString.to_s `{ return NativeString_to_s(recv->h_aliases[i]); `}
276
277 private fun native_h_aliases_reachable(i: Int): Bool `{ return (recv->h_aliases[i] != NULL); `}
278
279 fun h_aliases: Array[String]
280 do
281 var i=0
282 var d=new Array[String]
283 loop
284 d.add(native_h_aliases(i))
285 if native_h_aliases_reachable(i+1) == false then break
286 i += 1
287 end
288 return d
289 end
290
291 fun h_addr: String import NativeString.to_s `{ return NativeString_to_s((char*)inet_ntoa(*(struct in_addr*)recv->h_addr)); `}
292
293 fun h_addrtype: Int `{ return recv->h_addrtype; `}
294
295 fun h_length: Int `{ return recv->h_length; `}
296
297 fun h_name: String import NativeString.to_s `{ return NativeString_to_s(recv->h_name); `}
298 end
299
300 extern class NativeTimeval `{ struct timeval* `}
301 new (seconds: Int, microseconds: Int) `{
302 struct timeval* tv = NULL;
303 tv = malloc(sizeof(struct timeval));
304 tv->tv_sec = seconds;
305 tv->tv_usec = microseconds;
306 return tv;
307 `}
308
309 fun seconds: Int `{ return recv->tv_sec; `}
310
311 fun microseconds: Int `{ return recv->tv_usec; `}
312
313 fun destroy `{ free(recv); `}
314 end
315
316 extern class NativeSocketSet `{ fd_set* `}
317 new `{
318 fd_set *f = NULL;
319 f = malloc(sizeof(fd_set));
320 return f;
321 `}
322
323 fun set(s: NativeSocket) `{ FD_SET(*s, recv); `}
324
325 fun is_set(s: NativeSocket): Bool `{ return FD_ISSET(*s, recv); `}
326
327 fun zero `{ FD_ZERO(recv); `}
328
329 fun clear(s: NativeSocket) `{ FD_CLR(*s, recv); `}
330
331 fun destroy `{ free(recv); `}
332 end
333
334 class NativeSocketObserver
335 # FIXME this implementation is broken. `reads`, `write` and `except`
336 # are boxed objects, passing them to a C function is illegal.
337 fun select(max: NativeSocket, reads: nullable NativeSocketSet, write: nullable NativeSocketSet,
338 except: nullable NativeSocketSet, timeout: NativeTimeval): Int `{
339 fd_set *rds, *wts, *exs = NULL;
340 struct timeval *tm = NULL;
341 if (reads != NULL) rds = (fd_set*)reads;
342 if (write != NULL) wts = (fd_set*)write;
343 if (except != NULL) exs = (fd_set*)except;
344 if (timeout != NULL) tm = (struct timeval*)timeout;
345 return select(*max, rds, wts, exs, tm);
346 `}
347 end
348
349 extern class NativeSocketTypes `{ int `}
350 new sock_stream `{ return SOCK_STREAM; `}
351 new sock_dgram `{ return SOCK_DGRAM; `}
352 new sock_raw `{ return SOCK_RAW; `}
353 new sock_seqpacket `{ return SOCK_SEQPACKET; `}
354 end
355
356 extern class NativeSocketAddressFamilies `{ int `}
357 new af_null `{ return 0; `}
358
359 # Unspecified
360 new af_unspec `{ return AF_UNSPEC; `}
361
362 # Local to host (pipes)
363 new af_unix `{ return AF_UNIX; `}
364
365 # For backward compatibility
366 new af_local `{ return AF_LOCAL; `}
367
368 # Internetwork: UDP, TCP, etc.
369 new af_inet `{ return AF_INET; `}
370
371 # IBM SNA
372 new af_sna `{ return AF_SNA; `}
373
374 # DECnet
375 new af_decnet `{ return AF_DECnet; `}
376
377 # Internal Routing Protocol
378 new af_route `{ return AF_ROUTE; `}
379
380 # Novell Internet Protocol
381 new af_ipx `{ return AF_IPX; `}
382
383 # IPv6
384 new af_inet6 `{ return AF_INET6; `}
385
386 new af_max `{ return AF_MAX; `}
387 end
388
389 extern class NativeSocketProtocolFamilies `{ int `}
390 new pf_null `{ return 0; `}
391 new pf_unspec `{ return PF_UNSPEC; `}
392 new pf_local `{ return PF_LOCAL; `}
393 new pf_unix `{ return PF_UNIX; `}
394 new pf_inet `{ return PF_INET; `}
395 new pf_sna `{ return PF_SNA; `}
396 new pf_decnet `{ return PF_DECnet; `}
397 new pf_route `{ return PF_ROUTE; `}
398 new pf_ipx `{ return PF_IPX; `}
399 new pf_key `{ return PF_KEY; `}
400 new pf_inet6 `{ return PF_INET6; `}
401 new pf_max `{ return PF_MAX; `}
402 end
403
404 # Level on which to set options
405 extern class NativeSocketOptLevels `{ int `}
406
407 # Dummy for IP (As defined in C)
408 new ip `{ return IPPROTO_IP;`}
409
410 # Control message protocol
411 new icmp `{ return IPPROTO_ICMP;`}
412
413 # Use TCP
414 new tcp `{ return IPPROTO_TCP; `}
415
416 # Socket level options
417 new socket `{ return SOL_SOCKET; `}
418 end
419
420 # Options for socket, use with setsockopt
421 extern class NativeSocketOptNames `{ int `}
422
423 # Enables debugging information
424 new debug `{ return SO_DEBUG; `}
425
426 # Authorizes the broadcasting of messages
427 new broadcast `{ return SO_BROADCAST; `}
428
429 # Authorizes the reuse of the local address
430 new reuseaddr `{ return SO_REUSEADDR; `}
431
432 # Authorizes the use of keep-alive packets in a connection
433 new keepalive `{ return SO_KEEPALIVE; `}
434
435 # Disable the Nagle algorithm and send data as soon as possible, in smaller packets
436 new tcp_nodelay `{ return TCP_NODELAY; `}
437 end
438
439 # Used for the poll function of a socket, mix several Poll values to check for events on more than one type of event
440 extern class NativeSocketPollValues `{ int `}
441
442 # Data other than high-priority data may be read without blocking.
443 new pollin `{ return POLLIN; `}
444
445 # Normal data may be read without blocking.
446 new pollrdnorm `{ return POLLRDNORM; `}
447
448 # Priority data may be read without blocking.
449 new pollrdband `{ return POLLRDBAND; `}
450
451 # High-priority data may be read without blocking.
452 new pollpri `{ return POLLPRI; `}
453
454 # Normal data may be written without blocking.
455 new pollout `{ return POLLOUT; `}
456
457 # Equivalent to POLLOUT
458 new pollwrnorm `{ return POLLWRNORM; `}
459
460 # Priority data may be written.
461 new pollwrband `{ return POLLWRBAND; `}
462
463 # An error has occurred on the device or stream.
464 #
465 # This flag is only valid in the revents bitmask; it shall be ignored in the events member.
466 new pollerr `{ return POLLERR; `}
467
468 # The device has been disconnected.
469 #
470 # This event and POLLOUT are mutually-exclusive; a stream can never be
471 # writable if a hangup has occurred. However, this event and POLLIN,
472 # POLLRDNORM, POLLRDBAND, or POLLPRI are not mutually-exclusive.
473 #
474 # This flag is only valid in the revents bitmask; it shall be ignored in the events member.
475 new pollhup `{ return POLLHUP; `}
476
477 # The specified fd value is invalid.
478 #
479 # This flag is only valid in the revents member; it shall ignored in the events member.
480 new pollnval `{ return POLLNVAL; `}
481
482 # Combines two NativeSocketPollValues
483 private fun +(other: NativeSocketPollValues): NativeSocketPollValues `{
484 return recv | other;
485 `}
486 end