Makefile.rtl (GNAT.Sockets.Thin_Common): New unit.
[gcc.git] / gcc / ada / g-socket.ads
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- G N A T . S O C K E T S --
6 -- --
7 -- S p e c --
8 -- --
9 -- Copyright (C) 2001-2008, AdaCore --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 2, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING. If not, write --
19 -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
20 -- Boston, MA 02110-1301, USA. --
21 -- --
22 -- As a special exception, if other files instantiate generics from this --
23 -- unit, or you link this unit with other files to produce an executable, --
24 -- this unit does not by itself cause the resulting executable to be --
25 -- covered by the GNU General Public License. This exception does not --
26 -- however invalidate any other reasons why the executable file might be --
27 -- covered by the GNU Public License. --
28 -- --
29 -- GNAT was originally developed by the GNAT team at New York University. --
30 -- Extensive contributions were provided by Ada Core Technologies Inc. --
31 -- --
32 ------------------------------------------------------------------------------
33
34 -- This package provides an interface to the sockets communication facility
35 -- provided on many operating systems. This is implemented on the following
36 -- platforms:
37
38 -- All native ports, with restrictions as follows
39
40 -- Multicast is available only on systems which provide support for this
41 -- feature, so it is not available if Multicast is not supported, or not
42 -- installed.
43
44 -- The VMS implementation was implemented using the DECC RTL Socket API,
45 -- and is thus subject to limitations in the implementation of this API.
46
47 -- VxWorks cross ports fully implement this package
48
49 -- This package is not yet implemented on LynxOS or other cross ports
50
51 with Ada.Exceptions;
52 with Ada.Streams;
53 with Ada.Unchecked_Deallocation;
54
55 package GNAT.Sockets is
56
57 -- Sockets are designed to provide a consistent communication facility
58 -- between applications. This package provides an Ada binding to the
59 -- the de-facto standard BSD sockets API. The documentation below covers
60 -- only the specific binding provided by this package. It assumes that
61 -- the reader is already familiar with general network programming and
62 -- sockets usage. A useful reference on this matter is W. Richard Stevens'
63 -- "UNIX Network Programming: The Sockets Networking API"
64 -- (ISBN: 0131411551).
65
66 -- GNAT.Sockets has been designed with several ideas in mind
67
68 -- This is a system independent interface. Therefore, we try as much as
69 -- possible to mask system incompatibilities. Some functionalities are not
70 -- available because there are not fully supported on some systems.
71
72 -- This is a thick binding. For instance, a major effort has been done to
73 -- avoid using memory addresses or untyped ints. We preferred to define
74 -- streams and enumeration types. Errors are not returned as returned
75 -- values but as exceptions.
76
77 -- This package provides a POSIX-compliant interface (between two
78 -- different implementations of the same routine, we adopt the one closest
79 -- to the POSIX specification). For instance, using select(), the
80 -- notification of an asynchronous connect failure is delivered in the
81 -- write socket set (POSIX) instead of the exception socket set (NT).
82
83 -- The example below demonstrates various features of GNAT.Sockets:
84
85 -- with GNAT.Sockets; use GNAT.Sockets;
86
87 -- with Ada.Text_IO;
88 -- with Ada.Exceptions; use Ada.Exceptions;
89
90 -- procedure PingPong is
91
92 -- Group : constant String := "239.255.128.128";
93 -- -- Multicast group: administratively scoped IP address
94
95 -- task Pong is
96 -- entry Start;
97 -- entry Stop;
98 -- end Pong;
99
100 -- task body Pong is
101 -- Address : Sock_Addr_Type;
102 -- Server : Socket_Type;
103 -- Socket : Socket_Type;
104 -- Channel : Stream_Access;
105
106 -- begin
107 -- accept Start;
108 --
109 -- -- Get an Internet address of a host (here the local host name).
110 -- -- Note that a host can have several addresses. Here we get
111 -- -- the first one which is supposed to be the official one.
112
113 -- Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1);
114
115 -- -- Get a socket address that is an Internet address and a port
116
117 -- Address.Port := 5876;
118
119 -- -- The first step is to create a socket. Once created, this
120 -- -- socket must be associated to with an address. Usually only a
121 -- -- server (Pong here) needs to bind an address explicitly. Most
122 -- -- of the time clients can skip this step because the socket
123 -- -- routines will bind an arbitrary address to an unbound socket.
124
125 -- Create_Socket (Server);
126
127 -- -- Allow reuse of local addresses
128
129 -- Set_Socket_Option
130 -- (Server,
131 -- Socket_Level,
132 -- (Reuse_Address, True));
133
134 -- Bind_Socket (Server, Address);
135
136 -- -- A server marks a socket as willing to receive connect events
137
138 -- Listen_Socket (Server);
139
140 -- -- Once a server calls Listen_Socket, incoming connects events
141 -- -- can be accepted. The returned Socket is a new socket that
142 -- -- represents the server side of the connection. Server remains
143 -- -- available to receive further connections.
144
145 -- Accept_Socket (Server, Socket, Address);
146
147 -- -- Return a stream associated to the connected socket
148
149 -- Channel := Stream (Socket);
150
151 -- -- Force Pong to block
152
153 -- delay 0.2;
154
155 -- -- Receive and print message from client Ping
156
157 -- declare
158 -- Message : String := String'Input (Channel);
159
160 -- begin
161 -- Ada.Text_IO.Put_Line (Message);
162
163 -- -- Send same message back to client Ping
164
165 -- String'Output (Channel, Message);
166 -- end;
167
168 -- Close_Socket (Server);
169 -- Close_Socket (Socket);
170
171 -- -- Part of the multicast example
172
173 -- -- Create a datagram socket to send connectionless, unreliable
174 -- -- messages of a fixed maximum length.
175
176 -- Create_Socket (Socket, Family_Inet, Socket_Datagram);
177
178 -- -- Allow reuse of local addresses
179
180 -- Set_Socket_Option
181 -- (Socket,
182 -- Socket_Level,
183 -- (Reuse_Address, True));
184
185 -- -- Controls the live time of the datagram to avoid it being
186 -- -- looped forever due to routing errors. Routers decrement
187 -- -- the TTL of every datagram as it traverses from one network
188 -- -- to another and when its value reaches 0 the packet is
189 -- -- dropped. Default is 1.
190
191 -- Set_Socket_Option
192 -- (Socket,
193 -- IP_Protocol_For_IP_Level,
194 -- (Multicast_TTL, 1));
195
196 -- -- Want the data you send to be looped back to your host
197
198 -- Set_Socket_Option
199 -- (Socket,
200 -- IP_Protocol_For_IP_Level,
201 -- (Multicast_Loop, True));
202
203 -- -- If this socket is intended to receive messages, bind it
204 -- -- to a given socket address.
205
206 -- Address.Addr := Any_Inet_Addr;
207 -- Address.Port := 55505;
208
209 -- Bind_Socket (Socket, Address);
210
211 -- -- Join a multicast group
212
213 -- -- Portability note: On Windows, this option may be set only
214 -- -- on a bound socket.
215
216 -- Set_Socket_Option
217 -- (Socket,
218 -- IP_Protocol_For_IP_Level,
219 -- (Add_Membership, Inet_Addr (Group), Any_Inet_Addr));
220
221 -- -- If this socket is intended to send messages, provide the
222 -- -- receiver socket address.
223
224 -- Address.Addr := Inet_Addr (Group);
225 -- Address.Port := 55506;
226
227 -- Channel := Stream (Socket, Address);
228
229 -- -- Receive and print message from client Ping
230
231 -- declare
232 -- Message : String := String'Input (Channel);
233
234 -- begin
235 -- -- Get the address of the sender
236
237 -- Address := Get_Address (Channel);
238 -- Ada.Text_IO.Put_Line (Message & " from " & Image (Address));
239
240 -- -- Send same message back to client Ping
241
242 -- String'Output (Channel, Message);
243 -- end;
244
245 -- Close_Socket (Socket);
246
247 -- accept Stop;
248
249 -- exception when E : others =>
250 -- Ada.Text_IO.Put_Line
251 -- (Exception_Name (E) & ": " & Exception_Message (E));
252 -- end Pong;
253
254 -- task Ping is
255 -- entry Start;
256 -- entry Stop;
257 -- end Ping;
258
259 -- task body Ping is
260 -- Address : Sock_Addr_Type;
261 -- Socket : Socket_Type;
262 -- Channel : Stream_Access;
263
264 -- begin
265 -- accept Start;
266
267 -- -- See comments in Ping section for the first steps
268
269 -- Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1);
270 -- Address.Port := 5876;
271 -- Create_Socket (Socket);
272
273 -- Set_Socket_Option
274 -- (Socket,
275 -- Socket_Level,
276 -- (Reuse_Address, True));
277
278 -- -- Force Pong to block
279
280 -- delay 0.2;
281
282 -- -- If the client's socket is not bound, Connect_Socket will
283 -- -- bind to an unused address. The client uses Connect_Socket to
284 -- -- create a logical connection between the client's socket and
285 -- -- a server's socket returned by Accept_Socket.
286
287 -- Connect_Socket (Socket, Address);
288
289 -- Channel := Stream (Socket);
290
291 -- -- Send message to server Pong
292
293 -- String'Output (Channel, "Hello world");
294
295 -- -- Force Ping to block
296
297 -- delay 0.2;
298
299 -- -- Receive and print message from server Pong
300
301 -- Ada.Text_IO.Put_Line (String'Input (Channel));
302 -- Close_Socket (Socket);
303
304 -- -- Part of multicast example. Code similar to Pong's one
305
306 -- Create_Socket (Socket, Family_Inet, Socket_Datagram);
307
308 -- Set_Socket_Option
309 -- (Socket,
310 -- Socket_Level,
311 -- (Reuse_Address, True));
312
313 -- Set_Socket_Option
314 -- (Socket,
315 -- IP_Protocol_For_IP_Level,
316 -- (Multicast_TTL, 1));
317
318 -- Set_Socket_Option
319 -- (Socket,
320 -- IP_Protocol_For_IP_Level,
321 -- (Multicast_Loop, True));
322
323 -- Address.Addr := Any_Inet_Addr;
324 -- Address.Port := 55506;
325
326 -- Bind_Socket (Socket, Address);
327
328 -- Set_Socket_Option
329 -- (Socket,
330 -- IP_Protocol_For_IP_Level,
331 -- (Add_Membership, Inet_Addr (Group), Any_Inet_Addr));
332
333 -- Address.Addr := Inet_Addr (Group);
334 -- Address.Port := 55505;
335
336 -- Channel := Stream (Socket, Address);
337
338 -- -- Send message to server Pong
339
340 -- String'Output (Channel, "Hello world");
341
342 -- -- Receive and print message from server Pong
343
344 -- declare
345 -- Message : String := String'Input (Channel);
346
347 -- begin
348 -- Address := Get_Address (Channel);
349 -- Ada.Text_IO.Put_Line (Message & " from " & Image (Address));
350 -- end;
351
352 -- Close_Socket (Socket);
353
354 -- accept Stop;
355
356 -- exception when E : others =>
357 -- Ada.Text_IO.Put_Line
358 -- (Exception_Name (E) & ": " & Exception_Message (E));
359 -- end Ping;
360
361 -- begin
362 -- Initialize;
363 -- Ping.Start;
364 -- Pong.Start;
365 -- Ping.Stop;
366 -- Pong.Stop;
367 -- Finalize;
368 -- end PingPong;
369
370 procedure Initialize;
371 -- Initialize must be called before using any other socket routines.
372 -- Note that this operation is a no-op on UNIX platforms, but applications
373 -- should make sure to call it if portability is expected: some platforms
374 -- (such as Windows) require initialization before any socket operation.
375
376 procedure Initialize (Process_Blocking_IO : Boolean);
377 pragma Obsolescent
378 (Entity => Initialize,
379 "passing a parameter to Initialize is not supported anymore");
380 -- Previous versions of GNAT.Sockets used to require the user to indicate
381 -- whether socket I/O was process- or thread-blocking on the platform.
382 -- This property is now determined automatically when the run-time library
383 -- is built. The old version of Initialize, taking a parameter, is kept
384 -- for compatibility reasons, but this interface is obsolete (and if the
385 -- value given is wrong, an exception will be raised at run time).
386
387 procedure Finalize;
388 -- After Finalize is called it is not possible to use any routines
389 -- exported in by this package. This procedure is idempotent.
390
391 type Socket_Type is private;
392 -- Sockets are used to implement a reliable bi-directional point-to-point,
393 -- stream-based connections between hosts. No_Socket provides a special
394 -- value to denote uninitialized sockets.
395
396 No_Socket : constant Socket_Type;
397
398 type Selector_Type is limited private;
399 type Selector_Access is access all Selector_Type;
400 -- Selector objects are used to wait for i/o events to occur on sockets
401
402 -- Timeval_Duration is a subtype of Standard.Duration because the full
403 -- range of Standard.Duration cannot be represented in the equivalent C
404 -- structure. Moreover, negative values are not allowed to avoid system
405 -- incompatibilities.
406
407 Immediate : constant := 0.0;
408 Forever : constant := Duration (Integer'Last) * 1.0;
409 -- Should be Duration 2 ** (Constants.SIZEOF_tv_sec * 8 - 1) - 1 ???
410
411 subtype Timeval_Duration is Duration range Immediate .. Forever;
412
413 subtype Selector_Duration is Timeval_Duration;
414 -- Timeout value for selector operations
415
416 type Selector_Status is (Completed, Expired, Aborted);
417 -- Completion status of a selector operation, indicated as follows:
418 -- Complete: one of the expected events occurred
419 -- Expired: no event occurred before the expiration of the timeout
420 -- Aborted: an external action cancelled the wait operation before
421 -- any event occurred.
422
423 Socket_Error : exception;
424 -- There is only one exception in this package to deal with an error during
425 -- a socket routine. Once raised, its message contains a string describing
426 -- the error code.
427
428 function Image (Socket : Socket_Type) return String;
429 -- Return a printable string for Socket
430
431 function To_C (Socket : Socket_Type) return Integer;
432 -- Return a file descriptor to be used by external subprograms. This is
433 -- useful for C functions that are not yet interfaced in this package.
434
435 type Family_Type is (Family_Inet, Family_Inet6);
436 -- Address family (or protocol family) identifies the communication domain
437 -- and groups protocols with similar address formats. IPv6 will soon be
438 -- supported.
439
440 type Mode_Type is (Socket_Stream, Socket_Datagram);
441 -- Stream sockets provide connection-oriented byte streams. Datagram
442 -- sockets support unreliable connectionless message based communication.
443
444 type Shutmode_Type is (Shut_Read, Shut_Write, Shut_Read_Write);
445 -- When a process closes a socket, the policy is to retain any data queued
446 -- until either a delivery or a timeout expiration (in this case, the data
447 -- are discarded). A finer control is available through shutdown. With
448 -- Shut_Read, no more data can be received from the socket. With_Write, no
449 -- more data can be transmitted. Neither transmission nor reception can be
450 -- performed with Shut_Read_Write.
451
452 type Port_Type is new Natural;
453 -- Classical port definition. No_Port provides a special value to
454 -- denote uninitialized port. Any_Port provides a special value
455 -- enabling all ports.
456
457 Any_Port : constant Port_Type;
458 No_Port : constant Port_Type;
459
460 type Inet_Addr_Type (Family : Family_Type := Family_Inet) is private;
461 -- An Internet address depends on an address family (IPv4 contains 4 octets
462 -- and IPv6 contains 16 octets). Any_Inet_Addr is a special value treated
463 -- like a wildcard enabling all addresses. No_Inet_Addr provides a special
464 -- value to denote uninitialized inet addresses.
465
466 Any_Inet_Addr : constant Inet_Addr_Type;
467 No_Inet_Addr : constant Inet_Addr_Type;
468 Broadcast_Inet_Addr : constant Inet_Addr_Type;
469
470 type Sock_Addr_Type (Family : Family_Type := Family_Inet) is record
471 Addr : Inet_Addr_Type (Family);
472 Port : Port_Type;
473 end record;
474 -- Socket addresses fully define a socket connection with protocol family,
475 -- an Internet address and a port. No_Sock_Addr provides a special value
476 -- for uninitialized socket addresses.
477
478 No_Sock_Addr : constant Sock_Addr_Type;
479
480 function Image (Value : Inet_Addr_Type) return String;
481 -- Return an image of an Internet address. IPv4 notation consists in 4
482 -- octets in decimal format separated by dots. IPv6 notation consists in
483 -- 16 octets in hexadecimal format separated by colons (and possibly
484 -- dots).
485
486 function Image (Value : Sock_Addr_Type) return String;
487 -- Return inet address image and port image separated by a colon
488
489 function Inet_Addr (Image : String) return Inet_Addr_Type;
490 -- Convert address image from numbers-and-dots notation into an
491 -- inet address.
492
493 -- Host entries provide complete information on a given host: the official
494 -- name, an array of alternative names or aliases and array of network
495 -- addresses.
496
497 type Host_Entry_Type
498 (Aliases_Length, Addresses_Length : Natural) is private;
499
500 function Official_Name (E : Host_Entry_Type) return String;
501 -- Return official name in host entry
502
503 function Aliases_Length (E : Host_Entry_Type) return Natural;
504 -- Return number of aliases in host entry
505
506 function Addresses_Length (E : Host_Entry_Type) return Natural;
507 -- Return number of addresses in host entry
508
509 function Aliases
510 (E : Host_Entry_Type;
511 N : Positive := 1) return String;
512 -- Return N'th aliases in host entry. The first index is 1
513
514 function Addresses
515 (E : Host_Entry_Type;
516 N : Positive := 1) return Inet_Addr_Type;
517 -- Return N'th addresses in host entry. The first index is 1
518
519 Host_Error : exception;
520 -- Exception raised by the two following procedures. Once raised, its
521 -- message contains a string describing the error code. This exception is
522 -- raised when an host entry cannot be retrieved.
523
524 function Get_Host_By_Address
525 (Address : Inet_Addr_Type;
526 Family : Family_Type := Family_Inet) return Host_Entry_Type;
527 -- Return host entry structure for the given Inet address. Note that no
528 -- result will be returned if there is no mapping of this IP address to a
529 -- host name in the system tables (host database, DNS or otherwise).
530
531 function Get_Host_By_Name
532 (Name : String) return Host_Entry_Type;
533 -- Return host entry structure for the given host name. Here name is
534 -- either a host name, or an IP address. If Name is an IP address, this
535 -- is equivalent to Get_Host_By_Address (Inet_Addr (Name)).
536
537 function Host_Name return String;
538 -- Return the name of the current host
539
540 type Service_Entry_Type (Aliases_Length : Natural) is private;
541 -- Service entries provide complete information on a given service: the
542 -- official name, an array of alternative names or aliases and the port
543 -- number.
544
545 function Official_Name (S : Service_Entry_Type) return String;
546 -- Return official name in service entry
547
548 function Port_Number (S : Service_Entry_Type) return Port_Type;
549 -- Return port number in service entry
550
551 function Protocol_Name (S : Service_Entry_Type) return String;
552 -- Return Protocol in service entry (usually UDP or TCP)
553
554 function Aliases_Length (S : Service_Entry_Type) return Natural;
555 -- Return number of aliases in service entry
556
557 function Aliases
558 (S : Service_Entry_Type;
559 N : Positive := 1) return String;
560 -- Return N'th aliases in service entry (the first index is 1)
561
562 function Get_Service_By_Name
563 (Name : String;
564 Protocol : String) return Service_Entry_Type;
565 -- Return service entry structure for the given service name
566
567 function Get_Service_By_Port
568 (Port : Port_Type;
569 Protocol : String) return Service_Entry_Type;
570 -- Return service entry structure for the given service port number
571
572 Service_Error : exception;
573 -- Comment required ???
574
575 -- Errors are described by an enumeration type. There is only one exception
576 -- Socket_Error in this package to deal with an error during a socket
577 -- routine. Once raised, its message contains the error code between
578 -- brackets and a string describing the error code.
579
580 -- The name of the enumeration constant documents the error condition
581
582 type Error_Type is
583 (Success,
584 Permission_Denied,
585 Address_Already_In_Use,
586 Cannot_Assign_Requested_Address,
587 Address_Family_Not_Supported_By_Protocol,
588 Operation_Already_In_Progress,
589 Bad_File_Descriptor,
590 Software_Caused_Connection_Abort,
591 Connection_Refused,
592 Connection_Reset_By_Peer,
593 Destination_Address_Required,
594 Bad_Address,
595 Host_Is_Down,
596 No_Route_To_Host,
597 Operation_Now_In_Progress,
598 Interrupted_System_Call,
599 Invalid_Argument,
600 Input_Output_Error,
601 Transport_Endpoint_Already_Connected,
602 Too_Many_Symbolic_Links,
603 Too_Many_Open_Files,
604 Message_Too_Long,
605 File_Name_Too_Long,
606 Network_Is_Down,
607 Network_Dropped_Connection_Because_Of_Reset,
608 Network_Is_Unreachable,
609 No_Buffer_Space_Available,
610 Protocol_Not_Available,
611 Transport_Endpoint_Not_Connected,
612 Socket_Operation_On_Non_Socket,
613 Operation_Not_Supported,
614 Protocol_Family_Not_Supported,
615 Protocol_Not_Supported,
616 Protocol_Wrong_Type_For_Socket,
617 Cannot_Send_After_Transport_Endpoint_Shutdown,
618 Socket_Type_Not_Supported,
619 Connection_Timed_Out,
620 Too_Many_References,
621 Resource_Temporarily_Unavailable,
622 Unknown_Host,
623 Host_Name_Lookup_Failure,
624 Non_Recoverable_Error,
625 Unknown_Server_Error,
626 Cannot_Resolve_Error);
627
628 -- Get_Socket_Options and Set_Socket_Options manipulate options associated
629 -- with a socket. Options may exist at multiple protocol levels in the
630 -- communication stack. Socket_Level is the uppermost socket level.
631
632 type Level_Type is (
633 Socket_Level,
634 IP_Protocol_For_IP_Level,
635 IP_Protocol_For_UDP_Level,
636 IP_Protocol_For_TCP_Level);
637
638 -- There are several options available to manipulate sockets. Each option
639 -- has a name and several values available. Most of the time, the value is
640 -- a boolean to enable or disable this option.
641
642 type Option_Name is (
643 Keep_Alive, -- Enable sending of keep-alive messages
644 Reuse_Address, -- Allow bind to reuse local address
645 Broadcast, -- Enable datagram sockets to recv/send broadcasts
646 Send_Buffer, -- Set/get the maximum socket send buffer in bytes
647 Receive_Buffer, -- Set/get the maximum socket recv buffer in bytes
648 Linger, -- Shutdown wait for msg to be sent or timeout occur
649 Error, -- Get and clear the pending socket error
650 No_Delay, -- Do not delay send to coalesce data (TCP_NODELAY)
651 Add_Membership, -- Join a multicast group
652 Drop_Membership, -- Leave a multicast group
653 Multicast_If, -- Set default out interface for multicast packets
654 Multicast_TTL, -- Set the time-to-live of sent multicast packets
655 Multicast_Loop, -- Sent multicast packets are looped to local socket
656 Receive_Packet_Info, -- Receive low level packet info as ancillary data
657 Send_Timeout, -- Set timeout value for output
658 Receive_Timeout); -- Set timeout value for input
659
660 type Option_Type (Name : Option_Name := Keep_Alive) is record
661 case Name is
662 when Keep_Alive |
663 Reuse_Address |
664 Broadcast |
665 Linger |
666 No_Delay |
667 Receive_Packet_Info |
668 Multicast_Loop =>
669 Enabled : Boolean;
670
671 case Name is
672 when Linger =>
673 Seconds : Natural;
674 when others =>
675 null;
676 end case;
677
678 when Send_Buffer |
679 Receive_Buffer =>
680 Size : Natural;
681
682 when Error =>
683 Error : Error_Type;
684
685 when Add_Membership |
686 Drop_Membership =>
687 Multicast_Address : Inet_Addr_Type;
688 Local_Interface : Inet_Addr_Type;
689
690 when Multicast_If =>
691 Outgoing_If : Inet_Addr_Type;
692
693 when Multicast_TTL =>
694 Time_To_Live : Natural;
695
696 when Send_Timeout |
697 Receive_Timeout =>
698 Timeout : Timeval_Duration;
699
700 end case;
701 end record;
702
703 -- There are several controls available to manipulate sockets. Each option
704 -- has a name and several values available. These controls differ from the
705 -- socket options in that they are not specific to sockets but are
706 -- available for any device.
707
708 type Request_Name is (
709 Non_Blocking_IO, -- Cause a caller not to wait on blocking operations.
710 N_Bytes_To_Read); -- Return the number of bytes available to read
711
712 type Request_Type (Name : Request_Name := Non_Blocking_IO) is record
713 case Name is
714 when Non_Blocking_IO =>
715 Enabled : Boolean;
716
717 when N_Bytes_To_Read =>
718 Size : Natural;
719
720 end case;
721 end record;
722
723 -- A request flag allows to specify the type of message transmissions or
724 -- receptions. A request flag can be combination of zero or more
725 -- predefined request flags.
726
727 type Request_Flag_Type is private;
728
729 No_Request_Flag : constant Request_Flag_Type;
730 -- This flag corresponds to the normal execution of an operation
731
732 Process_Out_Of_Band_Data : constant Request_Flag_Type;
733 -- This flag requests that the receive or send function operates on
734 -- out-of-band data when the socket supports this notion (e.g.
735 -- Socket_Stream).
736
737 Peek_At_Incoming_Data : constant Request_Flag_Type;
738 -- This flag causes the receive operation to return data from the beginning
739 -- of the receive queue without removing that data from the queue. A
740 -- subsequent receive call will return the same data.
741
742 Wait_For_A_Full_Reception : constant Request_Flag_Type;
743 -- This flag requests that the operation block until the full request is
744 -- satisfied. However, the call may still return less data than requested
745 -- if a signal is caught, an error or disconnect occurs, or the next data
746 -- to be received is of a different type than that returned. Note that
747 -- this flag depends on support in the underlying sockets implementation,
748 -- and is not supported under Windows.
749
750 Send_End_Of_Record : constant Request_Flag_Type;
751 -- This flag indicates that the entire message has been sent and so this
752 -- terminates the record.
753
754 function "+" (L, R : Request_Flag_Type) return Request_Flag_Type;
755 -- Combine flag L with flag R
756
757 type Stream_Element_Reference is access all Ada.Streams.Stream_Element;
758
759 type Vector_Element is record
760 Base : Stream_Element_Reference;
761 Length : Ada.Streams.Stream_Element_Count;
762 end record;
763
764 type Vector_Type is array (Integer range <>) of Vector_Element;
765
766 procedure Create_Socket
767 (Socket : out Socket_Type;
768 Family : Family_Type := Family_Inet;
769 Mode : Mode_Type := Socket_Stream);
770 -- Create an endpoint for communication. Raises Socket_Error on error
771
772 procedure Accept_Socket
773 (Server : Socket_Type;
774 Socket : out Socket_Type;
775 Address : out Sock_Addr_Type);
776 -- Extracts the first connection request on the queue of pending
777 -- connections, creates a new connected socket with mostly the same
778 -- properties as Server, and allocates a new socket. The returned Address
779 -- is filled in with the address of the connection. Raises Socket_Error on
780 -- error.
781
782 procedure Accept_Socket
783 (Server : Socket_Type;
784 Socket : out Socket_Type;
785 Address : out Sock_Addr_Type;
786 Timeout : Selector_Duration;
787 Selector : access Selector_Type := null;
788 Status : out Selector_Status);
789 -- Accept a new connection on Server using Accept_Socket, waiting no longer
790 -- than the given timeout duration. Status is set to indicate whether the
791 -- operation completed successully, timed out, or was aborted. If Selector
792 -- is not null, the designated selector is used to wait for the socket to
793 -- become available, else a private selector object is created by this
794 -- procedure and destroyed before it returns.
795
796 procedure Bind_Socket
797 (Socket : Socket_Type;
798 Address : Sock_Addr_Type);
799 -- Once a socket is created, assign a local address to it. Raise
800 -- Socket_Error on error.
801
802 procedure Close_Socket (Socket : Socket_Type);
803 -- Close a socket and more specifically a non-connected socket
804
805 procedure Connect_Socket
806 (Socket : Socket_Type;
807 Server : Sock_Addr_Type);
808 -- Make a connection to another socket which has the address of Server.
809 -- Raises Socket_Error on error.
810
811 procedure Connect_Socket
812 (Socket : Socket_Type;
813 Server : Sock_Addr_Type;
814 Timeout : Selector_Duration;
815 Selector : access Selector_Type := null;
816 Status : out Selector_Status);
817 -- Connect Socket to the given Server address using Connect_Socket, waiting
818 -- no longer than the given timeout duration. Status is set to indicate
819 -- whether the operation completed successully, timed out, or was aborted.
820 -- If Selector is not null, the designated selector is used to wait for the
821 -- socket to become available, else a private selector object is created
822 -- by this procedure and destroyed before it returns.
823
824 procedure Control_Socket
825 (Socket : Socket_Type;
826 Request : in out Request_Type);
827 -- Obtain or set parameter values that control the socket. This control
828 -- differs from the socket options in that they are not specific to sockets
829 -- but are available for any device.
830
831 function Get_Peer_Name (Socket : Socket_Type) return Sock_Addr_Type;
832 -- Return the peer or remote socket address of a socket. Raise
833 -- Socket_Error on error.
834
835 function Get_Socket_Name (Socket : Socket_Type) return Sock_Addr_Type;
836 -- Return the local or current socket address of a socket. Return
837 -- No_Sock_Addr on error (e.g. socket closed or not locally bound).
838
839 function Get_Socket_Option
840 (Socket : Socket_Type;
841 Level : Level_Type := Socket_Level;
842 Name : Option_Name) return Option_Type;
843 -- Get the options associated with a socket. Raises Socket_Error on error
844
845 procedure Listen_Socket
846 (Socket : Socket_Type;
847 Length : Natural := 15);
848 -- To accept connections, a socket is first created with Create_Socket,
849 -- a willingness to accept incoming connections and a queue Length for
850 -- incoming connections are specified. Raise Socket_Error on error.
851 -- The queue length of 15 is an example value that should be appropriate
852 -- in usual cases. It can be adjusted according to each application's
853 -- particular requirements.
854
855 procedure Receive_Socket
856 (Socket : Socket_Type;
857 Item : out Ada.Streams.Stream_Element_Array;
858 Last : out Ada.Streams.Stream_Element_Offset;
859 Flags : Request_Flag_Type := No_Request_Flag);
860 -- Receive message from Socket. Last is the index value such that Item
861 -- (Last) is the last character assigned. Note that Last is set to
862 -- Item'First - 1 when the socket has been closed by peer. This is not an
863 -- error and no exception is raised. Flags allows to control the
864 -- reception. Raise Socket_Error on error.
865
866 procedure Receive_Socket
867 (Socket : Socket_Type;
868 Item : out Ada.Streams.Stream_Element_Array;
869 Last : out Ada.Streams.Stream_Element_Offset;
870 From : out Sock_Addr_Type;
871 Flags : Request_Flag_Type := No_Request_Flag);
872 -- Receive message from Socket. If Socket is not connection-oriented, the
873 -- source address From of the message is filled in. Last is the index
874 -- value such that Item (Last) is the last character assigned. Flags
875 -- allows to control the reception. Raises Socket_Error on error.
876
877 procedure Receive_Vector
878 (Socket : Socket_Type;
879 Vector : Vector_Type;
880 Count : out Ada.Streams.Stream_Element_Count);
881 -- Receive data from a socket and scatter it into the set of vector
882 -- elements Vector. Count is set to the count of received stream elements.
883
884 function Resolve_Exception
885 (Occurrence : Ada.Exceptions.Exception_Occurrence) return Error_Type;
886 -- When Socket_Error or Host_Error are raised, the exception message
887 -- contains the error code between brackets and a string describing the
888 -- error code. Resolve_Error extracts the error code from an exception
889 -- message and translate it into an enumeration value.
890
891 procedure Send_Socket
892 (Socket : Socket_Type;
893 Item : Ada.Streams.Stream_Element_Array;
894 Last : out Ada.Streams.Stream_Element_Offset;
895 Flags : Request_Flag_Type := No_Request_Flag);
896 -- Transmit a message to another socket. Note that Last is set to
897 -- Item'First-1 when socket has been closed by peer. This is not
898 -- considered an error and no exception is raised. Flags allows to control
899 -- the transmission. Raises Socket_Error on any other error condition.
900
901 procedure Send_Socket
902 (Socket : Socket_Type;
903 Item : Ada.Streams.Stream_Element_Array;
904 Last : out Ada.Streams.Stream_Element_Offset;
905 To : Sock_Addr_Type;
906 Flags : Request_Flag_Type := No_Request_Flag);
907 -- Transmit a message to another socket. The address is given by To. Flags
908 -- allows to control the transmission. Raises Socket_Error on error.
909
910 procedure Send_Vector
911 (Socket : Socket_Type;
912 Vector : Vector_Type;
913 Count : out Ada.Streams.Stream_Element_Count);
914 -- Transmit data gathered from the set of vector elements Vector to a
915 -- socket. Count is set to the count of transmitted stream elements.
916
917 procedure Set_Socket_Option
918 (Socket : Socket_Type;
919 Level : Level_Type := Socket_Level;
920 Option : Option_Type);
921 -- Manipulate socket options. Raises Socket_Error on error
922
923 procedure Shutdown_Socket
924 (Socket : Socket_Type;
925 How : Shutmode_Type := Shut_Read_Write);
926 -- Shutdown a connected socket. If How is Shut_Read, further receives will
927 -- be disallowed. If How is Shut_Write, further sends will be disallowed.
928 -- If how is Shut_Read_Write, further sends and receives will be
929 -- disallowed.
930
931 type Stream_Access is access all Ada.Streams.Root_Stream_Type'Class;
932 -- Same interface as Ada.Streams.Stream_IO
933
934 function Stream (Socket : Socket_Type) return Stream_Access;
935 -- Create a stream associated with a stream-based socket that is
936 -- already connected.
937
938 function Stream
939 (Socket : Socket_Type;
940 Send_To : Sock_Addr_Type) return Stream_Access;
941 -- Create a stream associated with a datagram-based socket that is already
942 -- bound. Send_To is the socket address to which messages are being sent.
943
944 function Get_Address
945 (Stream : not null Stream_Access) return Sock_Addr_Type;
946 -- Return the socket address from which the last message was received
947
948 procedure Free is new Ada.Unchecked_Deallocation
949 (Ada.Streams.Root_Stream_Type'Class, Stream_Access);
950 -- Destroy a stream created by one of the Stream functions above,
951 -- releasing the corresponding resources. The user is responsible for
952 -- calling this subprogram when the stream is not needed anymore.
953
954 type Socket_Set_Type is limited private;
955 -- This type allows to manipulate sets of sockets. It allows to wait for
956 -- events on multiple endpoints at one time. This is an access type on a
957 -- system dependent structure. To avoid memory leaks it is highly
958 -- recommended to clean the access value with procedure Empty.
959
960 procedure Clear (Item : in out Socket_Set_Type; Socket : Socket_Type);
961 -- Remove Socket from Item
962
963 procedure Copy (Source : Socket_Set_Type; Target : in out Socket_Set_Type);
964 -- Copy Source into Target as Socket_Set_Type is limited private
965
966 procedure Empty (Item : in out Socket_Set_Type);
967 -- Remove all Sockets from Item and deallocate internal data
968
969 procedure Get (Item : in out Socket_Set_Type; Socket : out Socket_Type);
970 -- Extract a Socket from socket set Item. Socket is set to
971 -- No_Socket when the set is empty.
972
973 function Is_Empty (Item : Socket_Set_Type) return Boolean;
974 -- Return True iff Item is empty
975
976 function Is_Set
977 (Item : Socket_Set_Type;
978 Socket : Socket_Type) return Boolean;
979 -- Return True iff Socket is present in Item
980
981 procedure Set (Item : in out Socket_Set_Type; Socket : Socket_Type);
982 -- Insert Socket into Item
983
984 -- The select(2) system call waits for events to occur on any of a set of
985 -- file descriptors. Usually, three independent sets of descriptors are
986 -- watched (read, write and exception). A timeout gives an upper bound
987 -- on the amount of time elapsed before select returns. This function
988 -- blocks until an event occurs. On some platforms, the select(2) system
989 -- can block the full process (not just the calling thread).
990 --
991 -- Check_Selector provides the very same behaviour. The only difference is
992 -- that it does not watch for exception events. Note that on some
993 -- platforms it is kept process blocking on purpose. The timeout parameter
994 -- allows the user to have the behaviour he wants. Abort_Selector allows
995 -- to abort safely a Check_Selector that is blocked forever. A special
996 -- file descriptor is opened by Create_Selector and included in each call
997 -- to Check_Selector. Abort_Selector causes an event to occur on this
998 -- descriptor in order to unblock Check_Selector. The user must call
999 -- Close_Selector to discard this special file. A reason to abort a select
1000 -- operation is typically to add a socket in one of the socket sets when
1001 -- the timeout is set to forever.
1002
1003 procedure Create_Selector (Selector : out Selector_Type);
1004 -- Create a new selector
1005
1006 procedure Close_Selector (Selector : in out Selector_Type);
1007 -- Close Selector and all internal descriptors associated; deallocate any
1008 -- associated resources. This subprogram may be called only when there is
1009 -- no other task still using Selector (i.e. still executing Check_Selector
1010 -- or Abort_Selector on this Selector).
1011
1012 procedure Check_Selector
1013 (Selector : in out Selector_Type;
1014 R_Socket_Set : in out Socket_Set_Type;
1015 W_Socket_Set : in out Socket_Set_Type;
1016 Status : out Selector_Status;
1017 Timeout : Selector_Duration := Forever);
1018 -- Return when one Socket in R_Socket_Set has some data to be read or if
1019 -- one Socket in W_Socket_Set is ready to transmit some data. In these
1020 -- cases Status is set to Completed and sockets that are ready are set in
1021 -- R_Socket_Set or W_Socket_Set. Status is set to Expired if no socket was
1022 -- ready after a Timeout expiration. Status is set to Aborted if an abort
1023 -- signal has been received while checking socket status.
1024 -- Note that two different Socket_Set_Type objects must be passed as
1025 -- R_Socket_Set and W_Socket_Set (even if they denote the same set of
1026 -- Sockets), or some event may be lost.
1027 -- Socket_Error is raised when the select(2) system call returns an
1028 -- error condition, or when a read error occurs on the signalling socket
1029 -- used for the implementation of Abort_Selector.
1030
1031 procedure Check_Selector
1032 (Selector : in out Selector_Type;
1033 R_Socket_Set : in out Socket_Set_Type;
1034 W_Socket_Set : in out Socket_Set_Type;
1035 E_Socket_Set : in out Socket_Set_Type;
1036 Status : out Selector_Status;
1037 Timeout : Selector_Duration := Forever);
1038 -- This refined version of Check_Selector allows to watch for exception
1039 -- events (that is notifications of out-of-band transmission and
1040 -- reception). As above, all of R_Socket_Set, W_Socket_Set and
1041 -- E_Socket_Set must be different objects.
1042
1043 procedure Abort_Selector (Selector : Selector_Type);
1044 -- Send an abort signal to the selector
1045
1046 type Fd_Set_Access is private;
1047 No_Fd_Set_Access : constant Fd_Set_Access;
1048 -- ??? This type must not be used directly, it needs to be visible because
1049 -- it is used in the visible part of GNAT.Sockets.Thin_Common. This is
1050 -- really an inversion of abstraction. The private part of GNAT.Sockets
1051 -- needs to have visibility on this type, but since Thin_Common is a child
1052 -- of Sokcets, the type can't be declared there. The correct fix would
1053 -- be to move the thin sockets binding outside of GNAT.Sockets altogether,
1054 -- e.g. by renaming it to GNAT.Sockets_Thin.
1055
1056 private
1057
1058 type Socket_Type is new Integer;
1059 No_Socket : constant Socket_Type := -1;
1060
1061 type Selector_Type is limited record
1062 R_Sig_Socket : Socket_Type := No_Socket;
1063 W_Sig_Socket : Socket_Type := No_Socket;
1064 -- Signalling sockets used to abort a select operation
1065 end record;
1066
1067 pragma Volatile (Selector_Type);
1068
1069 type Fd_Set is null record;
1070 type Fd_Set_Access is access all Fd_Set;
1071 pragma Convention (C, Fd_Set_Access);
1072 No_Fd_Set_Access : constant Fd_Set_Access := null;
1073
1074 type Socket_Set_Type is record
1075 Last : Socket_Type := No_Socket;
1076 Set : Fd_Set_Access;
1077 end record;
1078
1079 subtype Inet_Addr_Comp_Type is Natural range 0 .. 255;
1080 -- Octet for Internet address
1081
1082 type Inet_Addr_VN_Type is array (Natural range <>) of Inet_Addr_Comp_Type;
1083
1084 subtype Inet_Addr_V4_Type is Inet_Addr_VN_Type (1 .. 4);
1085 subtype Inet_Addr_V6_Type is Inet_Addr_VN_Type (1 .. 16);
1086
1087 type Inet_Addr_Type (Family : Family_Type := Family_Inet) is record
1088 case Family is
1089 when Family_Inet =>
1090 Sin_V4 : Inet_Addr_V4_Type := (others => 0);
1091
1092 when Family_Inet6 =>
1093 Sin_V6 : Inet_Addr_V6_Type := (others => 0);
1094 end case;
1095 end record;
1096
1097 Any_Port : constant Port_Type := 0;
1098 No_Port : constant Port_Type := 0;
1099
1100 Any_Inet_Addr : constant Inet_Addr_Type :=
1101 (Family_Inet, (others => 0));
1102 No_Inet_Addr : constant Inet_Addr_Type :=
1103 (Family_Inet, (others => 0));
1104 Broadcast_Inet_Addr : constant Inet_Addr_Type :=
1105 (Family_Inet, (others => 255));
1106
1107 No_Sock_Addr : constant Sock_Addr_Type := (Family_Inet, No_Inet_Addr, 0);
1108
1109 Max_Name_Length : constant := 64;
1110 -- The constant MAXHOSTNAMELEN is usually set to 64
1111
1112 subtype Name_Index is Natural range 1 .. Max_Name_Length;
1113
1114 type Name_Type
1115 (Length : Name_Index := Max_Name_Length)
1116 is record
1117 Name : String (1 .. Length);
1118 end record;
1119 -- We need fixed strings to avoid access types in host entry type
1120
1121 type Name_Array is array (Natural range <>) of Name_Type;
1122 type Inet_Addr_Array is array (Natural range <>) of Inet_Addr_Type;
1123
1124 type Host_Entry_Type (Aliases_Length, Addresses_Length : Natural) is record
1125 Official : Name_Type;
1126 Aliases : Name_Array (1 .. Aliases_Length);
1127 Addresses : Inet_Addr_Array (1 .. Addresses_Length);
1128 end record;
1129
1130 type Service_Entry_Type (Aliases_Length : Natural) is record
1131 Official : Name_Type;
1132 Aliases : Name_Array (1 .. Aliases_Length);
1133 Port : Port_Type;
1134 Protocol : Name_Type;
1135 end record;
1136
1137 type Request_Flag_Type is mod 2 ** 8;
1138 No_Request_Flag : constant Request_Flag_Type := 0;
1139 Process_Out_Of_Band_Data : constant Request_Flag_Type := 1;
1140 Peek_At_Incoming_Data : constant Request_Flag_Type := 2;
1141 Wait_For_A_Full_Reception : constant Request_Flag_Type := 4;
1142 Send_End_Of_Record : constant Request_Flag_Type := 8;
1143
1144 end GNAT.Sockets;