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),
166 m_shutdown(NULL), m_child_lock(NULL), m_child_wait(NULL), m_socket((ShibSocket)0)
169 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
170 m_socketpool=new SocketPool(*log,this);
173 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
174 m_child_lock = Mutex::create();
175 m_child_wait = CondWait::create();
179 SocketListener::~SocketListener()
186 bool SocketListener::init(bool force)
191 log->info("listener service starting");
193 ServiceProvider* sp = SPConfig::getConfig().getServiceProvider();
195 const PropertySet* props = sp->getPropertySet("OutOfProcess");
197 pair<bool,bool> flag = props->getBool("catchAll");
198 m_catchAll = flag.first && flag.second;
202 if (!create(m_socket)) {
203 log->crit("failed to create socket");
206 if (!bind(m_socket, force)) {
207 this->close(m_socket);
208 log->crit("failed to bind to socket.");
215 bool SocketListener::run(bool* shutdown)
220 // Save flag to monitor for shutdown request.
222 unsigned long count = 0;
224 while (!*m_shutdown) {
227 FD_SET(m_socket, &readfds);
228 struct timeval tv = { 0, 0 };
231 switch (select(m_socket + 1, &readfds, 0, 0, &tv)) {
237 if (errno == EINTR) continue;
239 log->error("select() on main listener socket failed");
248 // Accept the connection.
249 SocketListener::ShibSocket newsock;
250 if (!accept(m_socket, newsock)) {
251 log->crit("failed to accept incoming socket connection");
255 // We throw away the result because the children manage themselves...
257 new ServerThread(newsock,this,++count);
259 catch (exception& ex) {
260 log->crit("exception starting new server thread to service incoming request: %s", ex.what());
263 log->crit("unknown error starting new server thread to service incoming request");
270 log->info("listener service shutting down");
272 // Wait for all children to exit.
273 m_child_lock->lock();
274 while (!m_children.empty())
275 m_child_wait->wait(m_child_lock);
276 m_child_lock->unlock();
281 void SocketListener::term()
283 this->close(m_socket);
284 m_socket=(ShibSocket)0;
287 DDF SocketListener::send(const DDF& in)
293 log->debug("sending message (%s)", in.name() ? in.name() : "unnamed");
295 // Serialize data for transmission.
298 string ostr(os.str());
300 // Loop on the RPC in case we lost contact the first time through
307 SocketListener::ShibSocket sock;
309 sock = m_socketpool->get();
311 int outlen = ostr.length();
313 if (send(sock,(char*)&len,sizeof(len)) != sizeof(len) || send(sock,ostr.c_str(),outlen) != outlen) {
319 throw ListenerException("Failure sending remoted message ($1).", params(1,in.name()));
327 log->debug("send completed, reading response message");
330 while (recv(sock,(char*)&len,sizeof(len)) != sizeof(len)) {
331 if (errno == EINTR) continue; // Apparently this happens when a signal interrupts the blocking call.
332 log->error("error reading size of output message");
334 throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
342 size_read = recv(sock, buf, sizeof(buf));
344 is.write(buf, size_read);
347 else if (errno != EINTR) {
353 log->error("error reading output message from socket");
355 throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
358 m_socketpool->put(sock);
364 // Check for exception to unmarshall and throw, otherwise return.
365 if (out.isstring() && out.name() && !strcmp(out.name(),"exception")) {
366 // Reconstitute exception object.
367 DDFJanitor jout(out);
368 XMLToolingException* except=NULL;
370 except=XMLToolingException::fromString(out.string());
371 log->error("remoted message returned an error: %s", except->what());
373 catch (XMLToolingException& e) {
374 log->error("caught XMLToolingException while building the XMLToolingException: %s", e.what());
375 log->error("XML was: %s", out.string());
376 throw ListenerException("Remote call failed with an unparsable exception.");
379 auto_ptr<XMLToolingException> wrapper(except);
386 bool SocketListener::log_error() const
389 int rc=WSAGetLastError();
393 #ifdef HAVE_STRERROR_R
395 memset(buf,0,sizeof(buf));
396 strerror_r(rc,buf,sizeof(buf));
397 log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
399 const char* buf=strerror(rc);
400 log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
405 // actual function run in listener on server threads
406 void* server_thread_fn(void* arg)
408 ServerThread* child = (ServerThread*)arg;
411 // First, let's block all signals
412 Thread::mask_all_signals();
415 // Run the child until it exits.
418 // Now we can clean up and exit the thread.
423 ServerThread::ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id)
424 : m_sock(s), m_child(NULL), m_listener(listener)
428 buf << "[" << id << "]";
431 // Create the child thread
432 m_child = Thread::create(server_thread_fn, (void*)this);
436 ServerThread::~ServerThread()
438 // Then lock the children map, remove this socket/thread, signal waiters, and return
439 m_listener->m_child_lock->lock();
440 m_listener->m_children.erase(m_sock);
441 m_listener->m_child_lock->unlock();
442 m_listener->m_child_wait->signal();
447 void ServerThread::run()
451 // Before starting up, make sure we fully "own" this socket.
452 m_listener->m_child_lock->lock();
453 while (m_listener->m_children.find(m_sock)!=m_listener->m_children.end())
454 m_listener->m_child_wait->wait(m_listener->m_child_lock);
455 m_listener->m_children[m_sock] = m_child;
456 m_listener->m_child_lock->unlock();
460 struct timeval tv = { 0, 0 };
462 while(!*(m_listener->m_shutdown)) {
464 FD_SET(m_sock, &readfds);
467 switch (select(m_sock+1, &readfds, 0, 0, &tv)) {
473 if (errno == EINTR) continue;
474 m_listener->log_error();
475 m_listener->log->error("select() on incoming request socket (%u) returned error", m_sock);
485 m_listener->log_error();
486 m_listener->log->error("I/O failure processing request on socket (%u)", m_sock);
488 m_listener->close(m_sock);
495 int ServerThread::job()
497 Category& log = Category::getInstance(SHIBSP_LOGCAT".Listener");
499 bool incomingError = true; // set false once incoming message is received
509 int readlength = m_listener->recv(m_sock,(char*)&len,sizeof(len));
510 if (readlength == 0) {
511 log.info("detected socket closure, shutting down worker thread");
514 else if (readlength != sizeof(len)) {
515 log.error("error reading size of input message");
522 while (len && (size_read = m_listener->recv(m_sock, m_buf, sizeof(m_buf))) > 0) {
523 is.write(m_buf, size_read);
528 log.error("error reading input message from socket");
532 // Unmarshall the message.
537 log.debug("dispatching message (%s)", in.name() ? in.name() : "unnamed");
539 incomingError = false;
541 // Dispatch the message.
542 m_listener->receive(in, sink);
544 catch (XMLToolingException& e) {
546 log.error("error processing incoming message: %s", e.what());
547 DDF out=DDF("exception").string(e.toString().c_str());
548 DDFJanitor jout(out);
551 catch (exception& e) {
553 log.error("error processing incoming message: %s", e.what());
554 ListenerException ex(e.what());
555 DDF out=DDF("exception").string(ex.toString().c_str());
556 DDFJanitor jout(out);
561 log.error("unexpected error processing incoming message");
562 if (!m_listener->m_catchAll)
564 ListenerException ex("An unexpected error occurred while processing an incoming message.");
565 DDF out=DDF("exception").string(ex.toString().c_str());
566 DDFJanitor jout(out);
570 // Return whatever's available.
571 string response(sink.str());
572 int outlen = response.length();
574 if (m_listener->send(m_sock,(char*)&len,sizeof(len)) != sizeof(len)) {
575 log.error("error sending output message size");
578 if (m_listener->send(m_sock,response.c_str(),outlen) != outlen) {
579 log.error("error sending output message");