OSDN Git Service

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