2 * Copyright 2001-2007 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 * Berkeley Socket-based ListenerService implementation
24 #include "exceptions.h"
25 #include "remoting/impl/SocketListener.h"
30 #include <shibsp/SPConfig.h>
31 #include <xmltooling/util/NDC.h>
34 # include <netinet/in.h>
37 using namespace shibsp;
38 using namespace xmltooling;
40 using xercesc::DOMElement;
44 // Manages the pool of connections
48 SocketPool(Category& log, const SocketListener* listener)
49 : m_log(log), m_listener(listener), m_lock(Mutex::create()) {}
51 SocketListener::ShibSocket get();
52 void put(SocketListener::ShibSocket s);
55 SocketListener::ShibSocket connect();
58 const SocketListener* m_listener;
59 auto_ptr<Mutex> m_lock;
60 stack<SocketListener::ShibSocket> m_pool;
63 // Worker threads in server
66 ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id);
72 SocketListener::ShibSocket m_sock;
74 SocketListener* m_listener;
80 SocketListener::ShibSocket SocketPool::connect()
86 m_log.debug("trying to connect to listener");
88 SocketListener::ShibSocket sock;
89 if (!m_listener->create(sock)) {
90 m_log.error("cannot create socket");
91 throw ListenerException("Cannot create socket");
94 bool connected = false;
97 for (int i = num_tries-1; i >= 0; i--) {
98 if (m_listener->connect(sock)) {
103 m_log.warn("cannot connect socket (%u)...%s", sock, (i > 0 ? "retrying" : ""));
107 Sleep(2000*(num_tries-i));
109 sleep(2*(num_tries-i));
115 m_log.crit("socket server unavailable, failing");
116 m_listener->close(sock);
117 throw ListenerException("Cannot connect to shibd process, a site adminstrator should be notified.");
120 m_log.debug("socket (%u) connected successfully", sock);
124 SocketPool::~SocketPool()
126 while (!m_pool.empty()) {
128 closesocket(m_pool.top());
130 ::close(m_pool.top());
136 SocketListener::ShibSocket SocketPool::get()
139 if (m_pool.empty()) {
143 SocketListener::ShibSocket ret=m_pool.top();
149 void SocketPool::put(SocketListener::ShibSocket s)
156 SocketListener::SocketListener(const DOMElement* e) : log(&Category::getInstance(SHIBSP_LOGCAT".Listener")),
157 m_socketpool(NULL), m_shutdown(NULL), m_child_lock(NULL), m_child_wait(NULL), m_socket((ShibSocket)0)
160 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
161 m_socketpool=new SocketPool(*log,this);
164 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
165 m_child_lock = Mutex::create();
166 m_child_wait = CondWait::create();
170 SocketListener::~SocketListener()
177 bool SocketListener::run(bool* shutdown)
182 log->info("listener service starting");
184 // Save flag to monitor for shutdown request.
186 unsigned long count = 0;
188 if (!create(m_socket)) {
189 log->crit("failed to create socket");
192 if (!bind(m_socket,true)) {
193 this->close(m_socket);
194 log->crit("failed to bind to socket.");
198 while (!*m_shutdown) {
201 FD_SET(m_socket, &readfds);
202 struct timeval tv = { 0, 0 };
205 switch (select(m_socket + 1, &readfds, 0, 0, &tv)) {
211 if (errno == EINTR) continue;
213 log->error("select() on main listener socket failed");
221 // Accept the connection.
222 SocketListener::ShibSocket newsock;
223 if (!accept(m_socket, newsock))
224 log->crit("failed to accept incoming socket connection");
226 // We throw away the result because the children manage themselves...
228 new ServerThread(newsock,this,++count);
231 log->crit("error starting new server thread to service incoming request");
236 log->info("listener service shutting down");
238 // Wait for all children to exit.
239 m_child_lock->lock();
240 while (!m_children.empty())
241 m_child_wait->wait(m_child_lock);
242 m_child_lock->unlock();
244 this->close(m_socket);
245 m_socket=(ShibSocket)0;
249 DDF SocketListener::send(const DDF& in)
255 log->debug("sending message (%s)", in.name() ? in.name() : "unnamed");
257 // Serialize data for transmission.
260 string ostr(os.str());
262 // Loop on the RPC in case we lost contact the first time through
269 SocketListener::ShibSocket sock;
271 sock = m_socketpool->get();
273 int outlen = ostr.length();
275 if (send(sock,(char*)&len,sizeof(len)) != sizeof(len) || send(sock,ostr.c_str(),outlen) != outlen) {
281 throw ListenerException("Failure sending remoted message ($1).", params(1,in.name()));
289 log->debug("send completed, reading response message");
292 if (recv(sock,(char*)&len,sizeof(len)) != sizeof(len)) {
293 log->error("error reading size of output message");
295 throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
302 while (len && (size_read = recv(sock, buf, sizeof(buf))) > 0) {
303 is.write(buf, size_read);
308 log->error("error reading output message from socket");
310 throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
313 m_socketpool->put(sock);
319 // Check for exception to unmarshall and throw, otherwise return.
320 if (out.isstring() && out.name() && !strcmp(out.name(),"exception")) {
321 // Reconstitute exception object.
322 DDFJanitor jout(out);
323 XMLToolingException* except=NULL;
325 except=XMLToolingException::fromString(out.string());
326 log->error("remoted message returned an error: %s", except->what());
328 catch (XMLToolingException& e) {
329 log->error("caught XMLToolingException while building the XMLToolingException: %s", e.what());
330 log->error("XML was: %s", out.string());
331 throw ListenerException("Remote call failed with an unparsable exception.");
334 auto_ptr<XMLToolingException> wrapper(except);
341 bool SocketListener::log_error() const
344 int rc=WSAGetLastError();
348 #ifdef HAVE_STRERROR_R
350 memset(buf,0,sizeof(buf));
351 strerror_r(rc,buf,sizeof(buf));
352 log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
354 const char* buf=strerror(rc);
355 log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
360 // actual function run in listener on server threads
361 void* server_thread_fn(void* arg)
363 ServerThread* child = (ServerThread*)arg;
366 // First, let's block all signals
367 Thread::mask_all_signals();
370 // Run the child until it exits.
373 // Now we can clean up and exit the thread.
378 ServerThread::ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id)
379 : m_sock(s), m_child(NULL), m_listener(listener)
383 buf << "[" << id << "]";
386 // Create the child thread
387 m_child = Thread::create(server_thread_fn, (void*)this);
391 ServerThread::~ServerThread()
393 // Then lock the children map, remove this socket/thread, signal waiters, and return
394 m_listener->m_child_lock->lock();
395 m_listener->m_children.erase(m_sock);
396 m_listener->m_child_lock->unlock();
397 m_listener->m_child_wait->signal();
402 void ServerThread::run()
406 // Before starting up, make sure we fully "own" this socket.
407 m_listener->m_child_lock->lock();
408 while (m_listener->m_children.find(m_sock)!=m_listener->m_children.end())
409 m_listener->m_child_wait->wait(m_listener->m_child_lock);
410 m_listener->m_children[m_sock] = m_child;
411 m_listener->m_child_lock->unlock();
414 struct timeval tv = { 0, 0 };
416 while(!*(m_listener->m_shutdown)) {
418 FD_SET(m_sock, &readfds);
421 switch (select(m_sock+1, &readfds, 0, 0, &tv)) {
427 if (errno == EINTR) continue;
428 m_listener->log_error();
429 m_listener->log->error("select() on incoming request socket (%u) returned error", m_sock);
437 m_listener->log_error();
438 m_listener->log->error("I/O failure processing request on socket (%u)", m_sock);
439 m_listener->close(m_sock);
446 bool ServerThread::job()
448 Category& log = Category::getInstance("shibd.Listener");
450 bool incomingError = true; // set false once incoming message is received
460 if (m_listener->recv(m_sock,(char*)&len,sizeof(len)) != sizeof(len)) {
461 log.error("error reading size of input message");
468 while (len && (size_read = m_listener->recv(m_sock, m_buf, sizeof(m_buf))) > 0) {
469 is.write(m_buf, size_read);
474 log.error("error reading input message from socket");
478 // Unmarshall the message.
483 log.debug("dispatching message (%s)", in.name() ? in.name() : "unnamed");
485 incomingError = false;
487 // Dispatch the message.
488 m_listener->receive(in, sink);
490 catch (XMLToolingException& e) {
492 log.error("error processing incoming message: %s", e.what());
493 DDF out=DDF("exception").string(e.toString().c_str());
494 DDFJanitor jout(out);
497 catch (exception& e) {
499 log.error("error processing incoming message: %s", e.what());
500 ListenerException ex(e.what());
501 DDF out=DDF("exception").string(ex.toString().c_str());
502 DDFJanitor jout(out);
508 log.error("unexpected error processing incoming message");
509 ListenerException ex("An unexpected error occurred while processing an incoming message.");
510 DDF out=DDF("exception").string(ex.toString().c_str());
511 DDFJanitor jout(out);
516 // Return whatever's available.
517 string response(sink.str());
518 int outlen = response.length();
520 if (m_listener->send(m_sock,(char*)&len,sizeof(len)) != sizeof(len)) {
521 log.error("error sending output message size");
524 if (m_listener->send(m_sock,response.c_str(),outlen) != outlen) {
525 log.error("error sending output message");