File: shibd.cpp

package info (click to toggle)
shibboleth-sp2 2.6.0%2Bdfsg1-4%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 7,896 kB
  • sloc: cpp: 39,404; sh: 11,726; makefile: 866; xml: 371; ansic: 35
file content (484 lines) | stat: -rw-r--r-- 13,485 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/**
 * Licensed to the University Corporation for Advanced Internet
 * Development, Inc. (UCAID) under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.
 *
 * UCAID licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the
 * License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

/*
 * shibd.cpp -- the shibd "main" code.
 */


// eventually we might be able to support autoconf via cygwin...
#if defined (_MSC_VER) || defined(__BORLANDC__)
# include "config_win32.h"
#else
# include "config.h"
#endif

#ifdef WIN32
# define _CRT_NONSTDC_NO_DEPRECATE 1
# define _CRT_SECURE_NO_DEPRECATE 1
#endif

#include <shibsp/SPConfig.h>

#ifdef HAVE_UNISTD_H
# include <unistd.h>
# include <sys/select.h>
#endif

#if defined(HAVE_GRP_H) && defined(HAVE_PWD_H)
# include <pwd.h>
# include <grp.h>
#endif

#include <stdio.h>
#include <signal.h>
#include <shibsp/ServiceProvider.h>
#include <shibsp/remoting/ListenerService.h>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xmltooling/XMLToolingConfig.h>
#include <xmltooling/util/XMLConstants.h>
#include <xmltooling/util/XMLHelper.h>

#ifdef HAVE_SD_NOTIFY
#include <systemd/sd-daemon.h>
#else
#define SD_EMERG   ""
#define SD_ALERT   ""
#define SD_CRIT    ""
#define SD_ERR     ""
#define SD_WARNING ""
#define SD_NOTICE  ""
#define SD_INFO    ""
#define SD_DEBUG   ""
#endif

using namespace shibsp;
using namespace xmltooling;
using namespace std;

bool shibd_shutdown = false;
const char* shar_config = nullptr;
const char* shar_schemadir = nullptr;
const char* shar_prefix = nullptr;
bool shar_checkonly = false;
bool shar_version = false;
static bool unlink_socket = false;
const char* pidfile = nullptr;

#ifdef WIN32

//#include <CRTDBG.H>

#define nNoMansLandSize 4
typedef struct _CrtMemBlockHeader
{
        struct _CrtMemBlockHeader * pBlockHeaderNext;
        struct _CrtMemBlockHeader * pBlockHeaderPrev;
        char *                      szFileName;
        int                         nLine;
        size_t                      nDataSize;
        int                         nBlockUse;
        long                        lRequest;
        unsigned char               gap[nNoMansLandSize];
        /* followed by:
         *  unsigned char           data[nDataSize];
         *  unsigned char           anotherGap[nNoMansLandSize];
         */
} _CrtMemBlockHeader;

/*
int MyAllocHook(int nAllocType, void *pvData,
      size_t nSize, int nBlockUse, long lRequest,
      const unsigned char * szFileName, int nLine)
{
    if ( nBlockUse == _CRT_BLOCK )
      return( TRUE );
    if (nAllocType == _HOOK_FREE) {
        _CrtMemBlockHeader* ptr = (_CrtMemBlockHeader*)(((_CrtMemBlockHeader *)pvData)-1);
        if (ptr->nDataSize == 8192)
            fprintf(stderr,"free  request %u size %u\n", ptr->lRequest, ptr->nDataSize);
    }
    else if (nAllocType == _HOOK_ALLOC && nSize == 8192)
        fprintf(stderr,"%s request %u size %u\n", ((nAllocType == _HOOK_ALLOC) ? "alloc" : "realloc"), lRequest, nSize);
    return (TRUE);
}
*/

