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 char* fn) const
398 int rc=WSAGetLastError();
402 #ifdef HAVE_STRERROR_R
404 memset(buf,0,sizeof(buf));
405 strerror_r(rc,buf,sizeof(buf));
406 log->error("socket call (%s) resulted in error (%d): %s",fn, rc, isprint(*buf) ? buf : "no message");
408 const char* buf=strerror(rc);
409 log->error("socket call (%s) resulted in error (%d): %s", fn, rc, isprint(*buf) ? buf : "no message");
414 // actual function run in listener on server threads
415 void* server_thread_fn(void* arg)
417 ServerThread* child = (ServerThread*)arg;
420 // First, let's block all signals
421 Thread::mask_all_signals();
424 // Run the child until it exits.
427 // Now we can clean up and exit the thread.
432 ServerThread::ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id)
433 : m_sock(s), m_child(nullptr), m_listener(listener)
437 buf << "[" << id << "]";
440 // Create the child thread
441 m_child = Thread::create(server_thread_fn, (void*)this, m_listener->m_stackSize);
445 ServerThread::~ServerThread()
447 // Then lock the children map, remove this socket/thread, signal waiters, and return
448 m_listener->m_child_lock->lock();
449 m_listener->m_children.erase(m_sock);
450 m_listener->m_child_lock->unlock();
451 m_listener->m_child_wait->signal();
456 void ServerThread::run()
460 // Before starting up, make sure we fully "own" this socket.
461 m_listener->m_child_lock->lock();
462 while (m_listener->m_children.find(m_sock)!=m_listener->m_children.end())
463 m_listener->m_child_wait->wait(m_listener->m_child_lock);
464 m_listener->m_children[m_sock] = m_child;
465 m_listener->m_child_lock->unlock();
469 struct timeval tv = { 0, 0 };
471 while(!*(m_listener->m_shutdown)) {
473 FD_SET(m_sock, &readfds);
476 switch (select(m_sock+1, &readfds, 0, 0, &tv)) {
482 if (errno == EINTR) continue;
483 m_listener->log_error();
484 m_listener->log->error("select() on incoming request socket (%u) returned error", m_sock);
494 m_listener->log_error();
495 m_listener->log->error("I/O failure processing request on socket (%u)", m_sock);
497 m_listener->close(m_sock);
504 int ServerThread::job()
506 Category& log = Category::getInstance(SHIBSP_LOGCAT".Listener");
508 bool incomingError = true; // set false once incoming message is received
518 int readlength = m_listener->recv(m_sock,(char*)&len,sizeof(len));
519 if (readlength == 0) {
520 log.info("detected socket closure, shutting down worker thread");
523 else if (readlength != sizeof(len)) {
524 log.error("error reading size of input message");
531 while (len && (size_read = m_listener->recv(m_sock, m_buf, sizeof(m_buf))) > 0) {
532 is.write(m_buf, size_read);
537 log.error("error reading input message from socket");
541 // Unmarshall the message.
546 log.debug("dispatching message (%s)", in.name() ? in.name() : "unnamed");
548 incomingError = false;
550 // Dispatch the message.
551 m_listener->receive(in, sink);
553 catch (XMLToolingException& e) {
555 log.error("error processing incoming message: %s", e.what());
556 DDF out=DDF("exception").string(e.toString().c_str());
557 DDFJanitor jout(out);
560 catch (exception& e) {
562 log.error("error processing incoming message: %s", e.what());
563 ListenerException ex(e.what());
564 DDF out=DDF("exception").string(ex.toString().c_str());
565 DDFJanitor jout(out);
570 log.error("unexpected error processing incoming message");
571 if (!m_listener->m_catchAll)
573 ListenerException ex("An unexpected error occurred while processing an incoming message.");
574 DDF out=DDF("exception").string(ex.toString().c_str());
575 DDFJanitor jout(out);
579 // Return whatever's available.
580 string response(sink.str());
581 int outlen = response.length();
583 if (m_listener->send(m_sock,(char*)&len,sizeof(len)) != sizeof(len)) {
584 log.error("error sending output message size");
587 if (m_listener->send(m_sock,response.c_str(),outlen) != outlen) {
588 log.error("error sending output message");