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