2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * Berkeley Socket-based ListenerService implementation.
28 #include "exceptions.h"
29 #include "ServiceProvider.h"
31 #include "remoting/impl/SocketListener.h"
36 #include <xercesc/util/XMLUniDefs.hpp>
38 #include <xmltooling/util/NDC.h>
39 #include <xmltooling/util/XMLHelper.h>
42 # include <netinet/in.h>
49 using namespace shibsp;
50 using namespace xmltooling;
52 using xercesc::DOMElement;
56 // Manages the pool of connections
60 SocketPool(Category& log, const SocketListener* listener)
61 : m_log(log), m_listener(listener), m_lock(Mutex::create()) {}
63 SocketListener::ShibSocket get();
64 void put(SocketListener::ShibSocket s);
67 SocketListener::ShibSocket connect();
70 const SocketListener* m_listener;
71 auto_ptr<Mutex> m_lock;
72 stack<SocketListener::ShibSocket> m_pool;
75 // Worker threads in server
78 ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id);
81 int job(); // Return -1 on error, 1 for closed, 0 for success
84 SocketListener::ShibSocket m_sock;
86 SocketListener* m_listener;
92 SocketListener::ShibSocket SocketPool::connect()
98 m_log.debug("trying to connect to listener");
100 SocketListener::ShibSocket sock;
101 if (!m_listener->create(sock)) {
102 m_log.error("cannot create socket");
103 throw ListenerException("Cannot create socket");
106 bool connected = false;
109 for (int i = num_tries-1; i >= 0; i--) {
110 if (m_listener->connect(sock)) {
115 m_log.warn("cannot connect socket (%u)...%s", sock, (i > 0 ? "retrying" : ""));
119 Sleep(2000*(num_tries-i));
121 sleep(2*(num_tries-i));
127 m_log.crit("socket server unavailable, failing");
128 m_listener->close(sock);
129 throw ListenerException("Cannot connect to shibd process, a site adminstrator should be notified.");
132 m_log.debug("socket (%u) connected successfully", sock);
136 SocketPool::~SocketPool()
138 while (!m_pool.empty()) {
140 closesocket(m_pool.top());
142 ::close(m_pool.top());
148 SocketListener::ShibSocket SocketPool::get()
151 if (m_pool.empty()) {
155 SocketListener::ShibSocket ret=m_pool.top();
161 void SocketPool::put(SocketListener::ShibSocket s)
168 SocketListener::SocketListener(const DOMElement* e)
169 : m_catchAll(false), log(&Category::getInstance(SHIBSP_LOGCAT".Listener")), m_socketpool(nullptr),
170 m_shutdown(nullptr), m_child_lock(nullptr), m_child_wait(nullptr), m_stackSize(0), m_socket((ShibSocket)0)
173 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
174 m_socketpool=new SocketPool(*log,this);
177 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
178 m_child_lock = Mutex::create();
179 m_child_wait = CondWait::create();
181 static const XMLCh stackSize[] = UNICODE_LITERAL_9(s,t,a,c,k,S,i,z,e);
182 m_stackSize = XMLHelper::getAttrInt(e, 0, stackSize) * 1024;
186 SocketListener::~SocketListener()
193 bool SocketListener::init(bool force)
198 log->info("listener service starting");
200 ServiceProvider* sp = SPConfig::getConfig().getServiceProvider();
202 const PropertySet* props = sp->getPropertySet("OutOfProcess");
204 pair<bool,bool> flag = props->getBool("catchAll");
205 m_catchAll = flag.first && flag.second;
209 if (!create(m_socket)) {
210 log->crit("failed to create socket");
213 if (!bind(m_socket, force)) {
214 this->close(m_socket);
215 log->crit("failed to bind to socket.");
222 bool SocketListener::run(bool* shutdown)
227 // Save flag to monitor for shutdown request.
229 unsigned long count = 0;
231 while (!*m_shutdown) {
234 FD_SET(m_socket, &readfds);
235 struct timeval tv = { 0, 0 };
238 switch (select(m_socket + 1, &readfds, 0, 0, &tv)) {
244 if (errno == EINTR) continue;
246 log->error("select() on main listener socket failed");
255 // Accept the connection.
256 SocketListener::ShibSocket newsock;
257 if (!accept(m_socket, newsock)) {
258 log->crit("failed to accept incoming socket connection");
262 // We throw away the result because the children manage themselves...
264 new ServerThread(newsock,this,++count);
266 catch (exception& ex) {
267 log->crit("exception starting new server thread to service incoming request: %s", ex.what());
270 log->crit("unknown error starting new server thread to service incoming request");
277 log->info("listener service shutting down");
279 // Wait for all children to exit.
280 m_child_lock->lock();
281 while (!m_children.empty())
282 m_child_wait->wait(m_child_lock);
283 m_child_lock->unlock();
288 void SocketListener::term()
290 this->close(m_socket);
291 m_socket=(ShibSocket)0;
294 DDF SocketListener::send(const DDF& in)
300 log->debug("sending message (%s)", in.name() ? in.name() : "unnamed");
302 // Serialize data for transmission.
305 string ostr(os.str());
307 // Loop on the RPC in case we lost contact the first time through
314 SocketListener::ShibSocket sock;
316 sock = m_socketpool->get();
318 int outlen = ostr.length();
320 if (send(sock,(char*)&len,sizeof(len)) != sizeof(len) || send(sock,ostr.c_str(),outlen) != outlen) {
326 throw ListenerException("Failure sending remoted message ($1).", params(1,in.name()));
334 log->debug("send completed, reading response message");
337 while (recv(sock,(char*)&len,sizeof(len)) != sizeof(len)) {
338 if (errno == EINTR) continue; // Apparently this happens when a signal interrupts the blocking call.
339 log->error("error reading size of output message");
341 throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
349 size_read = recv(sock, buf, sizeof(buf));
351 is.write(buf, size_read);
354 else if (errno != EINTR) {
360 log->error("error reading output message from socket");
362 throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
365 m_socketpool->put(sock);
371 // Check for exception to unmarshall and throw, otherwise return.
372 if (out.isstring() && out.name() && !strcmp(out.name(),"exception")) {
373 // Reconstitute exception object.
374 DDFJanitor jout(out);
375 XMLToolingException* except=nullptr;
377 except=XMLToolingException::fromString(out.string());
378 log->error("remoted message returned an error: %s", except->what());
380 catch (XMLToolingException& e) {
381 log->error("caught XMLToolingException while building the XMLToolingException: %s", e.what());
382 log->error("XML was: %s", out.string());
383 throw ListenerException("Remote call failed with an unparsable exception.");
386 auto_ptr<XMLToolingException> wrapper(except);
393 bool SocketListener::log_error() const
396 int rc=WSAGetLastError();
400 #ifdef HAVE_STRERROR_R
402 memset(buf,0,sizeof(buf));
403 strerror_r(rc,buf,sizeof(buf));
404 log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
406 const char* buf=strerror(rc);
407 log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
412 // actual function run in listener on server threads
413 void* server_thread_fn(void* arg)
415 ServerThread* child = (ServerThread*)arg;
418 // First, let's block all signals
419 Thread::mask_all_signals();
422 // Run the child until it exits.
425 // Now we can clean up and exit the thread.
430 ServerThread::ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id)
431 : m_sock(s), m_child(nullptr), m_listener(listener)
435 buf << "[" << id << "]";
438 // Create the child thread
439 m_child = Thread::create(server_thread_fn, (void*)this, m_listener->m_stackSize);
443 ServerThread::~ServerThread()
445 // Then lock the children map, remove this socket/thread, signal waiters, and return
446 m_listener->m_child_lock->lock();
447 m_listener->m_children.erase(m_sock);
448 m_listener->m_child_lock->unlock();
449 m_listener->m_child_wait->signal();
454 void ServerThread::run()
458 // Before starting up, make sure we fully "own" this socket.
459 m_listener->m_child_lock->lock();
460 while (m_listener->m_children.find(m_sock)!=m_listener->m_children.end())
461 m_listener->m_child_wait->wait(m_listener->m_child_lock);
462 m_listener->m_children[m_sock] = m_child;
463 m_listener->m_child_lock->unlock();
467 struct timeval tv = { 0, 0 };
469 while(!*(m_listener->m_shutdown)) {
471 FD_SET(m_sock, &readfds);
474 switch (select(m_sock+1, &readfds, 0, 0, &tv)) {
480 if (errno == EINTR) continue;
481 m_listener->log_error();
482 m_listener->log->error("select() on incoming request socket (%u) returned error", m_sock);
492 m_listener->log_error();
493 m_listener->log->error("I/O failure processing request on socket (%u)", m_sock);
495 m_listener->close(m_sock);
502 int ServerThread::job()
504 Category& log = Category::getInstance(SHIBSP_LOGCAT".Listener");
506 bool incomingError = true; // set false once incoming message is received
516 int readlength = m_listener->recv(m_sock,(char*)&len,sizeof(len));
517 if (readlength == 0) {
518 log.info("detected socket closure, shutting down worker thread");
521 else if (readlength != sizeof(len)) {
522 log.error("error reading size of input message");
529 while (len && (size_read = m_listener->recv(m_sock, m_buf, sizeof(m_buf))) > 0) {
530 is.write(m_buf, size_read);
535 log.error("error reading input message from socket");
539 // Unmarshall the message.
544 log.debug("dispatching message (%s)", in.name() ? in.name() : "unnamed");
546 incomingError = false;
548 // Dispatch the message.
549 m_listener->receive(in, sink);
551 catch (XMLToolingException& e) {
553 log.error("error processing incoming message: %s", e.what());
554 DDF out=DDF("exception").string(e.toString().c_str());
555 DDFJanitor jout(out);
558 catch (exception& e) {
560 log.error("error processing incoming message: %s", e.what());
561 ListenerException ex(e.what());
562 DDF out=DDF("exception").string(ex.toString().c_str());
563 DDFJanitor jout(out);
568 log.error("unexpected error processing incoming message");
569 if (!m_listener->m_catchAll)
571 ListenerException ex("An unexpected error occurred while processing an incoming message.");
572 DDF out=DDF("exception").string(ex.toString().c_str());
573 DDFJanitor jout(out);
577 // Return whatever's available.
578 string response(sink.str());
579 int outlen = response.length();
581 if (m_listener->send(m_sock,(char*)&len,sizeof(len)) != sizeof(len)) {
582 log.error("error sending output message size");
585 if (m_listener->send(m_sock,response.c_str(),outlen) != outlen) {
586 log.error("error sending output message");