g-socket.ads 41.1 KB
Newer Older
Richard Kenner committed
1 2 3 4 5 6 7 8
------------------------------------------------------------------------------
--                                                                          --
--                         GNAT COMPILER COMPONENTS                         --
--                                                                          --
--                         G N A T . S O C K E T S                          --
--                                                                          --
--                                 S p e c                                  --
--                                                                          --
9
--              Copyright (C) 2001-2003 Ada Core Technologies, Inc.         --
Richard Kenner committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
--                                                                          --
-- GNAT is free software;  you can  redistribute it  and/or modify it under --
-- terms of the  GNU General Public License as published  by the Free Soft- --
-- ware  Foundation;  either version 2,  or (at your option) any later ver- --
-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
-- for  more details.  You should have  received  a copy of the GNU General --
-- Public License  distributed with GNAT;  see file COPYING.  If not, write --
-- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
-- MA 02111-1307, USA.                                                      --
--                                                                          --
-- As a special exception,  if other files  instantiate  generics from this --
-- unit, or you link  this unit with other files  to produce an executable, --
-- this  unit  does not  by itself cause  the resulting  executable  to  be --
-- covered  by the  GNU  General  Public  License.  This exception does not --
-- however invalidate  any other reasons why  the executable file  might be --
-- covered by the  GNU Public License.                                      --
--                                                                          --
29 30
-- GNAT was originally developed  by the GNAT team at  New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc.      --
Richard Kenner committed
31 32 33
--                                                                          --
------------------------------------------------------------------------------

34 35 36
--  This package provides an interface to the sockets communication
--  facility provided on many operating systems. This is implemented
--  on the following platforms:
37

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
--     All native ports, except Interix, with restrictions as follows

--       Multicast is available only on systems which provide support
--       for this feature, so it is not available if Multicast is not
--       supported, or not installed. In particular Multicast is not
--       available with the Windows version.

--       The VMS implementation has implemented using the DECC RTL Socket
--       API, and is thus subject to limitations in the implementation of
--       this API.

--       This package is not supported on the Interix port of GNAT.

--     VxWorks cross ports fully implement this package.

--     This package is not yet implemented on LynxOS.
Richard Kenner committed
54 55 56

with Ada.Exceptions;
with Ada.Streams;
Arnaud Charlet committed
57
with Ada.Unchecked_Deallocation;
Richard Kenner committed
58

59 60
with System;

Richard Kenner committed
61 62
package GNAT.Sockets is

63
   --  Sockets are designed to provide a consistent communication facility
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
   --  between applications. This package provides an Ada-like interface
   --  similar to that proposed as part of the BSD socket layer.

   --  GNAT.Sockets has been designed with several ideas in mind.

   --  This is a system independent interface. Therefore, we try as
   --  much as possible to mask system incompatibilities. Some
   --  functionalities are not available because there are not fully
   --  supported on some systems.

   --  This is a thick binding. For instance, a major effort has been
   --  done to avoid using memory addresses or untyped ints. We
   --  preferred to define streams and enumeration types. Errors are
   --  not returned as returned values but as exceptions.

   --  This package provides a POSIX-compliant interface (between two
   --  different implementations of the same routine, we adopt the one
   --  closest to the POSIX specification). For instance, using
   --  select(), the notification of an asynchronous connect failure
   --  is delivered in the write socket set (POSIX) instead of the
   --  exception socket set (NT).
85 86

   --  Here is a typical example of what you can do:
Richard Kenner committed
87 88

   --  with GNAT.Sockets; use GNAT.Sockets;
89

Richard Kenner committed
90 91
   --  with Ada.Text_IO;
   --  with Ada.Exceptions; use Ada.Exceptions;
92

Richard Kenner committed
93
   --  procedure PingPong is
94

Richard Kenner committed
95
   --     Group : constant String := "239.255.128.128";
96 97
   --     --  Multicast group: administratively scoped IP address

Richard Kenner committed
98 99 100 101
   --     task Pong is
   --        entry Start;
   --        entry Stop;
   --     end Pong;
102

Richard Kenner committed
103 104 105 106 107
   --     task body Pong is
   --        Address  : Sock_Addr_Type;
   --        Server   : Socket_Type;
   --        Socket   : Socket_Type;
   --        Channel  : Stream_Access;
108

Richard Kenner committed
109 110 111
   --     begin
   --        accept Start;
   --
112
   --        --  Get an Internet address of a host (here the local host name).
Richard Kenner committed
113 114
   --        --  Note that a host can have several addresses. Here we get
   --        --  the first one which is supposed to be the official one.
115

116
   --        Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1);
117

Richard Kenner committed
118
   --        --  Get a socket address that is an Internet address and a port
119 120 121

   --        Address.Port := 5876;

Richard Kenner committed
122
   --        --  The first step is to create a socket. Once created, this
123 124
   --        --  socket must be associated to with an address. Usually only
   --        --  a server (Pong here) needs to bind an address explicitly.
Richard Kenner committed
125 126 127
   --        --  Most of the time clients can skip this step because the
   --        --  socket routines will bind an arbitrary address to an unbound
   --        --  socket.
128

Richard Kenner committed
129
   --        Create_Socket (Server);
130 131 132

   --        --  Allow reuse of local addresses

Richard Kenner committed
133 134 135 136
   --        Set_Socket_Option
   --          (Server,
   --           Socket_Level,
   --           (Reuse_Address, True));
137

Richard Kenner committed
138
   --        Bind_Socket (Server, Address);
139 140 141

   --        --  A server marks a socket as willing to receive connect events

Richard Kenner committed
142
   --        Listen_Socket (Server);
143

