2 * Copyright 2001-2009 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 "ServiceProvider.h"
26 #include "remoting/impl/SocketListener.h"
31 #include <shibsp/SPConfig.h>
32 #include <xmltooling/util/NDC.h>
35 # include <netinet/in.h>
42 using namespace shibsp;
43 using namespace xmltooling;
45 using xercesc::DOMElement;
49 // Manages the pool of connections
53 SocketPool(Category& log, const SocketListener* listener)
54 : m_log(log), m_listener(listener), m_lock(Mutex::create()) {}
56 SocketListener::ShibSocket get();
57 void put(SocketListener::ShibSocket s);
60 SocketListener::ShibSocket connect();
63 const SocketListener* m_listener;
64 auto_ptr<Mutex> m_lock;
65 stack<SocketListener::ShibSocket> m_pool;
68 // Worker threads in server
71 ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id);
74 int job(); // Return -1 on error, 1 for closed, 0 for success
77 SocketListener::ShibSocket m_sock;
79 SocketListener* m_listener;
85 SocketListener::ShibSocket SocketPool::connect()
91 m_log.debug("trying to connect to listener");
93 SocketListener::ShibSocket sock;
94 if (!m_listener->create(sock)) {
95 m_log.error("cannot create socket");
96 throw ListenerException("Cannot create socket");
99 bool connected = false;
102 for (int i = num_tries-1; i >= 0; i--) {
103 if (m_listener->connect(sock)) {
108 m_log.warn("cannot connect socket (%u)...%s", sock, (i > 0 ? "retrying" : ""));
112 Sleep(2000*(num_tries-i));
114 sleep(2*(num_tries-i));
120 m_log.crit("socket server unavailable, failing");
121 m_listener->close(sock);
122 throw ListenerException("Cannot connect to shibd process, a site adminstrator should be notified.");
125 m_log.debug("socket (%u) connected successfully", sock);
129 SocketPool::~SocketPool()
131 while (!m_pool.empty()) {
133 closesocket(m_pool.top());
135 ::close(m_pool.top());
141 SocketListener::ShibSocket SocketPool::get()
144 if (m_pool.empty()) {
148 SocketListener::ShibSocket ret=m_pool.top();
154 void SocketPool::put(SocketListener::ShibSocket s)
161 SocketListener::SocketListener(const DOMElement* e)
162 : m_catchAll(false), log(&Category::getInstance(SHIBSP_LOGCAT".Listener")), m_socketpool(NULL),
163 m_shutdown(NULL), m_child_lock(NULL), m_child_wait(NULL), m_socket((ShibSocket)0)
166 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
167 m_socketpool=new SocketPool(*log,this);
170 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
171 m_child_lock = Mutex::create();
172 m_child_wait = CondWait::create();
176 SocketListener::~SocketListener()
183 bool SocketListener::init(bool force)
188 log->info("listener service starting");
190 ServiceProvider* sp = SPConfig::getConfig().getServiceProvider();
192 const PropertySet* props = sp->getPropertySet("OutOfProcess");
194 pair<bool,bool> flag = props->getBool("catchAll");
195 m_catchAll = flag.first && flag.second;
199 if (!create(m_socket)) {
200 log->crit("failed to create socket");
203 if (!bind(m_socket, force)) {
204 this->close(m_socket);
205 log->crit("failed to bind to socket.");
212 bool SocketListener::run(bool* shutdown)
217 // Save flag to monitor for shutdown request.
219 unsigned long count = 0;
221 while (!*m_shutdown) {
224 FD_SET(m_socket, &readfds);
225 struct timeval tv = { 0, 0 };
228 switch (select(m_socket + 1, &readfds, 0, 0, &tv)) {
234 if (errno == EINTR) continue;
236 log->error("select() on main listener socket failed");
245 // Accept the connection.
246 SocketListener::ShibSocket newsock;
247 if (!accept(m_socket, newsock)) {
248 log->crit("failed to accept incoming socket connection");
252 // We throw away the result because the children manage themselves...
254 new ServerThread(newsock,this,++count);
256 catch (exception& ex) {
257 log->crit("exception starting new server thread to service incoming request: %s", ex.what());
260 log->crit("unknown error starting new server thread to service incoming request");
267 log->info("listener service shutting down");
269 // Wait for all children to exit.
270 m_child_lock->lock();
271 while (!m_children.empty())
272 m_child_wait->wait(m_child_lock);
273 m_child_lock->unlock();
278 void SocketListener::term()
280 this->close(m_socket);
281 m_socket=(ShibSocket)0;
284 DDF SocketListener::send(const DDF& in)
290 log->debug("sending message (%s)", in.name() ? in.name() : "unnamed");
292 // Serialize data for transmission.
295 string ostr(os.str());
297 // Loop on the RPC in case we lost contact the first time through
304 SocketListener::ShibSocket sock;
306 sock = m_socketpool->get();
308 int outlen = ostr.length();
310 if (send(sock,(char*)&len,sizeof(len)) != sizeof(len) || send(sock,ostr.c_str(),outlen) != outlen) {
316 throw ListenerException("Failure sending remoted message ($1).", params(1,in.name()));
324 log->debug("send completed, reading response message");
327 while (recv(sock,(char*)&len,sizeof(len)) != sizeof(len)) {
328 if (errno == EINTR) continue; // Apparently this happens when a signal interrupts the blocking call.
329 log->error("error reading size of output message");
331 throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
339 size_read = recv(sock, buf, sizeof(buf));
341 is.write(buf, size_read);
344 else if (errno != EINTR) {
350 log->error("error reading output message from socket");
352 throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
355 m_socketpool->put(sock);
361 // Check for exception to unmarshall and throw, otherwise return.
362 if (out.isstring() && out.name() && !strcmp(out.name(),"exception")) {
363 // Reconstitute exception object.
364 DDFJanitor jout(out);
365 XMLToolingException* except=NULL;
367 except=XMLToolingException::fromString(out.string());
368 log->error("remoted message returned an error: %s", except->what());
370 catch (XMLToolingException& e) {
371 log->error("caught XMLToolingException while building the XMLToolingException: %s", e.what());
372 log->error("XML was: %s", out.string());
373 throw ListenerException("Remote call failed with an unparsable exception.");
376 auto_ptr<XMLToolingException> wrapper(except);
383 bool SocketListener::log_error() const
386 int rc=WSAGetLastError();
390 #ifdef HAVE_STRERROR_R
392 memset(buf,0,sizeof(buf));
393 strerror_r(rc,buf,sizeof(buf));
394 log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
396 const char* buf=strerror(rc);
397 log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
402 // actual function run in listener on server threads
403 void* server_thread_fn(void* arg)
405 ServerThread* child = (ServerThread*)arg;
408 // First, let's block all signals
409 Thread::mask_all_signals();
412 // Run the child until it exits.
415 // Now we can clean up and exit the thread.
420 ServerThread::ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id)
421 : m_sock(s), m_child(NULL), m_listener(listener)
425 buf << "[" << id << "]";
428 // Create the child thread
429 m_child = Thread::create(server_thread_fn, (void*)this);
433 ServerThread::~ServerThread()
435 // Then lock the children map, remove this socket/thread, signal waiters, and return
436 m_listener->m_child_lock->lock();
437 m_listener->m_children.erase(m_sock);
438 m_listener->m_child_lock->unlock();
439 m_listener->m_child_wait->signal();
444 void ServerThread::run()
448 // Before starting up, make sure we fully "own" this socket.
449 m_listener->m_child_lock->lock();
450 while (m_listener->m_children.find(m_sock)!=m_listener->m_children.end())
451 m_listener->m_child_wait->wait(m_listener->m_child_lock);
452 m_listener->m_children[m_sock] = m_child;
453 m_listener->m_child_lock->unlock();
457 struct timeval tv = { 0, 0 };
459 while(!*(m_listener->m_shutdown)) {
461 FD_SET(m_sock, &readfds);
464 switch (select(m_sock+1, &readfds, 0, 0, &tv)) {
470 if (errno == EINTR) continue;
471 m_listener->log_error();
472 m_listener->log->error("select() on incoming request socket (%u) returned error", m_sock);
482 m_listener->log_error();
483 m_listener->log->error("I/O failure processing request on socket (%u)", m_sock);
485 m_listener->close(m_sock);
492 int ServerThread::job()
494 Category& log = Category::getInstance(SHIBSP_LOGCAT".Listener");
496 bool incomingError = true; // set false once incoming message is received
506 int readlength = m_listener->recv(m_sock,(char*)&len,sizeof(len));
507 if (readlength == 0) {
508 log.info("detected socket closure, shutting down worker thread");
511 else if (readlength != sizeof(len)) {
512 log.error("error reading size of input message");
519 while (len && (size_read = m_listener->recv(m_sock, m_buf, sizeof(m_buf))) > 0) {
520 is.write(m_buf, size_read);
525 log.error("error reading input message from socket");
529 // Unmarshall the message.
534 log.debug("dispatching message (%s)", in.name() ? in.name() : "unnamed");
536 incomingError = false;
538 // Dispatch the message.
539 m_listener->receive(in, sink);
541 catch (XMLToolingException& e) {
543 log.error("error processing incoming message: %s", e.what());
544 DDF out=DDF("exception").string(e.toString().c_str());
545 DDFJanitor jout(out);
548 catch (exception& e) {
550 log.error("error processing incoming message: %s", e.what());
551 ListenerException ex(e.what());
552 DDF out=DDF("exception").string(ex.toString().c_str());
553 DDFJanitor jout(out);
558 log.error("unexpected error processing incoming message");
559 if (!m_listener->m_catchAll)
561 ListenerException ex("An unexpected error occurred while processing an incoming message.");
562 DDF out=DDF("exception").string(ex.toString().c_str());
563 DDFJanitor jout(out);
567 // Return whatever's available.
568 string response(sink.str());
569 int outlen = response.length();
571 if (m_listener->send(m_sock,(char*)&len,sizeof(len)) != sizeof(len)) {
572 log.error("error sending output message size");
575 if (m_listener->send(m_sock,response.c_str(),outlen) != outlen) {
576 log.error("error sending output message");