OSDN Git Service

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