Richard Kenner committed
144 145 146 147
   --        --  Once a server calls Listen_Socket, incoming connects events
   --        --  can be accepted. The returned Socket is a new socket that
   --        --  represents the server side of the connection. Server remains
   --        --  available to receive further connections.
148

Richard Kenner committed
149
   --        Accept_Socket (Server, Socket, Address);
150 151 152

   --        --  Return a stream associated to the connected socket

Richard Kenner committed
153
   --        Channel := Stream (Socket);
154

Richard Kenner committed
155
   --        --  Force Pong to block
156

Richard Kenner committed
157
   --        delay 0.2;
158 159 160

   --        --  Receive and print message from client Ping

Richard Kenner committed
161 162
   --        declare
   --           Message : String := String'Input (Channel);
163

Richard Kenner committed
164 165
   --        begin
   --           Ada.Text_IO.Put_Line (Message);
166 167 168

   --           --  Send same message back to client Ping

Richard Kenner committed
169 170
   --           String'Output (Channel, Message);
   --        end;
171

Richard Kenner committed
172 173
   --        Close_Socket (Server);
   --        Close_Socket (Socket);
174

Richard Kenner committed
175
   --        --  Part of the multicast example
176

Richard Kenner committed
177 178
   --        --  Create a datagram socket to send connectionless, unreliable
   --        --  messages of a fixed maximum length.
179

Richard Kenner committed
180
   --        Create_Socket (Socket, Family_Inet, Socket_Datagram);
181 182 183

   --        --  Allow reuse of local addresses

Richard Kenner committed
184 185 186 187
   --        Set_Socket_Option
   --          (Socket,
   --           Socket_Level,
   --           (Reuse_Address, True));
188 189 190

   --        --  Join a multicast group

Richard Kenner committed
191 192 193 194
   --        Set_Socket_Option
   --          (Socket,
   --           IP_Protocol_For_IP_Level,
   --           (Add_Membership, Inet_Addr (Group), Any_Inet_Addr));
195

Richard Kenner committed
196 197 198 199 200
   --        --  Controls the live time of the datagram to avoid it being
   --        --  looped forever due to routing errors. Routers decrement
   --        --  the TTL of every datagram as it traverses from one network
   --        --  to another and when its value reaches 0 the packet is
   --        --  dropped. Default is 1.
201

Richard Kenner committed
202 203 204 205
   --        Set_Socket_Option
   --          (Socket,
   --           IP_Protocol_For_IP_Level,
   --           (Multicast_TTL, 1));
206 207 208

   --        --  Want the data you send to be looped back to your host

Richard Kenner committed
209 210 211 212
   --        Set_Socket_Option
   --          (Socket,
   --           IP_Protocol_For_IP_Level,
   --           (Multicast_Loop, True));
213 214 215 216

   --        --  If this socket is intended to receive messages, bind it
   --        --  to a given socket address.

Richard Kenner committed
217 218
   --        Address.Addr := Any_Inet_Addr;
   --        Address.Port := 55505;
219

Richard Kenner committed
220
   --        Bind_Socket (Socket, Address);
221

Richard Kenner committed
222 223
   --        --  If this socket is intended to send messages, provide the
   --        --  receiver socket address.
224

Richard Kenner committed
225 226
   --        Address.Addr := Inet_Addr (Group);
   --        Address.Port := 55506;
227

Richard Kenner committed
228
   --        Channel := Stream (Socket, Address);
229 230 231

   --        --  Receive and print message from client Ping

Richard Kenner committed
232 233
   --        declare
   --           Message : String := String'Input (Channel);
234

Richard Kenner committed
235
   --        begin
236 237
   --           --  Get the address of the sender

Richard Kenner committed
238 239
   --           Address := Get_Address (Channel);
   --           Ada.Text_IO.Put_Line (Message & " from " & Image (Address));
240 241 242

   --           --  Send same message back to client Ping

Richard Kenner committed
243 244
   --           String'Output (Channel, Message);
   --        end;
245

Richard Kenner committed
246
   --        Close_Socket (Socket);
247

Richard Kenner committed
248
   --        accept Stop;
249

Richard Kenner committed
250 251 252 253
   --     exception when E : others =>
   --        Ada.Text_IO.Put_Line
   --          (Exception_Name (E) & ": " & Exception_Message (E));
   --     end Pong;
254

Richard Kenner committed
255 256 257 258
   --     task Ping is
   --        entry Start;
   --        entry Stop;
   --     end Ping;
259

Richard Kenner committed
260 261 262 263
   --     task body Ping is
   --        Address  : Sock_Addr_Type;
   --        Socket   : Socket_Type;
   --        Channel  : Stream_Access;
264

Richard Kenner committed
265 266
   --     begin
   --        accept Start;
267 268 269

   --        --  See comments in Ping section for the first steps

270
   --        Address.Addr := Addresses (Get_Host_By_Name (Host_Name), 1);
271
   --        Address.Port := 5876;
Richard Kenner committed
272
   --        Create_Socket (Socket);
273

Richard Kenner committed
274 275 276 277
   --        Set_Socket_Option
   --          (Socket,
   --           Socket_Level,
   --           (Reuse_Address, True));
278

Richard Kenner committed
279
   --        --  Force Pong to block
280

Richard Kenner committed
281
   --        delay 0.2;
282

Richard Kenner committed
283 284 285 286
   --        --  If the client's socket is not bound, Connect_Socket will
   --        --  bind to an unused address. The client uses Connect_Socket to
   --        --  create a logical connection between the client's socket and
   --        --  a server's socket returned by Accept_Socket.
287

Richard Kenner committed
288
   --        Connect_Socket (Socket, Address);
289

Richard Kenner committed
290
   --        Channel := Stream (Socket);
291

