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 "ServiceProvider.h"
26 #include "remoting/impl/SocketListener.h"
31 #include <shibsp/SPConfig.h>
32 #include <xmltooling/util/NDC.h>
35 # include <netinet/in.h>
38 using namespace shibsp;
39 using namespace xmltooling;
41 using xercesc::DOMElement;
45 // Manages the pool of connections
49 SocketPool(Category& log, const SocketListener* listener)
50 : m_log(log), m_listener(listener), m_lock(Mutex::create()) {}
52 SocketListener::ShibSocket get();
53 void put(SocketListener::ShibSocket s);
56 SocketListener::ShibSocket connect();
59 const SocketListener* m_listener;
60 auto_ptr<Mutex> m_lock;
61 stack<SocketListener::ShibSocket> m_pool;
64 // Worker threads in server
67 ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id);
70 int job(); // Return -1 on error, 1 for closed, 0 for success
73 SocketListener::ShibSocket m_sock;
75 SocketListener* m_listener;
81 SocketListener::ShibSocket SocketPool::connect()
87 m_log.debug("trying to connect to listener");
89 SocketListener::ShibSocket sock;
90 if (!m_listener->create(sock)) {
91 m_log.error("cannot create socket");
92 throw ListenerException("Cannot create socket");
95 bool connected = false;
98 for (int i = num_tries-1; i >= 0; i--) {
99 if (m_listener->connect(sock)) {
104 m_log.warn("cannot connect socket (%u)...%s", sock, (i > 0 ? "retrying" : ""));
108 Sleep(2000*(num_tries-i));
110 sleep(2*(num_tries-i));
116 m_log.crit("socket server unavailable, failing");
117 m_listener->close(sock);
118 throw ListenerException("Cannot connect to shibd process, a site adminstrator should be notified.");
121 m_log.debug("socket (%u) connected successfully", sock);
125 SocketPool::~SocketPool()
127 while (!m_pool.empty()) {
129 closesocket(m_pool.top());
131 ::close(m_pool.top());
137 SocketListener::ShibSocket SocketPool::get()
140 if (m_pool.empty()) {
144 SocketListener::ShibSocket ret=m_pool.top();
150 void SocketPool::put(SocketListener::ShibSocket s)
157 SocketListener::SocketListener(const DOMElement* e) : m_catchAll(false), log(&Category::getInstance(SHIBSP_LOGCAT".Listener")),
158 m_socketpool(NULL), m_shutdown(NULL), m_child_lock(NULL), m_child_wait(NULL), m_socket((ShibSocket)0)
161 if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
162 m_socketpool=new SocketPool(*log,this);
165 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
166 m_child_lock = Mutex::create();
167 m_child_wait = CondWait::create();
171 SocketListener::~SocketListener()
178 bool SocketListener::run(bool* shutdown)
183 log->info("listener service starting");
185 ServiceProvider* sp = SPConfig::getConfig().getServiceProvider();
187 const PropertySet* props = sp->getPropertySet("OutOfProcess");
189 pair<bool,bool> flag = props->getBool("catchAll");
190 m_catchAll = flag.first && flag.second;
194 // Save flag to monitor for shutdown request.
196 unsigned long count = 0;
198 if (!create(m_socket)) {
199 log->crit("failed to create socket");
202 if (!bind(m_socket,true)) {
203 this->close(m_socket);
204 log->crit("failed to bind to socket.");
208 while (!*m_shutdown) {
211 FD_SET(m_socket, &readfds);
212 struct timeval tv = { 0, 0 };
215 switch (select(m_socket + 1, &readfds, 0, 0, &tv)) {
221 if (errno == EINTR) continue;
223 log->error("select() on main listener socket failed");
231 // Accept the connection.
232 SocketListener::ShibSocket newsock;
233 if (!accept(m_socket, newsock))
234 log->crit("failed to accept incoming socket connection");
236 // We throw away the result because the children manage themselves...
238 new ServerThread(newsock,this,++count);
241 log->crit("error starting new server thread to service incoming request");
248 log->info("listener service shutting down");
250 // Wait for all children to exit.
251 m_child_lock->lock();
252 while (!m_children.empty())
253 m_child_wait->wait(m_child_lock);
254 m_child_lock->unlock();
256 this->close(m_socket);
257 m_socket=(ShibSocket)0;
261 DDF SocketListener::send(const DDF& in)
267 log->debug("sending message (%s)", in.name() ? in.name() : "unnamed");
269 // Serialize data for transmission.
272 string ostr(os.str());
274 // Loop on the RPC in case we lost contact the first time through
281 SocketListener::ShibSocket sock;
283 sock = m_socketpool->get();
285 int outlen = ostr.length();
287 if (send(sock,(char*)&len,sizeof(len)) != sizeof(len) || send(sock,ostr.c_str(),outlen) != outlen) {
293 throw ListenerException("Failure sending remoted message ($1).", params(1,in.name()));
301 log->debug("send completed, reading response message");
304 if (recv(sock,(char*)&len,sizeof(len)) != sizeof(len)) {
305 log->error("error reading size of output message");
307 throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
314 while (len && (size_read = recv(sock, buf, sizeof(buf))) > 0) {
315 is.write(buf, size_read);
320 log->error("error reading output message from socket");
322 throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
325 m_socketpool->put(sock);
331 // Check for exception to unmarshall and throw, otherwise return.
332 if (out.isstring() && out.name() && !strcmp(out.name(),"exception")) {
333 // Reconstitute exception object.
334 DDFJanitor jout(out);
335 XMLToolingException* except=NULL;
337 except=XMLToolingException::fromString(out.string());
338 log->error("remoted message returned an error: %s", except->what());
340 catch (XMLToolingException& e) {
341 log->error("caught XMLToolingException while building the XMLToolingException: %s", e.what());
342 log->error("XML was: %s", out.string());
343 throw ListenerException("Remote call failed with an unparsable exception.");
346 auto_ptr<XMLToolingException> wrapper(except);
353 bool SocketListener::log_error() const
356 int rc=WSAGetLastError();
360 #ifdef HAVE_STRERROR_R
362 memset(buf,0,sizeof(buf));
363 strerror_r(rc,buf,sizeof(buf));
364 log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
366 const char* buf=strerror(rc);
367 log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
372 // actual function run in listener on server threads
373 void* server_thread_fn(void* arg)
375 ServerThread* child = (ServerThread*)arg;
378 // First, let's block all signals
379 Thread::mask_all_signals();
382 // Run the child until it exits.
385 // Now we can clean up and exit the thread.
390 ServerThread::ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id)
391 : m_sock(s), m_child(NULL), m_listener(listener)
395 buf << "[" << id << "]";
398 // Create the child thread
399 m_child = Thread::create(server_thread_fn, (void*)this);
403 ServerThread::~ServerThread()
405 // Then lock the children map, remove this socket/thread, signal waiters, and return
406 m_listener->m_child_lock->lock();
407 m_listener->m_children.erase(m_sock);
408 m_listener->m_child_lock->unlock();
409 m_listener->m_child_wait->signal();
414 void ServerThread::run()
418 // Before starting up, make sure we fully "own" this socket.
419 m_listener->m_child_lock->lock();
420 while (m_listener->m_children.find(m_sock)!=m_listener->m_children.end())
421 m_listener->m_child_wait->wait(m_listener->m_child_lock);
422 m_listener->m_children[m_sock] = m_child;
423 m_listener->m_child_lock->unlock();
427 struct timeval tv = { 0, 0 };
429 while(!*(m_listener->m_shutdown)) {
431 FD_SET(m_sock, &readfds);
434 switch (select(m_sock+1, &readfds, 0, 0, &tv)) {
440 if (errno == EINTR) continue;
441 m_listener->log_error();
442 m_listener->log->error("select() on incoming request socket (%u) returned error", m_sock);
452 m_listener->log_error();
453 m_listener->log->error("I/O failure processing request on socket (%u)", m_sock);
455 m_listener->close(m_sock);
462 int ServerThread::job()
464 Category& log = Category::getInstance("shibd.Listener");
466 bool incomingError = true; // set false once incoming message is received
476 int readlength = m_listener->recv(m_sock,(char*)&len,sizeof(len));
477 if (readlength == 0) {
478 log.info("detected socket closure, shutting down worker thread");
481 else if (readlength != sizeof(len)) {
482 log.error("error reading size of input message");
489 while (len && (size_read = m_listener->recv(m_sock, m_buf, sizeof(m_buf))) > 0) {
490 is.write(m_buf, size_read);
495 log.error("error reading input message from socket");
499 // Unmarshall the message.
504 log.debug("dispatching message (%s)", in.name() ? in.name() : "unnamed");
506 incomingError = false;
508 // Dispatch the message.
509 m_listener->receive(in, sink);
511 catch (XMLToolingException& e) {
513 log.error("error processing incoming message: %s", e.what());
514 DDF out=DDF("exception").string(e.toString().c_str());
515 DDFJanitor jout(out);
518 catch (exception& e) {
520 log.error("error processing incoming message: %s", e.what());
521 ListenerException ex(e.what());
522 DDF out=DDF("exception").string(ex.toString().c_str());
523 DDFJanitor jout(out);
528 log.error("unexpected error processing incoming message");
529 if (!m_listener->m_catchAll)
531 ListenerException ex("An unexpected error occurred while processing an incoming message.");
532 DDF out=DDF("exception").string(ex.toString().c_str());
533 DDFJanitor jout(out);
537 // Return whatever's available.
538 string response(sink.str());
539 int outlen = response.length();
541 if (m_listener->send(m_sock,(char*)&len,sizeof(len)) != sizeof(len)) {
542 log.error("error sending output message size");
545 if (m_listener->send(m_sock,response.c_str(),outlen) != outlen) {
546 log.error("error sending output message");