eee5c8b75f186d24281472f931b73f0807558b4a
[shibboleth/sp.git] / shibd / shibd.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  * shar.cpp -- the shibd "main" code.  All the functionality is elsewhere
19  *
20  * Created By:  Derek Atkins <derek@ihtfp.com>
21  *
22  * $Id: shar.cpp 2164 2007-02-11 05:26:18 +0000 (Sun, 11 Feb 2007) cantor $
23  */
24
25
26 // eventually we might be able to support autoconf via cygwin...
27 #if defined (_MSC_VER) || defined(__BORLANDC__)
28 # include "config_win32.h"
29 #else
30 # include "config.h"
31 #endif
32
33 #ifdef WIN32
34 # define _CRT_NONSTDC_NO_DEPRECATE 1
35 # define _CRT_SECURE_NO_DEPRECATE 1
36 #endif
37
38 #include <shibsp/SPConfig.h>
39
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #include <sys/select.h>
43 #endif
44
45 #include <stdio.h>
46 #include <signal.h>
47 #include <shibsp/ServiceProvider.h>
48 #include <shibsp/remoting/ListenerService.h>
49 #include <xercesc/util/XMLUniDefs.hpp>
50 #include <xmltooling/XMLToolingConfig.h>
51 #include <xmltooling/util/XMLConstants.h>
52 #include <xmltooling/util/XMLHelper.h>
53
54 using namespace shibsp;
55 using namespace xmltooling;
56 using namespace std;
57
58 bool shibd_shutdown = false;
59 const char* shar_config = NULL;
60 const char* shar_schemadir = NULL;
61 const char* shar_prefix = NULL;
62 bool shar_checkonly = false;
63 bool shar_version = false;
64 static bool unlink_socket = false;
65 const char* pidfile = NULL;
66
67 #ifdef WIN32
68
69 //#include <CRTDBG.H>
70
71 #define nNoMansLandSize 4
72 typedef struct _CrtMemBlockHeader
73 {
74         struct _CrtMemBlockHeader * pBlockHeaderNext;
75         struct _CrtMemBlockHeader * pBlockHeaderPrev;
76         char *                      szFileName;
77         int                         nLine;
78         size_t                      nDataSize;
79         int                         nBlockUse;
80         long                        lRequest;
81         unsigned char               gap[nNoMansLandSize];
82         /* followed by:
83          *  unsigned char           data[nDataSize];
84          *  unsigned char           anotherGap[nNoMansLandSize];
85          */
86 } _CrtMemBlockHeader;
87
88 /*
89 int MyAllocHook(int nAllocType, void *pvData,
90       size_t nSize, int nBlockUse, long lRequest,
91       const unsigned char * szFileName, int nLine)
92 {
93     if ( nBlockUse == _CRT_BLOCK )
94       return( TRUE );
95     if (nAllocType == _HOOK_FREE) {
96         _CrtMemBlockHeader* ptr = (_CrtMemBlockHeader*)(((_CrtMemBlockHeader *)pvData)-1);
97         if (ptr->nDataSize == 8192)
98             fprintf(stderr,"free  request %u size %u\n", ptr->lRequest, ptr->nDataSize);
99     }
100     else if (nAllocType == _HOOK_ALLOC && nSize == 8192)
101         fprintf(stderr,"%s request %u size %u\n", ((nAllocType == _HOOK_ALLOC) ? "alloc" : "realloc"), lRequest, nSize);
102     return (TRUE);
103 }
104 */
105
106 int real_main(int preinit)
107 {
108     SPConfig& conf=SPConfig::getConfig();
109     if (preinit) {
110
111         // Initialize the SP library.
112         conf.setFeatures(
113             SPConfig::Listener |
114             SPConfig::Caching |
115             SPConfig::Metadata |
116             SPConfig::Trust |
117             SPConfig::Credentials |
118             SPConfig::AttributeResolution |
119             SPConfig::Handlers |
120             SPConfig::OutOfProcess |
121             (shar_checkonly ? SPConfig::RequestMapping : SPConfig::Logging)
122             );
123         if (!conf.init(shar_schemadir, shar_prefix)) {
124             fprintf(stderr, "configuration is invalid, see console for specific problems\n");
125             return -1;
126         }
127
128         if (!conf.instantiate(shar_config)) {
129             fprintf(stderr, "configuration is invalid, check console for specific problems\n");
130             conf.term();
131             return -2;
132         }
133
134         // If just a test run, bail.
135         if (shar_checkonly) {
136             fprintf(stdout, "overall configuration is loadable, check console for non-fatal problems\n");
137             return 0;
138         }
139     }
140     else {
141
142         //_CrtSetAllocHook(MyAllocHook);
143
144         if (!shar_checkonly) {
145             // Run the listener.
146             ListenerService* listener = conf.getServiceProvider()->getListenerService();
147             if (!listener->init(unlink_socket)) {
148                 fprintf(stderr, "listener failed to initialize\n");
149                 conf.term();
150                 return -3;
151             }
152             else if (!listener->run(&shibd_shutdown)) {
153                 fprintf(stderr, "listener failed during service\n");
154                 listener->term();
155                 conf.term();
156                 return -3;
157             }
158             listener->term();
159         }
160
161         conf.term();
162     }
163     return 0;
164 }
165
166 #else
167
168 int daemon_wait = 3;
169 bool shibd_running = false;
170 bool daemonize = true;
171
172 static void term_handler(int arg)
173 {
174     shibd_shutdown = true;
175 }
176
177 static void run_handler(int arg)
178 {
179     shibd_running = true;
180 }
181
182 static void child_handler(int arg)
183 {
184     // Terminate the parent's wait/sleep if the newly born daemon dies early.
185 }
186
187 static int setup_signals(void)
188 {
189     struct sigaction sa;
190     memset(&sa, 0, sizeof (sa));
191     sa.sa_handler = SIG_IGN;
192     sa.sa_flags = SA_RESTART;
193
194     if (sigaction(SIGPIPE, &sa, NULL) < 0) {
195         return -1;
196     }
197
198     memset(&sa, 0, sizeof (sa));
199     sa.sa_handler = term_handler;
200     sa.sa_flags = SA_RESTART;
201
202     if (sigaction(SIGHUP, &sa, NULL) < 0) {
203         return -1;
204     }
205     if (sigaction(SIGINT, &sa, NULL) < 0) {
206         return -1;
207     }
208     if (sigaction(SIGQUIT, &sa, NULL) < 0) {
209         return -1;
210     }
211     if (sigaction(SIGTERM, &sa, NULL) < 0) {
212         return -1;
213     }
214
215     if (daemonize) {
216         memset(&sa, 0, sizeof (sa));
217         sa.sa_handler = run_handler;
218
219         if (sigaction(SIGUSR1, &sa, NULL) < 0) {
220             return -1;
221         }
222
223         memset(&sa, 0, sizeof (sa));
224         sa.sa_handler = child_handler;
225
226         if (sigaction(SIGCHLD, &sa, NULL) < 0) {
227             return -1;
228         }
229     }
230
231     return 0;
232 }
233
234 static void usage(char* whoami)
235 {
236     fprintf(stderr, "usage: %s [-dcxtfpvh]\n", whoami);
237     fprintf(stderr, "  -d\tinstallation prefix to use.\n");
238     fprintf(stderr, "  -c\tconfig file to use.\n");
239     fprintf(stderr, "  -x\tXML schema catalogs to use.\n");
240     fprintf(stderr, "  -t\ttest configuration file for problems.\n");
241     fprintf(stderr, "  -f\tforce removal of listener socket.\n");
242     fprintf(stderr, "  -F\tstay in the foreground.\n");
243     fprintf(stderr, "  -p\tpid file to use.\n");
244     fprintf(stderr, "  -w\tseconds to wait for successful daemonization.\n");
245     fprintf(stderr, "  -v\tprint software version.\n");
246     fprintf(stderr, "  -h\tprint this help message.\n");
247     exit(1);
248 }
249
250 static int parse_args(int argc, char* argv[])
251 {
252     int opt;
253
254     while ((opt = getopt(argc, argv, "d:c:x:p:w:fFtvh")) > 0) {
255         switch (opt) {
256             case 'd':
257                 shar_prefix=optarg;
258                 break;
259             case 'c':
260                 shar_config=optarg;
261                 break;
262             case 'x':
263                 shar_schemadir=optarg;
264                 break;
265             case 'f':
266                 unlink_socket = true;
267                 break;
268             case 'F':
269                 daemonize = false;
270                 break;
271             case 't':
272                 shar_checkonly=true;
273                 daemonize=false;
274                 break;
275             case 'v':
276                 shar_version=true;
277                 break;
278             case 'p':
279                 pidfile=optarg;
280                 break;
281             case 'w':
282                 if (optarg)
283                     daemon_wait = atoi(optarg);
284                 if (daemon_wait <= 0)
285                     daemon_wait = 3;
286                 break;
287             default:
288                 return -1;
289         }
290     }
291     return 0;
292 }
293
294 int main(int argc, char *argv[])
295 {
296     if (parse_args(argc, argv) != 0)
297         usage(argv[0]);
298     else if (shar_version) {
299         fprintf(stdout, PACKAGE_STRING"\n");
300         return 0;
301     }
302
303     if (setup_signals() != 0)
304         return -1;
305
306     // initialize the shib-target library
307     SPConfig& conf=SPConfig::getConfig();
308     conf.setFeatures(
309         SPConfig::Listener |
310         SPConfig::Caching |
311         SPConfig::Metadata |
312         SPConfig::Trust |
313         SPConfig::Credentials |
314         SPConfig::AttributeResolution |
315         SPConfig::Handlers |
316         SPConfig::OutOfProcess |
317         (shar_checkonly ? SPConfig::RequestMapping : SPConfig::Logging)
318         );
319     if (!conf.init(shar_schemadir, shar_prefix)) {
320         fprintf(stderr, "configuration is invalid, check console for specific problems\n");
321         return -1;
322     }
323
324     if (daemonize) {
325         // We must fork() early, while we're single threaded.
326         // StorageService cleanup thread is about to start.
327         switch (fork()) {
328             case 0:
329                 break;
330             case -1:
331                 perror("forking");
332                 exit(EXIT_FAILURE);
333             default:
334                 sleep(daemon_wait);
335                 exit(shibd_running ? EXIT_SUCCESS : EXIT_FAILURE);
336         }
337     }
338
339     if (!conf.instantiate(shar_config)) {
340         fprintf(stderr, "configuration is invalid, check console for specific problems\n");
341         conf.term();
342         return -2;
343     }
344
345     if (shar_checkonly)
346         fprintf(stderr, "overall configuration is loadable, check console for non-fatal problems\n");
347     else {
348         // Init the listener.
349         ListenerService* listener = conf.getServiceProvider()->getListenerService();
350         if (!listener->init(unlink_socket)) {
351             fprintf(stderr, "listener failed to initialize\n");
352             conf.term();
353             return -3;
354         }
355
356         if (daemonize) {
357             if (setsid() == -1) {
358                 perror("setsid");
359                 exit(EXIT_FAILURE);
360             }
361             if (chdir("/") == -1) {
362                 perror("chdir to root");
363                 exit(EXIT_FAILURE);
364             }
365
366             if (pidfile) {
367                 FILE* pidf = fopen(pidfile, "w");
368                 if (pidf) {
369                     fprintf(pidf, "%d\n", getpid());
370                     fclose(pidf);
371                 }
372                 else {
373                     perror(pidfile);
374                 }
375             }
376
377             freopen("/dev/null", "r", stdin);
378             freopen("/dev/null", "w", stdout);
379             freopen("/dev/null", "w", stderr);
380
381             // Signal our parent that we are A-OK.
382             kill(getppid(), SIGUSR1);
383         }
384
385         // Run the listener.
386         if (!listener->run(&shibd_shutdown)) {
387             fprintf(stderr, "listener failure during service\n");
388             listener->term();
389             conf.term();
390             if (daemonize && pidfile)
391                 unlink(pidfile);
392             return -3;
393         }
394         listener->term();
395     }
396
397     conf.term();
398     if (daemonize && pidfile)
399         unlink(pidfile);
400     return 0;
401 }
402
403 #endif