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