// -*- c++ -*- //------------------------------------------------------------------------------ // Socket.h //------------------------------------------------------------------------------ // Copyright (C) 1997-2002,2005 Vladislav Grinchenko // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. //------------------------------------------------------------------------------ // // This class is a direct derivative from my Unix Network Programming // class work on generalizing object-oriented network interfaces. // //------------------------------------------------------------------------------ // Created: 03/22/1999 //------------------------------------------------------------------------------ #ifndef SOCKET_H #define SOCKET_H #include #include #include // for INT_MAX #include // for EOF #include #include #include // for fcntl(2) #ifdef linux # include // ioctl(2) #endif #ifdef sun // ioctl(2) # include # include # include #endif #include "assa/Address.h" /** @def BYTES_LEFT_IN_SOCKBUF(s) BYTES_LEFT_IN_SOCKBUF macro returns number of unprocessed bytes left in ASSA's double-buffer from EventHandler::handle_read() callback. Unless for a valid reason, this macro should always be called. @param s Reference to ASSA::Socket */ #define BYTES_LEFT_IN_SOCKBUF(s) ((s).eof () ? -1 : (s).in_avail ()) /** @def BYTES_LEFT_IN_SIN BYTES_LEFT_IN_SIN macro returns number of unprocessed bytes left in cin internal buffer. */ #define BYTES_LEFT_IN_SIN (cin.eof () ? -1 : cin.rdbuf ()->in_avail ()) namespace ASSA { class Streambuf; // Forward declaration /** @file Socket.h * * Abstraction of socket data type. This will be a subclass of instream */ class Socket { public: /// Size of bytes of a kernel page static const int PGSIZE; /** @enum io_state_t * State bits: goodbit, eofbit, failbit, badbit. Meaning to * these is explained in class' documentation. */ enum io_state_t { goodbit = 0, /**< indicates that socket is ready for use */ eofbit = 1, /**< indicates that an input operation reached the end of an input sequence */ failbit = 2, /**< indicates that an input operation failed to read the expected characters, or that an output operation failed to generate the desired characters. */ badbit = 4 /**< indicates a loss of integrity in an input or output sequence (such as an irrecoverable read error from a file) */ }; typedef int iostate; typedef unsigned char IOState; /** @enum opt_t * Socket options. */ enum opt_t { reuseaddr, /**< Allow local address reuse. */ rcvlowat, /**< The receiver low-water mark is the amount of data that must be in the socket receive buffer for select(3) to return "readable". It defaults to 1 for a TCP and UDP socket (NOTE: Posix.1g does not require support for this option). */ sndlowat, /**< The send low-water mark si the amount of available space that must exist in the socket send buffer for select to return "writable". This low-water mark normally defaults to 2048 for TCP socket. UDP socket is always writable (NOTE: Posix.1g does not require support for this option) */ nonblocking /**< Set Socket to a non-blocking mode (O_RDWR|O_NONBLOCK). The default setup for a socket is BLOCKING (O_RDWR), Blocking implies being suspended while waiting for data to arrive on read. On write, it means that there is no room to send all data out and the process is being suspended until more room in the output buffer becomes available. Use nonblocking option to set the socket to non-blocking mode. For input operations, if an operation cannot be satisfied (at least 1 byte of data for a TCP socket or a complete datagram for a UDP socket), return is made immediately with an error of EWOULDBLOCK. For output operations, if there is no room at all in the socket send buffer, return is made immediately with an error of EWOULDBLOCK. If, however, there is some room in the socket send buffer, the return value will be the number of bytes that the kernel was able to copy into the buffer (This is called a short count). NOTE: To go back to blocking mode, clear nonblocking with turnOptionOff(). */ }; /// Constructor Socket(); /// Destructor virtual ~Socket(); /// Open socket virtual bool open(const int domain_) =0; /// Close socket virtual bool close() =0; /** Make a connection. @param address_ address of the server to connect to */ virtual bool connect (const Address& address_); /** Server binds listening socket to its local well-known port. @param my_address_ address to bind to @return true if success, false otherwise */ virtual bool bind (const Address& my_address_) =0; /** Write specified number of bytes to the socket @param buf_ packet to send @param size_ size of the packet */ virtual int write (const char* buf_, const u_int size_); /** Return number of bytes available in socket receive buffer. */ int getBytesAvail (void) const; /** Read expected number of bytes from the socket. @param buf_ buffer to save received packet to @param size_ size of the packet */ virtual int read (char* buf_, const u_int size_); /** Extracts bytes and discards them. With no arguments, read and discard until eof is encountered. Bytes are extracted in the following manner:

n_ delim_ Action
1 EOF Read and discard 1 byte
k EOF Read and discard at most k bytes
INT_MAX EOF Read and discard till eof is reached
INT_MAX 'c' Read and discard till either 'c' or eof is found
k 'c' Read and discard at most k bytes, but stop if 'c' is found

