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