OSDN Git Service

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