a09bda274703ffb7e73a921e51450c0ba0b5ff08
[shibboleth/cpp-sp.git] / shibsp / remoting / impl / SocketListener.cpp
1 /**
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.
6  *
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
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  */
20
21 /**
22  * SocketListener.cpp
23  *
24  * Berkeley Socket-based ListenerService implementation.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "ServiceProvider.h"
30 #include "SPConfig.h"
31 #include "remoting/impl/SocketListener.h"
32
33 #include <errno.h>
34 #include <stack>
35 #include <sstream>
36 #include <xercesc/util/XMLUniDefs.hpp>
37
38 #include <xmltooling/util/NDC.h>
39 #include <xmltooling/util/XMLHelper.h>
40
41 #ifndef WIN32
42 # include <netinet/in.h>
43 #endif
44
45 #ifdef HAVE_UNISTD_H
46 # include <unistd.h>
47 #endif
48
49 using namespace shibsp;
50 using namespace xmltooling;
51 using namespace std;
52 using xercesc::DOMElement;
53
54 namespace shibsp {
55
56     // Manages the pool of connections
57     class SocketPool
58     {
59     public:
60         SocketPool(Category& log, const SocketListener* listener)
61             : m_log(log), m_listener(listener), m_lock(Mutex::create()) {}
62         ~SocketPool();
63         SocketListener::ShibSocket get();
64         void put(SocketListener::ShibSocket s);
65
66     private:
67         SocketListener::ShibSocket connect();
68
69         Category& m_log;
70         const SocketListener* m_listener;
71         boost::scoped_ptr<Mutex> m_lock;
72         stack<SocketListener::ShibSocket> m_pool;
73     };
74
75     // Worker threads in server
76     class ServerThread {
77     public:
78         ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id);
79         ~ServerThread();
80         void run();
81         int job();  // Return -1 on error, 1 for closed, 0 for success
82
83     private:
84         SocketListener::ShibSocket m_sock;
85         Thread* m_child;
86         SocketListener* m_listener;
87         string m_id;
88         char m_buf[16384];
89     };
90 }
91
92 SocketListener::ShibSocket SocketPool::connect()
93 {
94 #ifdef _DEBUG
95     NDC ndc("connect");
96 #endif
97
98     m_log.debug("trying to connect to listener");
99
100     SocketListener::ShibSocket sock;
101     if (!m_listener->create(sock)) {
102         m_log.error("cannot create socket");
103         throw ListenerException("Cannot create socket");
104     }
105
106     bool connected = false;
107     int num_tries = 3;
108
109     for (int i = num_tries-1; i >= 0; i--) {
110         if (m_listener->connect(sock)) {
111             connected = true;
112             break;
113         }
114
115         m_log.warn("cannot connect socket (%u)...%s", sock, (i > 0 ? "retrying" : ""));
116
117         if (i) {
118 #ifdef WIN32
119             Sleep(2000*(num_tries-i));
120 #else
121             sleep(2*(num_tries-i));
122 #endif
123         }
124     }
125
126     if (!connected) {
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.");
130     }
131
132     m_log.debug("socket (%u) connected successfully", sock);
133     return sock;
134 }
135
136 SocketPool::~SocketPool()
137 {
138     while (!m_pool.empty()) {
139 #ifdef WIN32
140         closesocket(m_pool.top());
141 #else
142         ::close(m_pool.top());
143 #endif
144         m_pool.pop();
145     }
146 }
147
148 SocketListener::ShibSocket SocketPool::get()
149 {
150     m_lock->lock();
151     if (m_pool.empty()) {
152         m_lock->unlock();
153         return connect();
154     }
155     SocketListener::ShibSocket ret=m_pool.top();
156     m_pool.pop();
157     m_lock->unlock();
158     return ret;
159 }
160
161 void SocketPool::put(SocketListener::ShibSocket s)
162 {
163     Lock lock(m_lock);
164     m_pool.push(s);
165 }
166
167 SocketListener::SocketListener(const DOMElement* e)
168     : m_catchAll(false), log(&Category::getInstance(SHIBSP_LOGCAT".Listener")),
169         m_shutdown(nullptr), m_stackSize(0), m_socket((ShibSocket)0)
170 {
171     // Are we a client?
172     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
173         m_socketpool.reset(new SocketPool(*log,this));
174     }
175     // Are we a server?
176     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
177         m_child_lock.reset(Mutex::create());
178         m_child_wait.reset(CondWait::create());
179
180         static const XMLCh stackSize[] = UNICODE_LITERAL_9(s,t,a,c,k,S,i,z,e);
181         m_stackSize = XMLHelper::getAttrInt(e, 0, stackSize) * 1024;
182     }
183 }
184
185 SocketListener::~SocketListener()
186 {
187 }
188
189 bool SocketListener::init(bool force)
190 {
191 #ifdef _DEBUG
192     NDC ndc("init");
193 #endif
194     log->info("listener service starting");
195
196     ServiceProvider* sp = SPConfig::getConfig().getServiceProvider();
197     sp->lock();
198     const PropertySet* props = sp->getPropertySet("OutOfProcess");
199     if (props) {
200         pair<bool,bool> flag = props->getBool("catchAll");
201         m_catchAll = flag.first && flag.second;
202     }
203     sp->unlock();
204
205     if (!create(m_socket)) {
206         log->crit("failed to create socket");
207         return false;
208     }
209     if (!bind(m_socket, force)) {
210         this->close(m_socket);
211         log->crit("failed to bind to socket.");
212         return false;
213     }
214
215     return true;
216 }
217
218 bool SocketListener::run(bool* shutdown)
219 {
220 #ifdef _DEBUG
221     NDC ndc("run");
222 #endif
223     // Save flag to monitor for shutdown request.
224     m_shutdown = shutdown;
225     unsigned long count = 0;
226
227     while (!*m_shutdown) {
228         fd_set readfds;
229         FD_ZERO(&readfds);
230         FD_SET(m_socket, &readfds);
231         struct timeval tv = { 0, 0 };
232         tv.tv_sec = 5;
233
234         switch (select(m_socket + 1, &readfds, 0, 0, &tv)) {
235 #ifdef WIN32
236             case SOCKET_ERROR:
237 #else
238             case -1:
239 #endif
240                 if (errno == EINTR) continue;
241                 log_error();
242                 log->error("select() on main listener socket failed");
243                 *m_shutdown = true;
244                 break;
245
246             case 0:
247                 continue;
248
249             default:
250             {
251                 // Accept the connection.
252                 SocketListener::ShibSocket newsock;
253                 if (!accept(m_socket, newsock)) {
254                     log->crit("failed to accept incoming socket connection");
255                     continue;
256                 }
257
258                 // We throw away the result because the children manage themselves...
259                 try {
260                     new ServerThread(newsock, this, ++count);
261                 }
262                 catch (exception& ex) {
263                     log->crit("exception starting new server thread to service incoming request: %s", ex.what());
264                 }
265                 catch (...) {
266                     log->crit("unknown error starting new server thread to service incoming request");
267                     if (!m_catchAll)
268                         *m_shutdown = true;
269                 }
270             }
271         }
272     }
273     log->info("listener service shutting down");
274
275     // Wait for all children to exit.
276     m_child_lock->lock();
277     while (!m_children.empty())
278         m_child_wait->wait(m_child_lock.get());
279     m_child_lock->unlock();
280
281     return true;
282 }
283
284 void SocketListener::term()
285 {
286     this->close(m_socket);
287     m_socket=(ShibSocket)0;
288 }
289
290 DDF SocketListener::send(const DDF& in)
291 {
292 #ifdef _DEBUG
293     NDC ndc("send");
294 #endif
295
296     log->debug("sending message (%s)", in.name() ? in.name() : "unnamed");
297
298     // Serialize data for transmission.
299     ostringstream os;
300     os << in;
301     string ostr(os.str());
302
303     // Loop on the RPC in case we lost contact the first time through
304 #ifdef WIN32
305     u_long len;
306 #else
307     uint32_t len;
308 #endif
309     int retry = 1;
310     SocketListener::ShibSocket sock;
311     while (retry >= 0) {
312         sock = m_socketpool->get();
313
314         int outlen = ostr.length();
315         len = htonl(outlen);
316         if (send(sock,(char*)&len,sizeof(len)) != sizeof(len) || send(sock,ostr.c_str(),outlen) != outlen) {
317             log_error();
318             this->close(sock);
319             if (retry)
320                 retry--;
321             else
322                 throw ListenerException("Failure sending remoted message ($1).", params(1,in.name()));
323         }
324         else {
325             // SUCCESS.
326             retry = -1;
327         }
328     }
329
330     log->debug("send completed, reading response message");
331
332     // Read the message.
333     while (recv(sock,(char*)&len,sizeof(len)) != sizeof(len)) {
334         if (errno == EINTR) continue;   // Apparently this happens when a signal interrupts the blocking call.
335         log->error("error reading size of output message");
336         this->close(sock);
337         throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
338     }
339     len = ntohl(len);
340
341     char buf[16384];
342     int size_read;
343     stringstream is;
344     while (len) {
345         size_read = recv(sock, buf, sizeof(buf));
346         if (size_read > 0) {
347             is.write(buf, size_read);
348             len -= size_read;
349         }
350         else if (errno != EINTR) {
351                 break;
352         }
353     }
354
355     if (len) {
356         log->error("error reading output message from socket");
357         this->close(sock);
358         throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
359     }
360
361     m_socketpool->put(sock);
362
363     // Unmarshall data.
364     DDF out;
365     is >> out;
366
367     // Check for exception to unmarshall and throw, otherwise return.
368     if (out.isstring() && out.name() && !strcmp(out.name(),"exception")) {
369         // Reconstitute exception object.
370         DDFJanitor jout(out);
371         XMLToolingException* except=nullptr;
372         try {
373             except=XMLToolingException::fromString(out.string());
374             log->error("remoted message returned an error: %s", except->what());
375         }
376         catch (XMLToolingException& e) {
377             log->error("caught XMLToolingException while building the XMLToolingException: %s", e.what());
378             log->error("XML was: %s", out.string());
379             throw ListenerException("Remote call failed with an unparsable exception.");
380         }
381
382         boost::scoped_ptr<XMLToolingException> wrapper(except);
383         wrapper->raise();
384     }
385
386     return out;
387 }
388
389 bool SocketListener::log_error(const char* fn) const
390 {
391     if (!fn)
392         fn = "unknown";
393 #ifdef WIN32
394     int rc=WSAGetLastError();
395 #else
396     int rc=errno;
397 #endif
398 #ifdef HAVE_STRERROR_R
399     char buf[256];
400     memset(buf,0,sizeof(buf));
401     strerror_r(rc,buf,sizeof(buf));
402     log->error("socket call (%s) resulted in error (%d): %s",fn, rc, isprint(*buf) ? buf : "no message");
403 #else
404     const char* buf=strerror(rc);
405     log->error("socket call (%s) resulted in error (%d): %s", fn, rc, isprint(*buf) ? buf : "no message");
406 #endif
407     return false;
408 }
409
410 // actual function run in listener on server threads
411 void* server_thread_fn(void* arg)
412 {
413     ServerThread* child = (ServerThread*)arg;
414
415 #ifndef WIN32
416     // First, let's block all signals
417     Thread::mask_all_signals();
418 #endif
419
420     // Run the child until it exits.
421     child->run();
422
423     // Now we can clean up and exit the thread.
424     delete child;
425     return nullptr;
426 }
427
428 ServerThread::ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id)
429     : m_sock(s), m_child(nullptr), m_listener(listener)
430 {
431
432     ostringstream buf;
433     buf << "[" << id << "]";
434     m_id = buf.str();
435
436     // Create the child thread
437     m_child = Thread::create(server_thread_fn, (void*)this, m_listener->m_stackSize);
438     m_child->detach();
439 }
440
441 ServerThread::~ServerThread()
442 {
443     // Then lock the children map, remove this socket/thread, signal waiters, and return
444     m_listener->m_child_lock->lock();
445     m_listener->m_children.erase(m_sock);
446     m_listener->m_child_lock->unlock();
447     m_listener->m_child_wait->signal();
448
449     delete m_child;
450 }
451
452 void ServerThread::run()
453 {
454     NDC ndc(m_id);
455
456     // Before starting up, make sure we fully "own" this socket.
457     m_listener->m_child_lock->lock();
458     while (m_listener->m_children.find(m_sock) != m_listener->m_children.end())
459         m_listener->m_child_wait->wait(m_listener->m_child_lock.get());
460     m_listener->m_children[m_sock] = m_child;
461     m_listener->m_child_lock->unlock();
462
463     int result;
464     fd_set readfds;
465     struct timeval tv = { 0, 0 };
466
467     while(!*(m_listener->m_shutdown)) {
468         FD_ZERO(&readfds);
469         FD_SET(m_sock, &readfds);
470         tv.tv_sec = 1;
471
472         switch (select(m_sock+1, &readfds, 0, 0, &tv)) {
473 #ifdef WIN32
474         case SOCKET_ERROR:
475 #else
476         case -1:
477 #endif
478             if (errno == EINTR) continue;
479             m_listener->log_error();
480             m_listener->log->error("select() on incoming request socket (%u) returned error", m_sock);
481             return;
482
483         case 0:
484             break;
485
486         default:
487             result = job();
488             if (result) {
489                 if (result < 0) {
490                     m_listener->log_error();
491                     m_listener->log->error("I/O failure processing request on socket (%u)", m_sock);
492                 }
493                 m_listener->close(m_sock);
494                 return;
495             }
496         }
497     }
498 }
499
500 int ServerThread::job()
501 {
502     Category& log = Category::getInstance(SHIBSP_LOGCAT".Listener");
503
504     bool incomingError = true;  // set false once incoming message is received
505     ostringstream sink;
506 #ifdef WIN32
507     u_long len;
508 #else
509     uint32_t len;
510 #endif
511
512     try {
513         // Read the message.
514         int readlength = m_listener->recv(m_sock,(char*)&len,sizeof(len));
515         if (readlength == 0) {
516             log.info("detected socket closure, shutting down worker thread");
517             return 1;
518         }
519         else if (readlength != sizeof(len)) {
520             log.error("error reading size of input message");
521             return -1;
522         }
523         len = ntohl(len);
524
525         int size_read;
526         stringstream is;
527         while (len && (size_read = m_listener->recv(m_sock, m_buf, sizeof(m_buf))) > 0) {
528             is.write(m_buf, size_read);
529             len -= size_read;
530         }
531
532         if (len) {
533             log.error("error reading input message from socket");
534             return -1;
535         }
536
537         // Unmarshall the message.
538         DDF in;
539         DDFJanitor jin(in);
540         is >> in;
541
542         log.debug("dispatching message (%s)", in.name() ? in.name() : "unnamed");
543
544         incomingError = false;
545
546         // Dispatch the message.
547         m_listener->receive(in, sink);
548     }
549     catch (XMLToolingException& e) {
550         if (incomingError)
551             log.error("error processing incoming message: %s", e.what());
552         DDF out=DDF("exception").string(e.toString().c_str());
553         DDFJanitor jout(out);
554         sink << out;
555     }
556     catch (exception& e) {
557         if (incomingError)
558             log.error("error processing incoming message: %s", e.what());
559         ListenerException ex(e.what());
560         DDF out=DDF("exception").string(ex.toString().c_str());
561         DDFJanitor jout(out);
562         sink << out;
563     }
564     catch (...) {
565         if (incomingError)
566             log.error("unexpected error processing incoming message");
567         if (!m_listener->m_catchAll)
568             throw;
569         ListenerException ex("An unexpected error occurred while processing an incoming message.");
570         DDF out=DDF("exception").string(ex.toString().c_str());
571         DDFJanitor jout(out);
572         sink << out;
573     }
574
575     // Return whatever's available.
576     string response(sink.str());
577     int outlen = response.length();
578     len = htonl(outlen);
579     if (m_listener->send(m_sock,(char*)&len,sizeof(len)) != sizeof(len)) {
580         log.error("error sending output message size");
581         return -1;
582     }
583     if (m_listener->send(m_sock,response.c_str(),outlen) != outlen) {
584         log.error("error sending output message");
585         return -1;
586     }
587
588     return 0;
589 }