Richard Kenner committed
292
   --        --  Send message to server Pong.
293

Richard Kenner committed
294
   --        String'Output (Channel, "Hello world");
295

Richard Kenner committed
296
   --        --  Force Ping to block
297

Richard Kenner committed
298
   --        delay 0.2;
299 300 301

   --        --  Receive and print message from server Pong

Richard Kenner committed
302 303
   --        Ada.Text_IO.Put_Line (String'Input (Channel));
   --        Close_Socket (Socket);
304 305 306

   --        --  Part of multicast example. Code similar to Pong's one

Richard Kenner committed
307
   --        Create_Socket (Socket, Family_Inet, Socket_Datagram);
308

Richard Kenner committed
309 310 311 312
   --        Set_Socket_Option
   --          (Socket,
   --           Socket_Level,
   --           (Reuse_Address, True));
313

Richard Kenner committed
314 315 316 317
   --        Set_Socket_Option
   --          (Socket,
   --           IP_Protocol_For_IP_Level,
   --           (Add_Membership, Inet_Addr (Group), Any_Inet_Addr));
318

Richard Kenner committed
319 320 321 322
   --        Set_Socket_Option
   --          (Socket,
   --           IP_Protocol_For_IP_Level,
   --           (Multicast_TTL, 1));
323

Richard Kenner committed
324 325 326 327
   --        Set_Socket_Option
   --          (Socket,
   --           IP_Protocol_For_IP_Level,
   --           (Multicast_Loop, True));
328

Richard Kenner committed
329 330
   --        Address.Addr := Any_Inet_Addr;
   --        Address.Port := 55506;
331

Richard Kenner committed
332
   --        Bind_Socket (Socket, Address);
333

Richard Kenner committed
334 335
   --        Address.Addr := Inet_Addr (Group);
   --        Address.Port := 55505;
336

Richard Kenner committed
337
   --        Channel := Stream (Socket, Address);
338 339 340

   --        --  Send message to server Pong

Richard Kenner committed
341
   --        String'Output (Channel, "Hello world");
342 343 344

   --        --  Receive and print message from server Pong

Richard Kenner committed
345 346
   --        declare
   --           Message : String := String'Input (Channel);
347

Richard Kenner committed
348 349 350 351
   --        begin
   --           Address := Get_Address (Channel);
   --           Ada.Text_IO.Put_Line (Message & " from " & Image (Address));
   --        end;
352

Richard Kenner committed
353
   --        Close_Socket (Socket);
354

Richard Kenner committed
355
   --        accept Stop;
356

Richard Kenner committed
357 358 359 360
   --     exception when E : others =>
   --        Ada.Text_IO.Put_Line
   --          (Exception_Name (E) & ": " & Exception_Message (E));
   --     end Ping;
361

Richard Kenner committed
362 363 364 365
   --  begin
   --     --  Indicate whether the thread library provides process
   --     --  blocking IO. Basically, if you are not using FSU threads
   --     --  the default is ok.
366

Richard Kenner committed
367 368 369 370 371 372 373 374 375
   --     Initialize (Process_Blocking_IO => False);
   --     Ping.Start;
   --     Pong.Start;
   --     Ping.Stop;
   --     Pong.Stop;
   --     Finalize;
   --  end PingPong;

   procedure Initialize (Process_Blocking_IO : Boolean := False);
376 377 378 379 380 381 382 383 384 385 386 387
   --  Initialize must be called before using any other socket routines.
   --  The Process_Blocking_IO parameter indicates whether the thread
   --  library provides process-blocking or thread-blocking input/output
   --  operations. In the former case (typically with FSU threads)
   --  GNAT.Sockets should be initialized with a value of True to
   --  provide task-blocking IO through an emulation mechanism.
   --  Only the first call to Initialize is taken into account (further
   --  calls will be ignored). Note that with the default value
   --  of Process_Blocking_IO, this operation is a no-op on UNIX
   --  platforms, but applications should make sure to call it
   --  if portability is expected: some platforms (such as Windows)
   --  require initialization before any other socket operations.
Richard Kenner committed
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

   procedure Finalize;
   --  After Finalize is called it is not possible to use any routines
   --  exported in by this package. This procedure is idempotent.

   type Socket_Type is private;
   --  Sockets are used to implement a reliable bi-directional
   --  point-to-point, stream-based connections between
   --  hosts. No_Socket provides a special value to denote
   --  uninitialized sockets.

   No_Socket : constant Socket_Type;

   Socket_Error : exception;
   --  There is only one exception in this package to deal with an
   --  error during a socket routine. Once raised, its message
   --  contains a string describing the error code.

   function Image (Socket : Socket_Type) return String;
   --  Return a printable string for Socket

   function To_C (Socket : Socket_Type) return Integer;
   --  Return a file descriptor to be used by external subprograms
   --  especially the C functions that are not yet interfaced in this
   --  package.

   type Family_Type is (Family_Inet, Family_Inet6);
   --  Address family (or protocol family) identifies the
   --  communication domain and groups protocols with similar address
   --  formats. IPv6 will soon be supported.

   type Mode_Type is (Socket_Stream, Socket_Datagram);
   --  Stream sockets provide connection-oriented byte
   --  streams. Datagram sockets support unreliable connectionless
   --  message based communication.

   type Shutmode_Type is (Shut_Read, Shut_Write, Shut_Read_Write);
   --  When a process closes a socket, the policy is to retain any
   --  data queued until either a delivery or a timeout expiration (in
   --  this case, the data are discarded). A finer control is
   --  available through shutdown. With Shut_Read, no more data can be
   --  received from the socket. With_Write, no more data can be
   --  transmitted. Neither transmission nor reception can be
   --  performed with Shut_Read_Write.

   type Port_Type is new Natural;
   --  Classical port definition. No_Port provides a special value to
   --  denote uninitialized port. Any_Port provides a special value
   --  enabling all ports.

   Any_Port : constant Port_Type;
   No_Port  : constant Port_Type;

   type Inet_Addr_Type (Family : Family_Type := Family_Inet) is private;
   --  An Internet address depends on an address family (IPv4 contains
   --  4 octets and Ipv6 contains 16 octets). Any_Inet_Address is a
   --  special value treated like a wildcard enabling all addresses.
   --  No_Inet_Addr provides a special value to denote uninitialized
   --  inet addresses.

   Any_Inet_Addr : constant Inet_Addr_Type;
   No_Inet_Addr  : constant Inet_Addr_Type;

   type Sock_Addr_Type (Family : Family_Type := Family_Inet) is record
      Addr : Inet_Addr_Type (Family);
      Port : Port_Type;
   end record;
   --  Socket addresses fully define a socket connection with a
   --  protocol family, an Internet address and a port. No_Sock_Addr
   --  provides a special value for uninitialized socket addresses.

   No_Sock_Addr : constant Sock_Addr_Type;

   function Image (Value : Inet_Addr_Type) return String;
   --  Return an image of an Internet address. IPv4 notation consists
   --  in 4 octets in decimal format separated by dots. IPv6 notation
   --  consists in 16 octets in hexadecimal format separated by
   --  colons (and possibly dots).

   function Image (Value : Sock_Addr_Type) return String;
   --  Return inet address image and port image separated by a colon.

   function Inet_Addr (Image : String) return Inet_Addr_Type;
   --  Convert address image from numbers-and-dots notation into an
   --  inet address.

474
   --  Host entries provide complete information on a given host:
Richard Kenner committed
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
   --  the official name, an array of alternative names or aliases and
   --  array of network addresses.

   type Host_Entry_Type
     (Aliases_Length, Addresses_Length : Natural) is private;

   function Official_Name (E : Host_Entry_Type) return String;
   --  Return official name in host entry

   function Aliases_Length (E : Host_Entry_Type) return Natural;
   --  Return number of aliases in host entry

   function Addresses_Length (E : Host_Entry_Type) return Natural;
   --  Return number of addresses in host entry

   function Aliases
     (E    : Host_Entry_Type;
      N    : Positive := 1)
      return String;
   --  Return N'th aliases in host entry. The first index is 1.

   function Addresses
     (E    : Host_Entry_Type;
      N    : Positive := 1)
      return Inet_Addr_Type;
   --  Return N'th addresses in host entry. The first index is 1.

   Host_Error : exception;
   --  Exception raised by the two following procedures. Once raised,
   --  its message contains a string describing the error code. This
   --  exception is raised when an host entry can not be retrieved.

   function Get_Host_By_Address
     (Address : Inet_Addr_Type;
      Family  : Family_Type := Family_Inet)
      return    Host_Entry_Type;
   --  Return host entry structure for the given inet address

   function Get_Host_By_Name
     (Name : String)
      return Host_Entry_Type;
516 517
   --  Return host entry structure for the given host name. Here name
   --  is either a host name, or an IP address.
Richard Kenner committed
518 519 520 521

   function Host_Name return String;
   --  Return the name of the current host

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
   --  Service entries provide complete information on a given
   --  service: the official name, an array of alternative names or
   --  aliases and the port number.

   type Service_Entry_Type (Aliases_Length : Natural) is private;

   function Official_Name (S : Service_Entry_Type) return String;
   --  Return official name in service entry

   function Port_Number (S : Service_Entry_Type) return Port_Type;
   --  Return port number in service entry

   function Protocol_Name (S : Service_Entry_Type) return String;
   --  Return Protocol in service entry (usually UDP or TCP)

   function Aliases_Length (S : Service_Entry_Type) return Natural;
   --  Return number of aliases in service entry

   function Aliases
     (S    : Service_Entry_Type;
      N    : Positive := 1)
      return String;
   --  Return N'th aliases in service entry. The first index is 1.

   function Get_Service_By_Name
     (Name     : String;
      Protocol : String)
      return     Service_Entry_Type;
   --  Return service entry structure for the given service name

   function Get_Service_By_Port
     (Port     : Port_Type;
      Protocol : String)
      return     Service_Entry_Type;
   --  Return service entry structure for the given service port number

   Service_Error : exception;

Richard Kenner committed
560 561 562
   --  Errors are described by an enumeration type. There is only one
   --  exception Socket_Error in this package to deal with an error
   --  during a socket routine. Once raised, its message contains the
563 564 565
   --  error code between brackets and a string describing the error code.

   --  The name of the enumeration constant documents the error condition.
Richard Kenner committed
566 567

   type Error_Type is
568 569
     (Success,
      Permission_Denied,
Richard Kenner committed
570 571 572 573 574
      Address_Already_In_Use,
      Cannot_Assign_Requested_Address,
      Address_Family_Not_Supported_By_Protocol,
      Operation_Already_In_Progress,
      Bad_File_Descriptor,
575
      Software_Caused_Connection_Abort,
Richard Kenner committed
576
      Connection_Refused,
577 578
      Connection_Reset_By_Peer,
      Destination_Address_Required,
Richard Kenner committed
579
      Bad_Address,
580 581
      Host_Is_Down,
      No_Route_To_Host,
Richard Kenner committed
582 583 584 585 586
      Operation_Now_In_Progress,
      Interrupted_System_Call,
      Invalid_Argument,
      Input_Output_Error,
      Transport_Endpoint_Already_Connected,
587 588
      Too_Many_Symbolic_Links,
      Too_Many_Open_Files,
Richard Kenner committed
589
      Message_Too_Long,
590 591 592
      File_Name_Too_Long,
      Network_Is_Down,
      Network_Dropped_Connection_Because_Of_Reset,
Richard Kenner committed
593 594 595 596
      Network_Is_Unreachable,
      No_Buffer_Space_Available,
      Protocol_Not_Available,
      Transport_Endpoint_Not_Connected,
597
      Socket_Operation_On_Non_Socket,
Richard Kenner committed
598
      Operation_Not_Supported,
599
      Protocol_Family_Not_Supported,
Richard Kenner committed
600
      Protocol_Not_Supported,
601 602
      Protocol_Wrong_Type_For_Socket,
      Cannot_Send_After_Transport_Endpoint_Shutdown,
Richard Kenner committed
603 604
      Socket_Type_Not_Supported,
      Connection_Timed_Out,
605
      Too_Many_References,
Richard Kenner committed
606 607 608
      Resource_Temporarily_Unavailable,
      Unknown_Host,
      Host_Name_Lookup_Failure,
609
      Non_Recoverable_Error,
Richard Kenner committed
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
      Unknown_Server_Error,
      Cannot_Resolve_Error);

   --  Get_Socket_Options and Set_Socket_Options manipulate options
   --  associated with a socket. Options may exist at multiple
   --  protocol levels in the communication stack. Socket_Level is the
   --  uppermost socket level.

   type Level_Type is (
     Socket_Level,
     IP_Protocol_For_IP_Level,
     IP_Protocol_For_UDP_Level,
     IP_Protocol_For_TCP_Level);

   --  There are several options available to manipulate sockets. Each
   --  option has a name and several values available. Most of the
   --  time, the value is a boolean to enable or disable this option.

   type Option_Name is (
     Keep_Alive,      -- Enable sending of keep-alive messages
     Reuse_Address,   -- Allow bind to reuse local address
     Broadcast,       -- Enable datagram sockets to recv/send broadcast packets
     Send_Buffer,     -- Set/get the maximum socket send buffer in bytes
     Receive_Buffer,  -- Set/get the maximum socket recv buffer in bytes
     Linger,          -- Shutdown wait for msg to be sent or timeout occur
     Error,           -- Get and clear the pending socket error
     No_Delay,        -- Do not delay send to coalesce packets (TCP_NODELAY)
     Add_Membership,  -- Join a multicast group
     Drop_Membership, -- Leave a multicast group
639
     Multicast_TTL,   -- Indicate the time-to-live of sent multicast packets
Richard Kenner committed
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
     Multicast_Loop); -- Sent multicast packets are looped to the local socket

   type Option_Type (Name : Option_Name := Keep_Alive) is record
      case Name is
         when Keep_Alive      |
              Reuse_Address   |
              Broadcast       |
              Linger          |
              No_Delay        |
              Multicast_Loop  =>
            Enabled : Boolean;

            case Name is
               when Linger    =>
                  Seconds : Natural;
               when others    =>
                  null;
            end case;

         when Send_Buffer     |
              Receive_Buffer  =>
            Size : Natural;

         when Error           =>
            Error : Error_Type;

         when Add_Membership  |
              Drop_Membership =>
            Multiaddr : Inet_Addr_Type;
            Interface : Inet_Addr_Type;

         when Multicast_TTL   =>
            Time_To_Live : Natural;

      end case;
   end record;

   --  There are several controls available to manipulate
   --  sockets. Each option has a name and several values available.
   --  These controls differ from the socket options in that they are
   --  not specific to sockets but are available for any device.

   type Request_Name is (
      Non_Blocking_IO,  --  Cause a caller not to wait on blocking operations.
      N_Bytes_To_Read); --  Return the number of bytes available to read

   type Request_Type (Name : Request_Name := Non_Blocking_IO) is record
      case Name is
         when Non_Blocking_IO =>
            Enabled : Boolean;

         when N_Bytes_To_Read =>
            Size : Natural;

      end case;
   end record;

697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
   --  A request flag allows to specify the type of message
   --  transmissions or receptions. A request flag can be a
   --  combination of zero or more predefined request flags.

   type Request_Flag_Type is private;

   No_Request_Flag : constant Request_Flag_Type;
   --  This flag corresponds to the normal execution of an operation.

   Process_Out_Of_Band_Data : constant Request_Flag_Type;
   --  This flag requests that the receive or send function operates
   --  on out-of-band data when the socket supports this notion (e.g.
   --  Socket_Stream).

   Peek_At_Incoming_Data : constant Request_Flag_Type;
   --  This flag causes the receive operation to return data from the
   --  beginning of the receive queue without removing that data from
   --  the queue. A subsequent receive call will return the same data.

   Wait_For_A_Full_Reception : constant Request_Flag_Type;
   --  This flag requests that the operation block until the full
   --  request is satisfied. However, the call may still return less
   --  data than requested if a signal is caught, an error or
   --  disconnect occurs, or the next data to be received is of a dif-
   --  ferent type than that returned.

   Send_End_Of_Record : constant Request_Flag_Type;
   --  This flag indicates that the entire message has been sent and
   --  so this terminates the record.

   function "+" (L, R : Request_Flag_Type) return Request_Flag_Type;
   --  Combine flag L with flag R

   type Stream_Element_Reference is access all Ada.Streams.Stream_Element;

   type Vector_Element is record
      Base   : Stream_Element_Reference;
      Length : Ada.Streams.Stream_Element_Count;
   end record;

   type Vector_Type is array (Integer range <>) of Vector_Element;

Richard Kenner committed
739 740 741 742
   procedure Create_Socket
     (Socket : out Socket_Type;
      Family : Family_Type := Family_Inet;
      Mode   : Mode_Type   := Socket_Stream);
743
   --  Create an endpoint for communication. Raises Socket_Error on error.
Richard Kenner committed
744 745 746 747 748 749 750 751 752

   procedure Accept_Socket
     (Server  : Socket_Type;
      Socket  : out Socket_Type;
      Address : out Sock_Addr_Type);
   --  Extract the first connection request on the queue of pending
   --  connections, creates a new connected socket with mostly the
   --  same properties as Server, and allocates a new socket. The
   --  returned Address is filled in with the address of the
753
   --  connection. Raises Socket_Error on error.
Richard Kenner committed
754 755 756 757 758 759 760 761 762 763 764 765 766 767

   procedure Bind_Socket
     (Socket  : Socket_Type;
      Address : Sock_Addr_Type);
   --  Once a socket is created, assign a local address to it. Raise
   --  Socket_Error on error.

   procedure Close_Socket (Socket : Socket_Type);
   --  Close a socket and more specifically a non-connected socket.

   procedure Connect_Socket
     (Socket : Socket_Type;
      Server : in out Sock_Addr_Type);
   --  Make a connection to another socket which has the address of
768
   --  Server. Raises Socket_Error on error.
Richard Kenner committed
769 770 771 772 773 774

   procedure Control_Socket
     (Socket  : Socket_Type;
      Request : in out Request_Type);
   --  Obtain or set parameter values that control the socket. This
   --  control differs from the socket options in that they are not
775
   --  specific to sockets but are available for any device.
Richard Kenner committed
776 777 778 779 780 781

   function Get_Peer_Name (Socket : Socket_Type) return Sock_Addr_Type;
   --  Return the peer or remote socket address of a socket. Raise
   --  Socket_Error on error.

   function Get_Socket_Name (Socket : Socket_Type) return Sock_Addr_Type;
782 783 784
   --  Return the local or current socket address of a socket. Return
   --  No_Sock_Addr on error (for instance, socket closed or not
   --  locally bound).
Richard Kenner committed
785 786 787 788 789 790

   function Get_Socket_Option
     (Socket : Socket_Type;
      Level  : Level_Type := Socket_Level;
      Name   : Option_Name)
      return   Option_Type;
791 792
   --  Get the options associated with a socket. Raises Socket_Error
   --  on error.
Richard Kenner committed
793 794 795 796 797 798 799 800 801 802 803 804

   procedure Listen_Socket
     (Socket : Socket_Type;
      Length : Positive := 15);
   --  To accept connections, a socket is first created with
   --  Create_Socket, a willingness to accept incoming connections and
   --  a queue Length for incoming connections are specified. Raise
   --  Socket_Error on error.

   procedure Receive_Socket
     (Socket : Socket_Type;
      Item   : out Ada.Streams.Stream_Element_Array;
805 806
      Last   : out Ada.Streams.Stream_Element_Offset;
      Flags  : Request_Flag_Type := No_Request_Flag);
Richard Kenner committed
807 808 809
   --  Receive message from Socket. Last is the index value such that
   --  Item (Last) is the last character assigned. Note that Last is
   --  set to Item'First - 1 when the socket has been closed by
810 811
   --  peer. This is not an error and no exception is raised. Flags
   --  allows to control the reception. Raise Socket_Error on error.
Richard Kenner committed
812 813 814 815 816

   procedure Receive_Socket
     (Socket : Socket_Type;
      Item   : out Ada.Streams.Stream_Element_Array;
      Last   : out Ada.Streams.Stream_Element_Offset;
817 818
      From   : out Sock_Addr_Type;
      Flags  : Request_Flag_Type := No_Request_Flag);
Richard Kenner committed
819 820 821
   --  Receive message from Socket. If Socket is not
   --  connection-oriented, the source address From of the message is
   --  filled in. Last is the index value such that Item (Last) is the
822 823 824 825 826 827 828 829 830
   --  last character assigned. Flags allows to control the
   --  reception. Raises Socket_Error on error.

   procedure Receive_Vector
     (Socket : Socket_Type;
      Vector : Vector_Type;
      Count  : out Ada.Streams.Stream_Element_Count);
   --  Receive data from a socket and scatter it into the set of vector
   --  elements Vector. Count is set to the count of received stream elements.
Richard Kenner committed
831 832 833

   function Resolve_Exception
     (Occurrence : Ada.Exceptions.Exception_Occurrence)
834
      return       Error_Type;
Richard Kenner committed
835 836 837 838 839 840 841 842 843
   --  When Socket_Error or Host_Error are raised, the exception
   --  message contains the error code between brackets and a string
   --  describing the error code. Resolve_Error extracts the error
   --  code from an exception message and translate it into an
   --  enumeration value.

   procedure Send_Socket
     (Socket : Socket_Type;
      Item   : Ada.Streams.Stream_Element_Array;
844 845
      Last   : out Ada.Streams.Stream_Element_Offset;
      Flags  : Request_Flag_Type := No_Request_Flag);
Richard Kenner committed
846
   --  Transmit a message to another socket. Note that Last is set to
847 848 849 850
   --  Item'First-1 when socket has been closed by peer. This is not
   --  considered an error and no exception is raised. Flags allows to
   --  control the transmission. Raises Socket_Error on any other
   --  error condition.
Richard Kenner committed
851 852 853 854 855

   procedure Send_Socket
     (Socket : Socket_Type;
      Item   : Ada.Streams.Stream_Element_Array;
      Last   : out Ada.Streams.Stream_Element_Offset;
856 857
      To     : Sock_Addr_Type;
      Flags  : Request_Flag_Type := No_Request_Flag);
Richard Kenner committed
858
   --  Transmit a message to another socket. The address is given by
859 860 861 862 863 864 865 866 867
   --  To. Flags allows to control the transmission. Raises
   --  Socket_Error on error.

   procedure Send_Vector
     (Socket : Socket_Type;
      Vector : Vector_Type;
      Count  : out Ada.Streams.Stream_Element_Count);
   --  Transmit data gathered from the set of vector elements Vector to a
   --  socket. Count is set to the count of transmitted stream elements.
Richard Kenner committed
868 869 870 871 872

   procedure Set_Socket_Option
     (Socket : Socket_Type;
      Level  : Level_Type := Socket_Level;
      Option : Option_Type);
873
   --  Manipulate socket options. Raises Socket_Error on error.
Richard Kenner committed
874 875 876 877 878 879 880

   procedure Shutdown_Socket
     (Socket : Socket_Type;
      How    : Shutmode_Type := Shut_Read_Write);
   --  Shutdown a connected socket. If How is Shut_Read, further
   --  receives will be disallowed. If How is Shut_Write, further
   --  sends will be disallowed. If how is Shut_Read_Write, further
881
   --  sends and receives will be disallowed.
Richard Kenner committed
882 883 884 885 886 887 888

   type Stream_Access is access all Ada.Streams.Root_Stream_Type'Class;
   --  Same interface as Ada.Streams.Stream_IO

   function Stream
     (Socket : Socket_Type)
      return   Stream_Access;
Arnaud Charlet committed
889 890
   --  Create a stream associated with a stream-based socket that is
   --  already connected.
Richard Kenner committed
891 892 893 894 895

   function Stream
     (Socket  : Socket_Type;
      Send_To : Sock_Addr_Type)
      return    Stream_Access;
Arnaud Charlet committed
896 897
   --  Create a stream associated with a datagram-based socket that is
   --  already bound. Send_To is the socket address to which messages are
Richard Kenner committed
898 899 900 901
   --  being sent.

   function Get_Address
     (Stream : Stream_Access)
902
      return   Sock_Addr_Type;
Richard Kenner committed
903 904 905
   --  Return the socket address from which the last message was
   --  received.

Arnaud Charlet committed
906 907 908 909 910
   procedure Free is new Ada.Unchecked_Deallocation
     (Ada.Streams.Root_Stream_Type'Class, Stream_Access);
   --  Destroy a stream created by one of the Stream functions above,
   --  releasing the corresponding resources. The user is responsible
   --  for calling this subprogram when the stream is not needed anymore.
Arnaud Charlet committed
911

912
   type Socket_Set_Type is limited private;
Richard Kenner committed
913 914 915 916 917 918 919 920 921
   --  This type allows to manipulate sets of sockets. It allows to
   --  wait for events on multiple endpoints at one time. This is an
   --  access type on a system dependent structure. To avoid memory
   --  leaks it is highly recommended to clean the access value with
   --  procedure Empty.

   procedure Clear (Item : in out Socket_Set_Type; Socket : Socket_Type);
   --  Remove Socket from Item

922 923
   procedure Copy  (Source : Socket_Set_Type; Target : in out Socket_Set_Type);
   --  Copy Source into Target as Socket_Set_Type is limited private
Richard Kenner committed
924 925 926 927

   procedure Empty (Item : in out Socket_Set_Type);
   --  Remove all Sockets from Item and deallocate internal data

928 929 930 931
   procedure Get (Item : in out Socket_Set_Type; Socket : out Socket_Type);
   --  Extract a Socket from socket set Item. Socket is set to
   --  No_Socket when the set is empty.

Richard Kenner committed
932
   function Is_Empty
933
     (Item  : Socket_Set_Type)
Richard Kenner committed
934 935 936 937 938 939 940 941 942
      return  Boolean;
   --  Return True if Item is empty

   function Is_Set
     (Item   : Socket_Set_Type;
      Socket : Socket_Type)
      return   Boolean;
   --  Return True if Socket is present in Item

943 944 945
   procedure Set   (Item : in out Socket_Set_Type; Socket : Socket_Type);
   --  Insert Socket into Item

Richard Kenner committed
946
   --  C select() waits for a number of file descriptors to change
947
   --  status. Usually, three independent sets of descriptors are
Richard Kenner committed
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
   --  watched (read, write and exception). A timeout gives an upper
   --  bound on the amount of time elapsed before select returns.
   --  This function blocks until an event occurs. On some platforms,
   --  C select can block the full process.
   --
   --  Check_Selector provides the very same behaviour. The only
   --  difference is that it does not watch for exception events. Note
   --  that on some platforms it is kept process blocking in purpose.
   --  The timeout parameter allows the user to have the behaviour he
   --  wants. Abort_Selector allows to abort safely a Check_Selector
   --  that is blocked forever. A special file descriptor is opened by
   --  Create_Selector and included in each call to
   --  Check_Selector. Abort_Selector causes an event to occur on this
   --  descriptor in order to unblock Check_Selector. The user must
   --  call Close_Selector to discard this special file. A reason to
   --  abort a select operation is typically to add a socket in one of
   --  the socket sets when the timeout is set to forever.

   type Selector_Type is limited private;
   type Selector_Access is access all Selector_Type;

969 970 971 972 973 974 975 976 977 978
   --  Selector_Duration is a subtype of Standard.Duration because the
   --  full range of Standard.Duration cannot be represented in the
   --  equivalent C structure. Moreover, negative values are not
   --  allowed to avoid system incompatibilities.

   Immediate : constant := 0.0;
   Forever   : constant := Duration (Integer'Last) * 1.0;

   subtype Selector_Duration is Duration range Immediate .. Forever;

Richard Kenner committed
979 980 981 982 983 984 985 986 987 988 989 990 991
   procedure Create_Selector (Selector : out Selector_Type);
   --  Create a new selector

   procedure Close_Selector (Selector : in out Selector_Type);
   --  Close Selector and all internal descriptors associated

   type Selector_Status is (Completed, Expired, Aborted);

   procedure Check_Selector
     (Selector     : in out Selector_Type;
      R_Socket_Set : in out Socket_Set_Type;
      W_Socket_Set : in out Socket_Set_Type;
      Status       : out Selector_Status;
992
      Timeout      : Selector_Duration := Forever);
Richard Kenner committed
993 994 995 996 997
   --  Return when one Socket in R_Socket_Set has some data to be read
   --  or if one Socket in W_Socket_Set is ready to receive some
   --  data. In these cases Status is set to Completed and sockets
   --  that are ready are set in R_Socket_Set or W_Socket_Set. Status
   --  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
Richard Kenner committed
999 1000 1001
   --  received while checking socket status. As this procedure
   --  returns when Timeout occurs, it is a design choice to keep this
   --  procedure process blocking. Note that a Timeout of 0.0 returns
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
   --  immediately. Also note that two different objects must be passed
   --  as R_Socket_Set and W_Socket_Set (even if they contain the same
   --  set of Sockets), or some event will be lost.

   procedure Check_Selector
     (Selector     : in out Selector_Type;
      R_Socket_Set : in out Socket_Set_Type;
      W_Socket_Set : in out Socket_Set_Type;
      E_Socket_Set : in out Socket_Set_Type;
      Status       : out Selector_Status;
      Timeout      : Selector_Duration := Forever);
   --  This refined version of Check_Selector allows to watch for
   --  exception events (that is notifications of out-of-band
   --  transmission and reception). As above, all of R_Socket_Set,
   --  W_Socket_Set and E_Socket_Set must be different objects.
Richard Kenner committed
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029

   procedure Abort_Selector (Selector : Selector_Type);
   --  Send an abort signal to the selector.

private

   type Socket_Type is new Integer;
   No_Socket : constant Socket_Type := -1;

   type Selector_Type is limited record
      R_Sig_Socket : Socket_Type;
      W_Sig_Socket : Socket_Type;
   end record;
1030 1031 1032

   pragma Volatile (Selector_Type);

Richard Kenner committed
1033 1034 1035
   --  The two signalling sockets are used to abort a select
   --  operation.

1036 1037 1038 1039 1040 1041 1042
   subtype Socket_Set_Access is System.Address;
   No_Socket_Set : constant Socket_Set_Access := System.Null_Address;

   type Socket_Set_Type is record
      Last : Socket_Type       := No_Socket;
      Set  : Socket_Set_Access := No_Socket_Set;
   end record;
Richard Kenner committed
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069

   subtype Inet_Addr_Comp_Type is Natural range 0 .. 255;
   --  Octet for Internet address

   type Inet_Addr_VN_Type is array (Natural range <>) of Inet_Addr_Comp_Type;

   subtype Inet_Addr_V4_Type is Inet_Addr_VN_Type (1 ..  4);
   subtype Inet_Addr_V6_Type is Inet_Addr_VN_Type (1 .. 16);

   type Inet_Addr_Type (Family : Family_Type := Family_Inet) is record
      case Family is
         when Family_Inet =>
            Sin_V4 : Inet_Addr_V4_Type := (others => 0);

         when Family_Inet6 =>
            Sin_V6 : Inet_Addr_V6_Type := (others => 0);
      end case;
   end record;

   Any_Port : constant Port_Type := 0;
   No_Port  : constant Port_Type := 0;

   Any_Inet_Addr : constant Inet_Addr_Type := (Family_Inet, (others => 0));
   No_Inet_Addr  : constant Inet_Addr_Type := (Family_Inet, (others => 0));

   No_Sock_Addr  : constant Sock_Addr_Type := (Family_Inet, No_Inet_Addr, 0);

1070
   Max_Name_Length : constant := 64;
Richard Kenner committed
1071 1072
   --  The constant MAXHOSTNAMELEN is usually set to 64

1073
   subtype Name_Index is Natural range 1 .. Max_Name_Length;
Richard Kenner committed
1074

1075 1076
   type Name_Type
     (Length : Name_Index := Max_Name_Length)
Richard Kenner committed
1077 1078 1079 1080 1081
   is record
      Name : String (1 .. Length);
   end record;
   --  We need fixed strings to avoid access types in host entry type

1082
   type Name_Array is array (Natural range <>) of Name_Type;
Richard Kenner committed
1083 1084 1085
   type Inet_Addr_Array is array (Natural range <>) of Inet_Addr_Type;

   type Host_Entry_Type (Aliases_Length, Addresses_Length : Natural) is record
1086 1087
      Official  : Name_Type;
      Aliases   : Name_Array (1 .. Aliases_Length);
Richard Kenner committed
1088 1089 1090
      Addresses : Inet_Addr_Array (1 .. Addresses_Length);
   end record;

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
   type Service_Entry_Type (Aliases_Length : Natural) is record
      Official  : Name_Type;
      Aliases   : Name_Array (1 .. Aliases_Length);
      Port      : Port_Type;
      Protocol  : Name_Type;
   end record;

   type Request_Flag_Type is mod 2 ** 8;
   No_Request_Flag           : constant Request_Flag_Type := 0;
   Process_Out_Of_Band_Data  : constant Request_Flag_Type := 1;
   Peek_At_Incoming_Data     : constant Request_Flag_Type := 2;
   Wait_For_A_Full_Reception : constant Request_Flag_Type := 4;
   Send_End_Of_Record        : constant Request_Flag_Type := 8;

Richard Kenner committed
1105
end GNAT.Sockets;