int real_main(int preinit)
{
    if (shar_version) {
        if (preinit)
            fprintf(stdout, PACKAGE_STRING"\n");
        return 0;
    }

    SPConfig& conf = SPConfig::getConfig();
    if (preinit) {
        // Initialize the SP library.
        conf.setFeatures(
            SPConfig::Listener |
            SPConfig::Caching |
            SPConfig::Metadata |
            SPConfig::Trust |
            SPConfig::Credentials |
            SPConfig::AttributeResolution |
            SPConfig::Handlers |
            SPConfig::OutOfProcess |
            (shar_checkonly ? SPConfig::RequestMapping : SPConfig::Logging)
            );
        if (!conf.init(shar_schemadir, shar_prefix)) {
            fprintf(stderr, "configuration is invalid, see console for specific problems\n");
            return -1;
        }

        if (!conf.instantiate(shar_config)) {
            fprintf(stderr, "configuration is invalid, check console for specific problems\n");
            conf.term();
            return -2;
        }

        // If just a test run, bail.
        if (shar_checkonly) {
            fprintf(stdout, "overall configuration is loadable, check console for non-fatal problems\n");
            return 0;
        }
    }
    else {

        //_CrtSetAllocHook(MyAllocHook);

        if (!shar_checkonly) {
            // Run the listener.
            ListenerService* listener = conf.getServiceProvider()->getListenerService();
            if (!listener->init(unlink_socket)) {
                fprintf(stderr, "listener failed to initialize\n");
                conf.term();
                return -3;
            }
            else if (!listener->run(&shibd_shutdown)) {
                fprintf(stderr, "listener failed during service\n");
                listener->term();
                conf.term();
                return -3;
            }
            listener->term();
        }

        conf.term();
    }
    return 0;
}

#else

int daemon_wait = 3;
bool shibd_running = false;
bool daemonize = true;
const char* runasuser = nullptr;
const char* runasgroup = nullptr;

static void term_handler(int arg)
{
    shibd_shutdown = true;
}

static void run_handler(int arg)
{
    shibd_running = true;
}

static void child_handler(int arg)
{
    // Terminate the parent's wait/sleep if the newly born daemon dies early.
}

static int setup_signals(void)
{
    struct sigaction sa;
    memset(&sa, 0, sizeof (sa));
    sa.sa_handler = SIG_IGN;
    sa.sa_flags = SA_RESTART;

    if (sigaction(SIGPIPE, &sa, nullptr) < 0) {
        return -1;
    }

    memset(&sa, 0, sizeof (sa));
    sa.sa_handler = term_handler;
    sa.sa_flags = SA_RESTART;

    if (sigaction(SIGHUP, &sa, nullptr) < 0) {
        return -1;
    }
    if (sigaction(SIGINT, &sa, nullptr) < 0) {
        return -1;
    }
    if (sigaction(SIGQUIT, &sa, nullptr) < 0) {
        return -1;
    }
    if (sigaction(SIGTERM, &sa, nullptr) < 0) {
        return -1;
    }

    if (daemonize) {
        memset(&sa, 0, sizeof (sa));
        sa.sa_handler = run_handler;

        if (sigaction(SIGUSR1, &sa, nullptr) < 0) {
            return -1;
        }

        memset(&sa, 0, sizeof (sa));
        sa.sa_handler = child_handler;

        if (sigaction(SIGCHLD, &sa, nullptr) < 0) {
            return -1;
        }
    }

    return 0;
}

static void usage(char* whoami)
{
    fprintf(stderr, "usage: %s [-dcxtfFpwugvh]\n", whoami);
    fprintf(stderr, "  -d\tinstallation prefix to use\n");
    fprintf(stderr, "  -c\tconfig file to use\n");
    fprintf(stderr, "  -x\tXML schema catalogs to use\n");
    fprintf(stderr, "  -t\ttest configuration file for problems\n");
    fprintf(stderr, "  -f\tforce removal of listener socket\n");
    fprintf(stderr, "  -F\tstay in the foreground\n");
    fprintf(stderr, "  -p\tpid file to use\n");
    fprintf(stderr, "  -w\tseconds to wait for successful daemonization\n");
    fprintf(stderr, "  -u\tuser to run under\n");
    fprintf(stderr, "  -g\tgroup to run under\n");
    fprintf(stderr, "  -v\tprint software version\n");
    fprintf(stderr, "  -h\tprint this help message\n");
    exit(1);
}

static int parse_args(int argc, char* argv[])
{
    int opt;

    while ((opt = getopt(argc, argv, "d:c:x:p:w:u:g:fFtvh")) > 0) {
        switch (opt) {
            case 'd':
                shar_prefix=optarg;
                break;
            case 'c':
                shar_config=optarg;
                break;
            case 'x':
                shar_schemadir=optarg;
                break;
            case 'f':
                unlink_socket = true;
                break;
            case 'F':
                daemonize = false;
                break;
            case 't':
                shar_checkonly=true;
                daemonize=false;
                break;
            case 'v':
                shar_version=true;
                break;
            case 'p':
                pidfile=optarg;
                break;
            case 'w':
                if (optarg)
                    daemon_wait = atoi(optarg);
                if (daemon_wait <= 0)
                    daemon_wait = 3;
                break;
            case 'u':
                if (optarg)
                    runasuser = optarg;
                break;
            case 'g':
                if (optarg)
                    runasgroup = optarg;
                break;
            default:
                return -1;
        }
    }
    return 0;
}

