1 /* $Id: pipe.cpp,v 1.5 2005-11-10 23:10:42 adam Exp $
2 Copyright (c) 2005, Index Data.
16 #include <netinet/in.h>
18 #include <arpa/inet.h>
19 #include <netinet/tcp.h>
25 #include <sys/socket.h>
28 #include <sys/select.h>
31 #include <boost/thread/thread.hpp>
32 #include <boost/thread/mutex.hpp>
33 #include <boost/thread/condition.hpp>
39 #include <yaz++/socket-observer.h>
45 class Pipe::Rep : public boost::noncopyable {
57 void Pipe::Rep::close(int &fd)
71 m_fd[0] = m_fd[1] = -1;
75 bool Pipe::Rep::nonblock(int s)
78 unsigned long tru = 1;
79 if (ioctlsocket(s, FIONBIO, &tru) < 0)
82 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
85 signal (SIGPIPE, SIG_IGN);
91 Pipe::Pipe(int port_to_use) : m_p(new Rep)
95 WORD wVersionRequested = MAKEWORD(2, 0);
96 if (WSAStartup( wVersionRequested, &wsaData ))
97 throw Pipe::Error("WSAStartup failed");
101 // create server socket
102 m_p->m_socket = socket(AF_INET, SOCK_STREAM, 0);
103 if (m_p->m_socket < 0)
104 throw Pipe::Error("could not create socket");
106 unsigned long one = 1;
107 if (setsockopt(m_p->m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)
108 &one, sizeof(one)) < 0)
109 throw Pipe::Error("setsockopt error");
111 // bind server socket
112 struct sockaddr_in add;
113 add.sin_family = AF_INET;
114 add.sin_port = htons(port_to_use);
115 add.sin_addr.s_addr = INADDR_ANY;
116 struct sockaddr *addr = ( struct sockaddr *) &add;
118 if (bind(m_p->m_socket, addr, sizeof(struct sockaddr_in)))
119 throw Pipe::Error("could not bind on socket");
121 if (listen(m_p->m_socket, 3) < 0)
122 throw Pipe::Error("could not listen on socket");
126 tmpadd = (unsigned) inet_addr("127.0.0.1");
128 memcpy(&add.sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
130 throw Pipe::Error("inet_addr failed");
132 m_p->m_fd[1] = socket(AF_INET, SOCK_STREAM, 0);
133 if (m_p->m_fd[1] < 0)
134 throw Pipe::Error("could not create socket");
136 m_p->nonblock(m_p->m_fd[1]);
138 if (connect(m_p->m_fd[1], addr, sizeof(*addr)) < 0)
141 if (WSAGetLastError() != WSAEWOULDBLOCK)
142 throw Pipe::Error("could not connect to socket");
144 if (errno != EINPROGRESS)
145 throw Pipe::Error("could not connect to socket");
150 struct sockaddr caddr;
152 int caddr_len = sizeof(caddr);
154 socklen_t caddr_len = sizeof(caddr);
156 m_p->m_fd[0] = accept(m_p->m_socket, &caddr, &caddr_len);
157 if (m_p->m_fd[0] < 0)
158 throw Pipe::Error("could not accept on socket");
163 FD_SET(m_p->m_fd[1], &write_set);
164 int r = select(m_p->m_fd[1]+1, 0, &write_set, 0, 0);
166 throw Pipe::Error("could not complete connect");
168 m_p->close(m_p->m_socket);
180 m_p->close(m_p->m_fd[0]);
181 m_p->close(m_p->m_fd[1]);
182 m_p->close(m_p->m_socket);
188 int &Pipe::read_fd() const
193 int &Pipe::write_fd() const
201 * indent-tabs-mode: nil
202 * c-file-style: "stroustrup"
204 * vim: shiftwidth=4 tabstop=8 expandtab