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