int main(int argc, char *argv[])
{
    if (parse_args(argc, argv) != 0)
        usage(argv[0]);
    else if (shar_version) {
        fprintf(stdout, PACKAGE_STRING"\n");
        return 0;
    }

    if (setup_signals() != 0)
        return -1;

    if (runasgroup) {
#ifdef HAVE_GETGRNAM
        struct group* grp = getgrnam(runasgroup);
        if (!grp) {
            fprintf(stderr, "getgrnam failed, check -g option\n");
            return -1;
        }
        if (setgid(grp->gr_gid) != 0) {
            fprintf(stderr, "setgid failed, check -g option\n");
            return -1;
        }
#else
        fprintf(stderr, "-g not supported on this platform");
        return -1;
#endif
    }

    if (runasuser) {
#ifdef HAVE_GETPWNAM
        struct passwd* pwd = getpwnam(runasuser);
        if (!pwd) {
            fprintf(stderr, "getpwnam failed, check -u option\n");
            return -1;
        }
#ifdef HAVE_INITGROUPS
        // w/out initgroups/setgroups process retains supplementary groups
        if (initgroups(pwd->pw_name, pwd->pw_gid) != 0) {
            fprintf(stderr, "initgroups failed, check -u option\n");
            return -1;
        }
#endif
        if (setuid(pwd->pw_uid) != 0) {
            fprintf(stderr, "setuid failed, check -u option\n");
            return -1;
        }
#else
        fprintf(stderr, "-u not supported on this platform");
        return -1;
#endif
    }

    // initialize the shib-target library
    SPConfig& conf=SPConfig::getConfig();
    conf.setFeatures(
        SPConfig::Listener |
        SPConfig::Caching |
        SPConfig::Metadata |
        SPConfig::Trust |
        SPConfig::Credentials |
        SPConfig::AttributeResolution |
        SPConfig::Handlers |
        SPConfig::OutOfProcess |
        (shar_checkonly ? SPConfig::RequestMapping : SPConfig::Logging)
        );
    if (!conf.init(shar_schemadir, shar_prefix)) {
        fprintf(stderr, SD_ERR "configuration is invalid, check console for specific problems\n");
        return -1;
    }

    if (daemonize) {
        // We must fork() early, while we're single threaded.
        // StorageService cleanup thread is about to start.
        switch (fork()) {
            case 0:
                break;
            case -1:
                perror("forking");
                exit(EXIT_FAILURE);
            default:
                sleep(daemon_wait);
                exit(shibd_running ? EXIT_SUCCESS : EXIT_FAILURE);
        }
    }

    if (!conf.instantiate(shar_config)) {
        fprintf(stderr, SD_ERR "configuration is invalid, check console for specific problems\n");
        conf.term();
        return -2;
    }

    if (shar_checkonly)
        fprintf(stderr, "overall configuration is loadable, check console for non-fatal problems\n");
    else {
        // Init the listener.
        ListenerService* listener = conf.getServiceProvider()->getListenerService();
        if (!listener->init(unlink_socket)) {
            fprintf(stderr, SD_ERR "listener failed to initialize\n");
            conf.term();
            return -3;
        }

        if (daemonize) {
            if (setsid() == -1) {
                perror("setsid");
                exit(EXIT_FAILURE);
            }
            if (chdir("/") == -1) {
                perror("chdir to root");
                exit(EXIT_FAILURE);
            }

            if (pidfile) {
                FILE* pidf = fopen(pidfile, "w");
                if (pidf) {
                    fprintf(pidf, "%d\n", getpid());
                    fclose(pidf);
                }
                else {
                    perror(pidfile);
                }
            }

            freopen("/dev/null", "r", stdin);
            freopen("/dev/null", "w", stdout);
            freopen("/dev/null", "w", stderr);

            // Signal our parent that we are A-OK.
            kill(getppid(), SIGUSR1);
        }

        // Run the listener.
#ifdef HAVE_SD_NOTIFY
        sd_notify(0, "READY=1");
#endif
        if (!listener->run(&shibd_shutdown)) {
            fprintf(stderr, SD_ERR "listener failure during service\n");
            listener->term();
            conf.term();
            if (daemonize && pidfile)
                unlink(pidfile);
            return -3;
        }
        listener->term();
    }
#ifdef HAVE_SD_NOTIFY
    sd_notify(0, "STOPPING=1");
#endif
    conf.term();
    if (daemonize && pidfile)
        unlink(pidfile);
    return 0;
}

#endif