@param n_ number of bytes to ignore (default=INT_MAX) @param delim_ delimiter to search for (default=EOF) @return number of bytes discarded */ int ignore (int n_ = INT_MAX, int delim_ = EOF); /// Get file descriptor virtual handler_t getHandler() const = 0; /// Get socket domain virtual const int getDomain() const = 0; /** Return a pointer to the Streambuf associated with the stream. This is part of the construction of a stream, and the buffer class object is not normally changed. This function may be used to get at Streambuf functionality directly, given a Socket object. Default behavior is to return NULL. @return NULL */ virtual Streambuf* rdbuf () { return 0; } /** Virtual function that sets new socket buffer and returns the old one. Default behavior is to return NULL. @return Old Socketbuf object. */ virtual Streambuf* rdbuf (Streambuf* /*sb_*/) { return 0; } /** This function returns the number of characters immediately available in the get area of the underlying Socketbuf buffer without making a system call if Socket is doing buffering I/O. It is certain that returned number of characters may be fetched without error, and without accessing any external device. */ virtual int in_avail () const = 0; /** This function simply calls the public "synchronizing" function rdbuf()->pubsync() (assuming the associated streambuf object is present). Typically, such an operation flushes an output stream to the associated external pipe. */ virtual Socket& flush (); /** Enable socket option @param opt_ option name @return true on success; false if error */ bool turnOptionOn (opt_t opt_); /** Disable socket option @param opt_ option name @return true on success; false if error */ bool turnOptionOff (opt_t opt_); /** Set socket option to value required. @param opt_ option name @param arg_ value to set (for binary: 0 - disable, 1 - enable). @return true on success_; false if error */ bool setOption (opt_t opt_, int arg_); /** Get current value of a socket option. @param opt_ option name @return option value on success (for binary: 0 - disable, 1 - enabled); -1 if error */ int getOption (opt_t opt_) const; /// Convertion to void* (for testing where bool is required) operator void* () const; /// Alias to fail() bool operator! () const; /** Retrieve state of the socket @return control state of the socket */ iostate rdstate () const { return m_state; } /// Clear the socket state. Closed socket remains in bad state. void clear (iostate state_ = Socket::goodbit); /** Set socket state to flag_ by adding flag_ to the existing state. * @param flag_ new state */ void setstate (iostate flag_); /** Indicates no error on the socket. @return true if goodbit is set, false otherwise */ bool good () const { return m_state == 0; } /** An earlier extraction operation has encountered the end of file of the input stream (peer closed its socket). @return true if peer closed the socket; false otherwise */ bool eof () const { return m_state & Socket::eofbit; } /** Indicates that earlier extraction opeartion has failed to match the required pattern of input. Socket should be closed at this point by the owner. @return true if failbit or badbit is set, false otherwise */ bool fail () const { return m_state & (Socket::failbit | Socket::badbit); } /** Socket fd == -1 or read/write error occured or some loss of integrity on assosiated stream buffer. @return true if badbit is set, false otherwise */ bool bad () const { return m_state & Socket::badbit; } /// Write state bits of the socket to the log file. void dumpState () const; /// Give the true length of the XDR-encoded STL string. static size_t xdr_length (const std::string& s_) { return (4 + s_.length () + s_.length () % 4); } /// Input of built-in char type. The value will be XDR-decoded. Socket& operator>> (char& c); /// Input of built-in u_char type. The value will be XDR-decoded. Socket& operator>> (unsigned char& c_) { return operator>>((char&) c_); } /// Input of built-in signed char type. The value will be XDR-decoded. Socket& operator>> (signed char& c_) { return operator>>((char&) c_); } /// Input of STL string type. The string content will be XDR-decoded. Socket& operator>> (std::string& s_); /// Input of built-in short type. The value will be XDR-decoded. Socket& operator>> (short& n_); /// Input of built-in u_short type. The value will be XDR-decoded. Socket& operator>> (unsigned short& n_); /// Input of built-in integer type. The value will be XDR-decoded. Socket& operator>> (int& n_); /// Input of built-in u_int type. The value will be XDR-decoded. Socket& operator>> (unsigned int& n_); /// Input of built-in long type. The value will be XDR-decoded. Socket& operator>> (long& n_); /// Input of built-in u_long type. The value will be XDR-decoded. Socket& operator>> (unsigned long& n_); /// Input of built-in float type. The value will be XDR-decoded. Socket& operator>> (float& n_); /// Input of built-in double type. The value will be XDR-decoded. Socket& operator>> (double& n_); /// Output of built-in char type. The value will be XDR-encoded. Socket& operator<< (char c); /// Output of built-in u_char type. The value will be XDR-encoded. Socket& operator<< (unsigned char c_) { return (*this) << (char) c_; } /// Output of built-in signed char type. The value will be XDR-encoded. Socket& operator<< (signed char c_) { return (*this) << (char) c_; } /// Output of STL string type. The value will be XDR-encoded. Socket& operator<< (const std::string& s_); /// Output of built-in short type. The value will be XDR-encoded. Socket& operator<< (short n_); /// Output of built-in u_short type. The value will be XDR-encoded. Socket& operator<< (unsigned short n_); /// Output of built-in integer type. The value will be XDR-encoded. Socket& operator<< (int n_); /// Output of built-in u_int type. The value will be XDR-encoded. Socket& operator<< (unsigned int n_); /// Output of built-in long type. The value will be XDR-encoded. Socket& operator<< (long n_); /// Output of built-in u_long type. The value will be XDR-encoded. Socket& operator<< (unsigned long n_); /// Output of built-in float type. The value will be XDR-encoded. Socket& operator<< (float n_); /// Output of built-in double type. The value will be XDR-encoded. Socket& operator<< (double n_); /// Manipulators plug-in operator Socket& operator<< (Socket& (*f) (Socket&)) { return (f (*this)); } /** Determine the endianess of the platform we are on. * * @return true if it is a little-endian host; * false if a big-endian host. */ static bool is_little_endian (); /** Close socket endpoint in a portable way. * Socket is also set to an invalid value. */ static void close_handler (handler_t& socket_) { #if defined (WIN32) closesocket (socket_); #else ::close (socket_); #endif disable_handler (socket_); } /** Decipher flags packed into mask_ used in fcntl() call. */ static string decode_fcntl_flags (long mask_); /*------------------------------------------------------------------ * Protected Members *------------------------------------------------------------------ */ protected: /** Gateway method of setting socket options. @return 0 on success, -1 on error (setsockopt(2) failed) */ int set_option (int level_, int optname_, int val_); /** Gateway method for setting file descriptor options. @return 0 on success, -1 on error (fcntl(2) failed) */ int set_fd_options (long flags_); /** Gateway method for clearing file descriptor options. @return 0 on success, -1 on error (fcntl(2) failed) */ int clear_fd_options (long flags_); protected: /** File descriptor */ handler_t m_fd; // u_int, INVALID_SOCKET=(SOCKET)(~0) /// Socket domain type int m_type; #if defined (WIN32) bool m_nonblocking; // We cannot retrieve the status of the // socket. So, we remember what it was instead. #endif /// Control state of the socket IOState m_state; //------------------------------------------------------------------------------ // Inline functions //------------------------------------------------------------------------------ private: /** The copy constructor and assignment operator are private to prevent copying of Socket objects, since the effect of such copying is not well defined. Usually you want to copy a pointer to the object, or pass a reference to a function. */ Socket (const Socket&); Socket& operator= (const Socket&); }; //------------------------------------------------------------------------------ // Inline functions //------------------------------------------------------------------------------ inline Socket::Socket() : m_fd (BAD_HANDLER), m_type(0), #if defined (WIN32) m_nonblocking (false), #endif m_state(Socket::badbit) { trace_with_mask("Socket::Socket",SOCKTRACE); } inline Socket::~Socket () { trace_with_mask("Socket::~Socket",SOCKTRACE); } inline bool Socket::connect (const Address& /* address_ */) { trace_with_mask("Socket::connect",SOCKTRACE); return false; } inline int Socket::write(const char* /*buf_*/, const u_int /*size_*/) { trace_with_mask("Socket::write",SOCKTRACE); return -1; } inline int Socket::read(char* /*buf_*/, const u_int /*size_*/) { trace_with_mask("Socket::read()",SOCKTRACE); return -1; } inline Socket::operator void*() const { return fail() ? (void *)0 : (void *)(-1); } inline bool Socket::operator!() const { return fail(); } inline void Socket::clear(iostate state_) { m_state = is_valid_handler (m_fd) ? state_ : state_ | Socket::badbit; } inline void Socket::setstate(iostate flag_) { m_state |= flag_; } /** flush manipulator. Flush a stream buffer. */ inline Socket& flush (Socket& os_) { os_.flush (); return (os_); } /** endl manipulator. If you want to insert a newline character ('\n') to terminate a text line, you should favor the manipulator endl. This manipulator inserts a newline character and also flushes the stream buffer. @author Vladislav Grinchenko */ inline Socket& endl (Socket& os_) { char c = '\n'; os_.write (&c, 1); os_.flush (); return (os_); } /** ends manipulator. You can insert a null character (without flushing the output stream) with the manipulator ends. A common use for a Socket object is to mediate output to a stream buffer that constructs an in-memory character sequence. Such a sequence wants a terminating null character. The manipulator ends provides highly visible evidence that the null character is indeed being supplied. @author Vladislav Grinchenko */ inline Socket& ends (Socket& os_) { char c = '\0'; os_.write (&c, 1); return (os_); } } // end namespace ASSA #include "assa/Streambuf.h" #endif // SOCKET_H