1 /* $Id: pipe.cpp,v 1.8 2006-06-10 14:29:12 adam Exp $
2 Copyright (c) 2005-2006, Index Data.
4 See the LICENSE file for details
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 <yazpp/socket-observer.h>
44 namespace mp = metaproxy_1;
46 namespace metaproxy_1 {
47 class Pipe::Rep : public boost::noncopyable {
59 void Pipe::Rep::close(int &fd)
73 m_fd[0] = m_fd[1] = -1;
77 bool Pipe::Rep::nonblock(int s)
80 unsigned long tru = 1;
81 if (ioctlsocket(s, FIONBIO, &tru) < 0)
84 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
87 signal (SIGPIPE, SIG_IGN);
93 Pipe::Pipe(int port_to_use) : m_p(new Rep)
97 WORD wVersionRequested = MAKEWORD(2, 0);
98 if (WSAStartup( wVersionRequested, &wsaData ))
99 throw Pipe::Error("WSAStartup failed");
103 // create server socket
104 m_p->m_socket = socket(AF_INET, SOCK_STREAM, 0);
105 if (m_p->m_socket < 0)
106 throw Pipe::Error("could not create socket");
108 unsigned long one = 1;
109 if (setsockopt(m_p->m_socket, SOL_SOCKET, SO_REUSEADDR, (char*)
110 &one, sizeof(one)) < 0)
111 throw Pipe::Error("setsockopt error");
113 // bind server socket
114 struct sockaddr_in add;
115 add.sin_family = AF_INET;
116 add.sin_port = htons(port_to_use);
117 add.sin_addr.s_addr = INADDR_ANY;
118 struct sockaddr *addr = ( struct sockaddr *) &add;
120 if (bind(m_p->m_socket, addr, sizeof(struct sockaddr_in)))
121 throw Pipe::Error("could not bind on socket");
123 if (listen(m_p->m_socket, 3) < 0)
124 throw Pipe::Error("could not listen on socket");
128 tmpadd = (unsigned) inet_addr("127.0.0.1");
130 memcpy(&add.sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
132 throw Pipe::Error("inet_addr failed");
134 m_p->m_fd[1] = socket(AF_INET, SOCK_STREAM, 0);
135 if (m_p->m_fd[1] < 0)
136 throw Pipe::Error("could not create socket");
138 m_p->nonblock(m_p->m_fd[1]);
140 if (connect(m_p->m_fd[1], addr, sizeof(*addr)) < 0)
143 if (WSAGetLastError() != WSAEWOULDBLOCK)
144 throw Pipe::Error("could not connect to socket");
146 if (errno != EINPROGRESS)
147 throw Pipe::Error("could not connect to socket");
152 struct sockaddr caddr;
154 int caddr_len = sizeof(caddr);
156 socklen_t caddr_len = sizeof(caddr);
158 m_p->m_fd[0] = accept(m_p->m_socket, &caddr, &caddr_len);
159 if (m_p->m_fd[0] < 0)
160 throw Pipe::Error("could not accept on socket");
165 FD_SET(m_p->m_fd[1], &write_set);
166 int r = select(m_p->m_fd[1]+1, 0, &write_set, 0, 0);
168 throw Pipe::Error("could not complete connect");
170 m_p->close(m_p->m_socket);
182 m_p->close(m_p->m_fd[0]);
183 m_p->close(m_p->m_fd[1]);
184 m_p->close(m_p->m_socket);
190 int &Pipe::read_fd() const
195 int &Pipe::write_fd() const
203 * indent-tabs-mode: nil
204 * c-file-style: "stroustrup"
206 * vim: shiftwidth=4 tabstop=8 expandtab