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