https://issues.shibboleth.net/jira/browse/SSPCPP-206
[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) : m_catchAll(false), log(&Category::getInstance(SHIBSP_LOGCAT".Listener")),
162     m_socketpool(NULL), m_shutdown(NULL), m_child_lock(NULL), m_child_wait(NULL), m_socket((ShibSocket)0)
163 {
164     // Are we a client?
165     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
166         m_socketpool=new SocketPool(*log,this);
167     }
168     // Are we a server?
169     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
170         m_child_lock = Mutex::create();
171         m_child_wait = CondWait::create();
172     }
173 }
174
175 SocketListener::~SocketListener()
176 {
177     delete m_socketpool;
178     delete m_child_wait;
179     delete m_child_lock;
180 }
181
182 bool SocketListener::run(bool force, bool* shutdown)
183 {
184 #ifdef _DEBUG
185     NDC ndc("run");
186 #endif
187     log->info("listener service starting");
188
189     ServiceProvider* sp = SPConfig::getConfig().getServiceProvider();
190     sp->lock();
191     const PropertySet* props = sp->getPropertySet("OutOfProcess");
192     if (props) {
193         pair<bool,bool> flag = props->getBool("catchAll");
194         m_catchAll = flag.first && flag.second;
195     }
196     sp->unlock();
197
198     // Save flag to monitor for shutdown request.
199     m_shutdown=shutdown;
200     unsigned long count = 0;
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     while (!*m_shutdown) {
213         fd_set readfds;
214         FD_ZERO(&readfds);
215         FD_SET(m_socket, &readfds);
216         struct timeval tv = { 0, 0 };
217         tv.tv_sec = 5;
218
219         switch (select(m_socket + 1, &readfds, 0, 0, &tv)) {
220 #ifdef WIN32
221             case SOCKET_ERROR:
222 #else
223             case -1:
224 #endif
225                 if (errno == EINTR) continue;
226                 log_error();
227                 log->error("select() on main listener socket failed");
228                 return false;
229
230             case 0:
231                 continue;
232
233             default:
234             {
235                 // Accept the connection.
236                 SocketListener::ShibSocket newsock;
237                 if (!accept(m_socket, newsock)) {
238                     log->crit("failed to accept incoming socket connection");
239                     continue;
240                 }
241
242                 // We throw away the result because the children manage themselves...
243                 try {
244                     new ServerThread(newsock,this,++count);
245                 }
246                 catch (exception& ex) {
247                     log->crit("exception starting new server thread to service incoming request: %s", ex.what());
248                 }
249                 catch (...) {
250                     log->crit("unknown error starting new server thread to service incoming request");
251                     if (!m_catchAll)
252                         *m_shutdown = true;
253                 }
254             }
255         }
256     }
257     log->info("listener service shutting down");
258
259     // Wait for all children to exit.
260     m_child_lock->lock();
261     while (!m_children.empty())
262         m_child_wait->wait(m_child_lock);
263     m_child_lock->unlock();
264
265     this->close(m_socket);
266     m_socket=(ShibSocket)0;
267     return true;
268 }
269
270 DDF SocketListener::send(const DDF& in)
271 {
272 #ifdef _DEBUG
273     NDC ndc("send");
274 #endif
275
276     log->debug("sending message (%s)", in.name() ? in.name() : "unnamed");
277
278     // Serialize data for transmission.
279     ostringstream os;
280     os << in;
281     string ostr(os.str());
282
283     // Loop on the RPC in case we lost contact the first time through
284 #ifdef WIN32
285     u_long len;
286 #else
287     uint32_t len;
288 #endif
289     int retry = 1;
290     SocketListener::ShibSocket sock;
291     while (retry >= 0) {
292         sock = m_socketpool->get();
293
294         int outlen = ostr.length();
295         len = htonl(outlen);
296         if (send(sock,(char*)&len,sizeof(len)) != sizeof(len) || send(sock,ostr.c_str(),outlen) != outlen) {
297             log_error();
298             this->close(sock);
299             if (retry)
300                 retry--;
301             else
302                 throw ListenerException("Failure sending remoted message ($1).", params(1,in.name()));
303         }
304         else {
305             // SUCCESS.
306             retry = -1;
307         }
308     }
309
310     log->debug("send completed, reading response message");
311
312     // Read the message.
313     while (recv(sock,(char*)&len,sizeof(len)) != sizeof(len)) {
314         if (errno == EINTR) continue;   // Apparently this happens when a signal interrupts the blocking call.
315         log->error("error reading size of output message");
316         this->close(sock);
317         throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
318     }
319     len = ntohl(len);
320
321     char buf[16384];
322     int size_read;
323     stringstream is;
324     while (len) {
325         size_read = recv(sock, buf, sizeof(buf));
326         if (size_read > 0) {
327             is.write(buf, size_read);
328             len -= size_read;
329         }
330         else if (errno != EINTR) {
331                 break;
332         }
333     }
334
335     if (len) {
336         log->error("error reading output message from socket");
337         this->close(sock);
338         throw ListenerException("Failure receiving response to remoted message ($1).", params(1,in.name()));
339     }
340
341     m_socketpool->put(sock);
342
343     // Unmarshall data.
344     DDF out;
345     is >> out;
346
347     // Check for exception to unmarshall and throw, otherwise return.
348     if (out.isstring() && out.name() && !strcmp(out.name(),"exception")) {
349         // Reconstitute exception object.
350         DDFJanitor jout(out);
351         XMLToolingException* except=NULL;
352         try {
353             except=XMLToolingException::fromString(out.string());
354             log->error("remoted message returned an error: %s", except->what());
355         }
356         catch (XMLToolingException& e) {
357             log->error("caught XMLToolingException while building the XMLToolingException: %s", e.what());
358             log->error("XML was: %s", out.string());
359             throw ListenerException("Remote call failed with an unparsable exception.");
360         }
361
362         auto_ptr<XMLToolingException> wrapper(except);
363         wrapper->raise();
364     }
365
366     return out;
367 }
368
369 bool SocketListener::log_error() const
370 {
371 #ifdef WIN32
372     int rc=WSAGetLastError();
373 #else
374     int rc=errno;
375 #endif
376 #ifdef HAVE_STRERROR_R
377     char buf[256];
378     memset(buf,0,sizeof(buf));
379     strerror_r(rc,buf,sizeof(buf));
380     log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
381 #else
382     const char* buf=strerror(rc);
383     log->error("socket call resulted in error (%d): %s",rc,isprint(*buf) ? buf : "no message");
384 #endif
385     return false;
386 }
387
388 // actual function run in listener on server threads
389 void* server_thread_fn(void* arg)
390 {
391     ServerThread* child = (ServerThread*)arg;
392
393 #ifndef WIN32
394     // First, let's block all signals
395     Thread::mask_all_signals();
396 #endif
397
398     // Run the child until it exits.
399     child->run();
400
401     // Now we can clean up and exit the thread.
402     delete child;
403     return NULL;
404 }
405
406 ServerThread::ServerThread(SocketListener::ShibSocket& s, SocketListener* listener, unsigned long id)
407     : m_sock(s), m_child(NULL), m_listener(listener)
408 {
409
410     ostringstream buf;
411     buf << "[" << id << "]";
412     m_id = buf.str();
413
414     // Create the child thread
415     m_child = Thread::create(server_thread_fn, (void*)this);
416     m_child->detach();
417 }
418
419 ServerThread::~ServerThread()
420 {
421     // Then lock the children map, remove this socket/thread, signal waiters, and return
422     m_listener->m_child_lock->lock();
423     m_listener->m_children.erase(m_sock);
424     m_listener->m_child_lock->unlock();
425     m_listener->m_child_wait->signal();
426
427     delete m_child;
428 }
429
430 void ServerThread::run()
431 {
432     NDC ndc(m_id);
433
434     // Before starting up, make sure we fully "own" this socket.
435     m_listener->m_child_lock->lock();
436     while (m_listener->m_children.find(m_sock)!=m_listener->m_children.end())
437         m_listener->m_child_wait->wait(m_listener->m_child_lock);
438     m_listener->m_children[m_sock] = m_child;
439     m_listener->m_child_lock->unlock();
440
441     int result;
442     fd_set readfds;
443     struct timeval tv = { 0, 0 };
444
445     while(!*(m_listener->m_shutdown)) {
446         FD_ZERO(&readfds);
447         FD_SET(m_sock, &readfds);
448         tv.tv_sec = 1;
449
450         switch (select(m_sock+1, &readfds, 0, 0, &tv)) {
451 #ifdef WIN32
452         case SOCKET_ERROR:
453 #else
454         case -1:
455 #endif
456             if (errno == EINTR) continue;
457             m_listener->log_error();
458             m_listener->log->error("select() on incoming request socket (%u) returned error", m_sock);
459             return;
460
461         case 0:
462             break;
463
464         default:
465             result = job();
466             if (result) {
467                 if (result < 0) {
468                     m_listener->log_error();
469                     m_listener->log->error("I/O failure processing request on socket (%u)", m_sock);
470                 }
471                 m_listener->close(m_sock);
472                 return;
473             }
474         }
475     }
476 }
477
478 int ServerThread::job()
479 {
480     Category& log = Category::getInstance(SHIBSP_LOGCAT".Listener");
481
482     bool incomingError = true;  // set false once incoming message is received
483     ostringstream sink;
484 #ifdef WIN32
485     u_long len;
486 #else
487     uint32_t len;
488 #endif
489
490     try {
491         // Read the message.
492         int readlength = m_listener->recv(m_sock,(char*)&len,sizeof(len));
493         if (readlength == 0) {
494             log.info("detected socket closure, shutting down worker thread");
495             return 1;
496         }
497         else if (readlength != sizeof(len)) {
498             log.error("error reading size of input message");
499             return -1;
500         }
501         len = ntohl(len);
502
503         int size_read;
504         stringstream is;
505         while (len && (size_read = m_listener->recv(m_sock, m_buf, sizeof(m_buf))) > 0) {
506             is.write(m_buf, size_read);
507             len -= size_read;
508         }
509
510         if (len) {
511             log.error("error reading input message from socket");
512             return -1;
513         }
514
515         // Unmarshall the message.
516         DDF in;
517         DDFJanitor jin(in);
518         is >> in;
519
520         log.debug("dispatching message (%s)", in.name() ? in.name() : "unnamed");
521
522         incomingError = false;
523
524         // Dispatch the message.
525         m_listener->receive(in, sink);
526     }
527     catch (XMLToolingException& e) {
528         if (incomingError)
529             log.error("error processing incoming message: %s", e.what());
530         DDF out=DDF("exception").string(e.toString().c_str());
531         DDFJanitor jout(out);
532         sink << out;
533     }
534     catch (exception& e) {
535         if (incomingError)
536             log.error("error processing incoming message: %s", e.what());
537         ListenerException ex(e.what());
538         DDF out=DDF("exception").string(ex.toString().c_str());
539         DDFJanitor jout(out);
540         sink << out;
541     }
542     catch (...) {
543         if (incomingError)
544             log.error("unexpected error processing incoming message");
545         if (!m_listener->m_catchAll)
546             throw;
547         ListenerException ex("An unexpected error occurred while processing an incoming message.");
548         DDF out=DDF("exception").string(ex.toString().c_str());
549         DDFJanitor jout(out);
550         sink << out;
551     }
552
553     // Return whatever's available.
554     string response(sink.str());
555     int outlen = response.length();
556     len = htonl(outlen);
557     if (m_listener->send(m_sock,(char*)&len,sizeof(len)) != sizeof(len)) {
558         log.error("error sending output message size");
559         return -1;
560     }
561     if (m_listener->send(m_sock,response.c_str(),outlen) != outlen) {
562         log.error("error sending output message");
563         return -1;
564     }
565
566     return 0;
567 }