/* The software in this package is distributed under the GNU General Public License version 2 (with a special exception described below). A copy of GNU General Public License (GPL) is included in this distribution, in the file COPYING.GPL. As a special exception, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other works to produce a work based on this file, this file does not by itself cause the resulting work to be covered by the GNU General Public License. However the source code for this file must still be made available in accordance with section (3) of the GNU General Public License. This exception does not invalidate any other reasons why a work based on this file might be covered by the GNU General Public License. */ /*************************************************************************** insocketstream.hxx - C++ streambuffer wrapper ------------------- begin : Sun Nov 10 2002 copyright : (C) 2002 by Intra2net AG ***************************************************************************/ #ifndef _INSOCKETSTREAM #define _INSOCKETSTREAM #include #include #include #include #include #include #include #include #include "exception.hxx" // ATTENTION: A lot of mysterious STL bugs occured // with a "real" buffer (buffer larger than 1 byte and up to 100 bytes) // -> Keep it slow and working! class insocketstream : public std::streambuf { protected: char buffer; int sock; public: insocketstream(std::string unixsocket) { sock=socket(AF_UNIX,SOCK_STREAM,0); if (sock == -1) { std::ostringstream os; os << "can't open socket: " << strerror(errno); throw EXCEPTION (insocketstream_error, os.str()); } struct sockaddr_un server_adr; server_adr.sun_family=AF_UNIX; strncpy(server_adr.sun_path,unixsocket.c_str(),sizeof(server_adr.sun_path)); server_adr.sun_path[sizeof(server_adr.sun_path)-1]=0; if(connect(sock,(struct sockaddr *) &server_adr, sizeof(server_adr))) { std::ostringstream os; os << "can't connect to socket: " << strerror(errno); throw EXCEPTION (insocketstream_error, os.str()); } setg (&buffer, &buffer, &buffer); // force underflow } ~insocketstream() { if (sock != -1) { shutdown(sock,SHUT_RDWR); close(sock); } sock = -1; } protected: virtual int_type underflow() { if (gptr() < egptr()) return std::streambuf::traits_type::to_int_type(*gptr()); int nbytes=::read(sock,&buffer,1); if (nbytes==-1) { if (errno == EINTR) return std::streambuf::traits_type::to_int_type(*gptr()); else { std::ostringstream os; os << "error reading form socket: " << strerror(errno); throw EXCEPTION (insocketstream_error, os.str()); } } if (nbytes==0) return EOF; setg (&buffer, &buffer, &buffer+sizeof(char)); return std::streambuf::traits_type::to_int_type(*gptr()); } }; #endif