src/node/socket.h
author Tom Henderson <tomh@tomh.org>
Wed Aug 05 20:53:44 2009 -0700 (2009-08-05)
changeset 4697 6e048d6486d8
parent 4357 9c638ff9f732
child 5227 ecb08c1fc273
permissions -rw-r--r--
Implement UdpSocketImpl::Close ()
     1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
     2 /*
     3  * Copyright (c) 2006 Georgia Tech Research Corporation
     4  *               2007 INRIA
     5  *
     6  * This program is free software; you can redistribute it and/or modify
     7  * it under the terms of the GNU General Public License version 2 as
     8  * published by the Free Software Foundation;
     9  *
    10  * This program is distributed in the hope that it will be useful,
    11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  * GNU General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU General Public License
    16  * along with this program; if not, write to the Free Software
    17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    18  *
    19  * Authors: George F. Riley<riley@ece.gatech.edu>
    20  *          Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
    21  */
    22 
    23 #ifndef __SOCKET_H__
    24 #define __SOCKET_H__
    25 
    26 #include "ns3/callback.h"
    27 #include "ns3/ptr.h"
    28 #include "ns3/tag.h"
    29 #include "ns3/object.h"
    30 #include "address.h"
    31 #include <stdint.h>
    32 
    33 namespace ns3 {
    34 
    35 
    36 class Node;
    37 class Packet;
    38 
    39 /**
    40  * \ingroup node
    41  * \defgroup socket Socket
    42  */
    43 
    44 /**
    45  * \brief A low-level Socket API based loosely on the BSD Socket API.
    46  * \ingroup socket
    47  *
    48  * A few things to keep in mind about this type of socket:
    49  * - it uses ns-3 API constructs such as class ns3::Address instead of
    50  *   C-style structs
    51  * - in contrast to the original BSD socket API, this API is asynchronous:
    52  *   it does not contain blocking calls.  Sending and receiving operations
    53  *   must make use of the callbacks provided. 
    54  * - It also uses class ns3::Packet as a fancy byte buffer, allowing 
    55  *   data to be passed across the API using an ns-3 Packet instead of 
    56  *   a raw data pointer.  
    57  * - Not all of the full POSIX sockets API is supported
    58  *
    59  * Other than that, it tries to stick to the BSD API to make it 
    60  * easier for those who know the BSD API to use this API.  
    61  * More details are provided in the ns-3 tutorial.
    62  */
    63 class Socket : public Object
    64 {
    65 public:
    66 
    67   Socket (void);
    68   virtual ~Socket (void);
    69 
    70   enum SocketErrno {
    71     ERROR_NOTERROR,
    72     ERROR_ISCONN,
    73     ERROR_NOTCONN,
    74     ERROR_MSGSIZE,
    75     ERROR_AGAIN,
    76     ERROR_SHUTDOWN,
    77     ERROR_OPNOTSUPP,
    78     ERROR_AFNOSUPPORT,
    79     ERROR_INVAL,
    80     ERROR_BADF,
    81     ERROR_NOROUTETOHOST,
    82     SOCKET_ERRNO_LAST
    83   };
    84 
    85   /**
    86    * This method wraps the creation of sockets that is performed
    87    * by a socket factory on a given node based on a TypeId.
    88    * 
    89    * \return A smart pointer to a newly created socket.
    90    * 
    91    * \param node The node on which to create the socket
    92    * \param tid The TypeId of the socket to create
    93    */
    94   static Ptr<Socket> CreateSocket (Ptr<Node> node, TypeId tid);
    95   /**
    96    * \return the errno associated to the last call which failed in this
    97    *         socket. Each socket's errno is initialized to zero
    98    *         when the socket is created.
    99    */
   100   virtual enum Socket::SocketErrno GetErrno (void) const = 0;
   101   /**
   102    * \returns the node this socket is associated with.
   103    */
   104   virtual Ptr<Node> GetNode (void) const = 0;
   105   /**
   106    * \param connectionSucceeded this callback is invoked when the 
   107    *        connection request initiated by the user is successfully 
   108    *        completed. The callback is passed  back a pointer to 
   109    *        the same socket object.
   110    * \param connectionFailed this callback is invoked when the 
   111    *        connection request initiated by the user is unsuccessfully 
   112    *        completed. The callback is passed back a pointer to the 
   113    *        same socket object. 
   114    */
   115   void SetConnectCallback (Callback<void, Ptr<Socket> > connectionSucceeded,
   116                            Callback<void,  Ptr<Socket> > connectionFailed);
   117   /**
   118    * \brief Accept connection requests from remote hosts
   119    * \param connectionRequest Callback for connection request from peer. 
   120    *        This user callback is passed a pointer to this socket, the 
   121    *        ip address and the port number of the connection originator. 
   122    *        This callback must return true to accept the incoming connection,
   123    *        false otherwise. If the connection is accepted, the 
   124    *        "newConnectionCreated" callback will be invoked later to 
   125    *        give access to the user to the socket created to match 
   126    *        this new connection. If the user does not explicitly 
   127    *        specify this callback, all incoming  connections will be refused.
   128    * \param newConnectionCreated Callback for new connection: when a new
   129    *        is accepted, it is created and the corresponding socket is passed
   130    *        back to the user through this callback. This user callback is 
   131    *        passed a pointer to the new socket, and the ip address and 
   132    *        port number of the connection originator.
   133    */
   134   void SetAcceptCallback (Callback<bool, Ptr<Socket>, 
   135                             const Address &> connectionRequest,
   136                           Callback<void, Ptr<Socket>, 
   137                             const Address&> newConnectionCreated);
   138   /**
   139    * \brief Notify application when a packet has been sent from transport 
   140    *        protocol (non-standard socket call)
   141    * \param dataSent Callback for the event that data is sent from the
   142    *        underlying transport protocol.  This callback is passed a
   143    *        pointer to the socket, and the number of bytes sent.
   144    */
   145   void SetDataSentCallback (Callback<void, Ptr<Socket>, 
   146                             uint32_t> dataSent);
   147   /**
   148    * \brief Notify application when space in transmit buffer is added
   149    *
   150    *        This callback is intended to notify a 
   151    *        socket that would have been blocked in a blocking socket model
   152    *        that space is available in the transmit buffer and that it
   153    *        can call Send() again.  
   154    *
   155    * \param sendCb Callback for the event that the socket transmit buffer
   156    *        fill level has decreased.  This callback is passed a pointer to
   157    *        the socket, and the number of bytes available for writing
   158    *        into the buffer (an absolute value).  If there is no transmit
   159    *        buffer limit, a maximum-sized integer is always returned.
   160    */
   161   void SetSendCallback (Callback<void, Ptr<Socket>, uint32_t> sendCb);
   162   /**
   163    * \brief Notify application when new data is available to be read.
   164    *
   165    *        This callback is intended to notify a socket that would
   166    *        have been blocked in a blocking socket model that data
   167    *        is available to be read.
   168    */
   169   void SetRecvCallback (Callback<void, Ptr<Socket> >);
   170   /** 
   171    * \param address the address to try to allocate
   172    * \returns 0 on success, -1 on failure.
   173    *
   174    * Allocate a local endpoint for this socket.
   175    */
   176   virtual int Bind (const Address &address) = 0;
   177 
   178   /** 
   179    * Allocate a local endpoint for this socket.
   180    *
   181    * \returns 0 on success, -1 on failure.
   182    */
   183   virtual int Bind () = 0;
   184 
   185   /** 
   186    * \brief Close a socket.
   187    * \returns zero on success, -1 on failure.
   188    *
   189    * After the Close call, the socket is no longer valid, and cannot
   190    * safely be used for subsequent operations.
   191    */
   192   virtual int Close (void) = 0;
   193 
   194   /**
   195    * \returns zero on success, -1 on failure.
   196    *
   197    * Do not allow any further Send calls. This method is typically
   198    * implemented for Tcp sockets by a half close.
   199    */
   200   virtual int ShutdownSend (void) = 0;
   201 
   202   /**
   203    * \returns zero on success, -1 on failure.
   204    *
   205    * Do not allow any further Recv calls. This method is typically
   206    * implemented for Tcp sockets by a half close.
   207    */
   208   virtual int ShutdownRecv (void) = 0;
   209 
   210   /**
   211    * \brief Initiate a connection to a remote host
   212    * \param address Address of remote.
   213    */
   214   virtual int Connect (const Address &address) = 0;
   215     
   216   /**
   217    * \brief Listen for incoming connections.
   218    * \returns 0 on success, -1 on error (in which case errno is set).
   219    */
   220   virtual int Listen (void) = 0;
   221 
   222   /**
   223    * \brief Returns the number of bytes which can be sent in a single call
   224    * to Send. 
   225    * 
   226    * For datagram sockets, this returns the number of bytes that
   227    * can be passed atomically through the underlying protocol.
   228    *
   229    * For stream sockets, this returns the available space in bytes
   230    * left in the transmit buffer.
   231    */
   232   virtual uint32_t GetTxAvailable (void) const = 0;
   233  
   234   /**
   235    * \brief Send data (or dummy data) to the remote host
   236    *
   237    * This function matches closely in semantics to the send() function
   238    * call in the standard C library (libc):
   239    *   ssize_t send (int s, const void *msg, size_t len, int flags);
   240    * except that the send I/O is asynchronous.  This is the
   241    * primary Send method at this low-level API and must be implemented 
   242    * by subclasses.
   243    * 
   244    * In a typical blocking sockets model, this call would block upon
   245    * lack of space to hold the message to be sent.  In ns-3 at this
   246    * API, the call returns immediately in such a case, but the callback
   247    * registered with SetSendCallback() is invoked when the socket
   248    * has space (when it conceptually unblocks); this is an asynchronous
   249    * I/O model for send().
   250    * 
   251    * This variant of Send() uses class ns3::Packet to encapsulate
   252    * data, rather than providing a raw pointer and length field.  
   253    * This allows an ns-3 application to attach tags if desired (such
   254    * as a flow ID) and may allow the simulator to avoid some data
   255    * copies.  Despite the appearance of sending Packets on a stream
   256    * socket, just think of it as a fancy byte buffer with streaming
   257    * semantics.    
   258    *
   259    * If either the message buffer within the Packet is too long to pass 
   260    * atomically through the underlying protocol (for datagram sockets), 
   261    * or the message buffer cannot entirely fit in the transmit buffer
   262    * (for stream sockets), -1 is returned and SocketErrno is set 
   263    * to ERROR_MSGSIZE.  If the packet does not fit, the caller can
   264    * split the Packet (based on information obtained from 
   265    * GetTxAvailable) and reattempt to send the data.
   266    *
   267    * The flags argument is formed by or'ing one or more of the values:     
   268    *        MSG_OOB        process out-of-band data 
   269    *        MSG_DONTROUTE  bypass routing, use direct interface 
   270    * These flags are _unsupported_ as of ns-3.1.  
   271    *
   272    * \param p ns3::Packet to send
   273    * \param flags Socket control flags
   274    * \returns the number of bytes accepted for transmission if no error
   275    *          occurs, and -1 otherwise.
   276    *
   277    * \see SetSendCallback
   278    */
   279   virtual int Send (Ptr<Packet> p, uint32_t flags) = 0;
   280 
   281   /**
   282    * \brief Send data to a specified peer.
   283    *
   284    * This method has similar semantics to Send () but subclasses may
   285    * want to provide checks on socket state, so the implementation is
   286    * pushed to subclasses.
   287    *
   288    * \param p packet to send
   289    * \param flags Socket control flags
   290    * \param toAddress IP Address of remote host
   291    * \returns -1 in case of error or the number of bytes copied in the 
   292    *          internal buffer and accepted for transmission.
   293    */
   294   virtual int SendTo (Ptr<Packet> p, uint32_t flags, 
   295     const Address &toAddress) = 0;
   296 
   297   /**
   298    * Return number of bytes which can be returned from one or 
   299    * multiple calls to Recv.
   300    * Must be possible to call this method from the Recv callback.
   301    */
   302   virtual uint32_t GetRxAvailable (void) const = 0;
   303 
   304   /**
   305    * \brief Read data from the socket
   306    *
   307    * This function matches closely in semantics to the recv() function
   308    * call in the standard C library (libc):
   309    *   ssize_t recv (int s, void *buf, size_t len, int flags);
   310    * except that the receive I/O is asynchronous.  This is the
   311    * primary Recv method at this low-level API and must be implemented 
   312    * by subclasses.
   313    * 
   314    * This method is normally used only on a connected socket.
   315    * In a typical blocking sockets model, this call would block until
   316    * at least one byte is returned or the connection closes.  
   317    * In ns-3 at this API, the call returns immediately in such a case
   318    * and returns 0 if nothing is available to be read.
   319    * However, an application can set a callback, ns3::SetRecvCallback,
   320    * to be notified of data being available to be read
   321    * (when it conceptually unblocks); this is an asynchronous
   322    * I/O model for recv().
   323    * 
   324    * This variant of Recv() uses class ns3::Packet to encapsulate
   325    * data, rather than providing a raw pointer and length field.  
   326    * This allows an ns-3 application to attach tags if desired (such
   327    * as a flow ID) and may allow the simulator to avoid some data
   328    * copies.  Despite the appearance of receiving Packets on a stream
   329    * socket, just think of it as a fancy byte buffer with streaming
   330    * semantics.    
   331    *
   332    * The semantics depend on the type of socket.  For a datagram socket,
   333    * each Recv() returns the data from at most one Send(), and order
   334    * is not necessarily preserved.  For a stream socket, the bytes
   335    * are delivered in order, and on-the-wire packet boundaries are
   336    * not preserved.  
   337    * 
   338    * The flags argument is formed by or'ing one or more of the values:     
   339    *        MSG_OOB             process out-of-band data
   340    *        MSG_PEEK            peek at incoming message
   341    * None of these flags are supported for now.
   342    *
   343    * Some variants of Recv() are supported as additional API,
   344    * including RecvFrom(), overloaded Recv() without arguments,
   345    * and variants that use raw character buffers.
   346    *
   347    * \param maxSize reader will accept packet up to maxSize
   348    * \param flags Socket control flags
   349    * \returns Ptr<Packet> of the next in-sequence packet.  Returns
   350    * 0 if the socket cannot return a next in-sequence packet conforming
   351    * to the maxSize and flags.
   352    *
   353    * \see SetRecvCallback
   354    */
   355   virtual Ptr<Packet> Recv (uint32_t maxSize, uint32_t flags) = 0;
   356 
   357   /**
   358    * \brief Read a single packet from the socket and retrieve the sender 
   359    * address.
   360    *
   361    * Calls Recv(maxSize, flags) with maxSize
   362    * implicitly set to maximum sized integer, and flags set to zero.
   363    *
   364    * This method has similar semantics to Recv () but subclasses may   
   365    * want to provide checks on socket state, so the implementation is   
   366    * pushed to subclasses.
   367    *
   368    * \param maxSize reader will accept packet up to maxSize
   369    * \param flags Socket control flags
   370    * \param fromAddress output parameter that will return the
   371    * address of the sender of the received packet, if any.  Remains
   372    * untouched if no packet is received.
   373    * \returns Ptr<Packet> of the next in-sequence packet.  Returns
   374    * 0 if the socket cannot return a next in-sequence packet.
   375    */
   376   virtual Ptr<Packet> RecvFrom (uint32_t maxSize, uint32_t flags,  
   377     Address &fromAddress) = 0;
   378 
   379   /////////////////////////////////////////////////////////////////////
   380   //   The remainder of these public methods are overloaded methods  //
   381   //   or variants of Send() and Recv(), and they are non-virtual    //
   382   /////////////////////////////////////////////////////////////////////
   383  
   384   /**
   385    * \brief Send data (or dummy data) to the remote host
   386    * 
   387    * Overloaded version of Send(..., flags) with flags set to zero.
   388    *
   389    * \param p ns3::Packet to send
   390    * \returns the number of bytes accepted for transmission if no error
   391    *          occurs, and -1 otherwise.
   392    */
   393   int Send (Ptr<Packet> p);
   394 
   395   /**
   396    * \brief Send data (or dummy data) to the remote host
   397    * 
   398    * This method is provided so as to have an API which is closer in 
   399    * appearance to that of real network or BSD sockets.  
   400    *
   401    * \param buf A pointer to a raw byte buffer of some data to send.  If 
   402    * this buffer is 0, we send dummy data whose size is specified by the 
   403    * second parameter
   404    * \param size the number of bytes to copy from the buffer
   405    * \param flags Socket control flags
   406    */
   407   int Send (const uint8_t* buf, uint32_t size, uint32_t flags);
   408   
   409 
   410   /**
   411    * \brief Send data to a specified peer.
   412    *
   413    * This method is provided so as to have an API which is closer in 
   414    * appearance to that of real network or BSD sockets.  
   415    *
   416    * \param buf A pointer to a raw byte buffer of some data to send.  
   417    * If this is 0, we send dummy data whose size is specified by the 
   418    * third parameter
   419    * \param size the number of bytes to copy from the buffer
   420    * \param flags Socket control flags
   421    * \param address IP Address of remote host
   422    * \returns -1 in case of error or the number of bytes copied in the 
   423    *          internal buffer and accepted for transmission.
   424    *
   425    */
   426   int SendTo (const uint8_t* buf, uint32_t size, uint32_t flags, 
   427               const Address &address); 
   428 
   429   /**
   430    * \brief Read a single packet from the socket
   431    *
   432    * Overloaded version of Recv(maxSize, flags) with maxSize
   433    * implicitly set to maximum sized integer, and flags set to zero.
   434    *
   435    * \returns Ptr<Packet> of the next in-sequence packet.  Returns
   436    * 0 if the socket cannot return a next in-sequence packet.
   437    */
   438    Ptr<Packet> Recv (void);
   439 
   440   /**
   441    * \brief Recv data (or dummy data) from the remote host
   442    *
   443    * This method is provided so as to have an API which is closer in 
   444    * appearance to that of real network or BSD sockets.  
   445    * 
   446    * If the underlying packet was carring null (fake) data, this buffer
   447    * will be zeroed up to the length specified by the return value.
   448    *
   449    * \param buf A pointer to a raw byte buffer to write the data to. 
   450    * \param size Number of bytes (at most) to copy to buf
   451    * \param flags any flags to pass to the socket
   452    * \returns number of bytes copied into buf
   453    */
   454   int Recv (uint8_t* buf, uint32_t size, uint32_t flags);
   455 
   456   /**
   457    * \brief Read a single packet from the socket and retrieve the sender 
   458    * address.
   459    *
   460    * Calls RecvFrom (maxSize, flags, fromAddress) with maxSize
   461    * implicitly set to maximum sized integer, and flags set to zero.
   462    *
   463    * \param fromAddress output parameter that will return the
   464    * address of the sender of the received packet, if any.  Remains
   465    * untouched if no packet is received.
   466    * \returns Ptr<Packet> of the next in-sequence packet.  Returns
   467    * 0 if the socket cannot return a next in-sequence packet.
   468    */
   469   Ptr<Packet> RecvFrom (Address &fromAddress);
   470 
   471   /**
   472    * \brief Read a single packet from the socket and retrieve the sender
   473    * address.
   474    *
   475    * This method is provided so as to have an API which is closer in 
   476    * appearance to that of real network or BSD sockets.  
   477    * 
   478    * \param buf A pointer to a raw byte buffer to write the data to. 
   479    * If the underlying packet was carring null (fake) data, this buffer
   480    * will be zeroed up to the length specified by the return value.
   481    * \param size Number of bytes (at most) to copy to buf
   482    * \param flags any flags to pass to the socket
   483    * \param fromAddress output parameter that will return the
   484    * address of the sender of the received packet, if any.  Remains
   485    * untouched if no packet is received.
   486    * \returns number of bytes copied into buf
   487    */
   488   int RecvFrom (uint8_t* buf, uint32_t size, uint32_t flags,
   489                 Address &fromAddress);
   490     /**
   491    * \returns the address name  this socket is associated with.
   492    */
   493   virtual int GetSockName (Address &address) const = 0; 
   494  
   495 protected:
   496   void NotifyConnectionSucceeded (void);
   497   void NotifyConnectionFailed (void);
   498   bool NotifyConnectionRequest (const Address &from);
   499   void NotifyNewConnectionCreated (Ptr<Socket> socket, const Address &from);
   500   void NotifyDataSent (uint32_t size);
   501   void NotifySend (uint32_t spaceAvailable);
   502   void NotifyDataRecv (void);
   503   virtual void DoDispose (void);
   504 private:
   505   Callback<void, Ptr<Socket> >   m_connectionSucceeded;
   506   Callback<void, Ptr<Socket> >   m_connectionFailed;
   507   Callback<bool, Ptr<Socket>, const Address &>   m_connectionRequest;
   508   Callback<void, Ptr<Socket>, const Address&>    m_newConnectionCreated;
   509   Callback<void, Ptr<Socket>, uint32_t>          m_dataSent;
   510   Callback<void, Ptr<Socket>, uint32_t >         m_sendCb;
   511   Callback<void, Ptr<Socket> > m_receivedData;
   512 
   513 };
   514 
   515 /**
   516  * \brief This class implements a tag that carries an address
   517  * of a packet across the socket interface.
   518  */
   519 class SocketAddressTag : public Tag
   520 {
   521 public:
   522   SocketAddressTag ();
   523   void SetAddress (Address addr);
   524   Address GetAddress (void) const;
   525 
   526   static TypeId GetTypeId (void);  
   527   virtual TypeId GetInstanceTypeId (void) const;
   528   virtual uint32_t GetSerializedSize (void) const;
   529   virtual void Serialize (TagBuffer i) const;
   530   virtual void Deserialize (TagBuffer i);
   531   virtual void Print (std::ostream &os) const;
   532 
   533 private:
   534   Address m_address;
   535 };
   536 
   537 /**
   538  * \brief This class implements a tag that carries the socket-specific
   539  * TTL of a packet to the IP layer
   540  */
   541 class SocketIpTtlTag : public Tag
   542 {
   543 public:
   544   SocketIpTtlTag ();
   545   void SetTtl (uint8_t ttl);
   546   uint8_t GetTtl (void) const;
   547 
   548   static TypeId GetTypeId (void);  
   549   virtual TypeId GetInstanceTypeId (void) const;
   550   virtual uint32_t GetSerializedSize (void) const;
   551   virtual void Serialize (TagBuffer i) const;
   552   virtual void Deserialize (TagBuffer i);
   553   virtual void Print (std::ostream &os) const;
   554 
   555 private:
   556   uint8_t m_ttl;
   557 };
   558 
   559 
   560 /**
   561  * \brief indicated whether packets should be sent out with
   562  * the DF flag set.
   563  */
   564 class SocketSetDontFragmentTag : public Tag
   565 {
   566 public:
   567   SocketSetDontFragmentTag ();
   568   void Enable (void);
   569   void Disable (void);
   570   bool IsEnabled (void) const;
   571 
   572   static TypeId GetTypeId (void);  
   573   virtual TypeId GetInstanceTypeId (void) const;
   574   virtual uint32_t GetSerializedSize (void) const;
   575   virtual void Serialize (TagBuffer i) const;
   576   virtual void Deserialize (TagBuffer i);
   577   virtual void Print (std::ostream &os) const;
   578 private:
   579   bool m_dontFragment;
   580 };
   581 
   582 } //namespace ns3
   583 
   584 #endif /* SOCKET_H */
   585 
   586