]> git.sur5r.net Git - openldap/blob - servers/slapd/main.c
Fix insecure chroot (coverity)
[openldap] / servers / slapd / main.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2014 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms are permitted
19  * provided that this notice is preserved and that due credit is given
20  * to the University of Michigan at Ann Arbor. The name of the University
21  * may not be used to endorse or promote products derived from this
22  * software without specific prior written permission. This software
23  * is provided ``as is'' without express or implied warranty.
24  */
25
26 #include "portable.h"
27
28 #include <stdio.h>
29
30 #include <ac/ctype.h>
31 #include <ac/socket.h>
32 #include <ac/string.h>
33 #include <ac/time.h>
34 #include <ac/unistd.h>
35 #include <ac/wait.h>
36 #include <ac/errno.h>
37
38 #include "slap.h"
39 #include "lutil.h"
40 #include "ldif.h"
41
42 #ifdef LDAP_SLAPI
43 #include "slapi/slapi.h"
44 #endif
45
46 #ifdef LDAP_SIGCHLD
47 static RETSIGTYPE wait4child( int sig );
48 #endif
49
50 #ifdef HAVE_NT_SERVICE_MANAGER
51 #define MAIN_RETURN(x) return
52 static struct sockaddr_in       bind_addr;
53
54 #define SERVICE_EXIT( e, n )    do { \
55         if ( is_NT_Service ) { \
56                 lutil_ServiceStatus.dwWin32ExitCode                             = (e); \
57                 lutil_ServiceStatus.dwServiceSpecificExitCode   = (n); \
58         } \
59 } while ( 0 )
60
61 #else
62 #define SERVICE_EXIT( e, n )
63 #define MAIN_RETURN(x) return(x)
64 #endif
65
66 typedef int (MainFunc) LDAP_P(( int argc, char *argv[] ));
67 extern MainFunc slapadd, slapcat, slapdn, slapindex, slappasswd,
68         slaptest, slapauth, slapacl, slapschema;
69
70 static struct {
71         char *name;
72         MainFunc *func;
73 } tools[] = {
74         {"slapadd", slapadd},
75         {"slapcat", slapcat},
76         {"slapdn", slapdn},
77         {"slapindex", slapindex},
78         {"slappasswd", slappasswd},
79         {"slapschema", slapschema},
80         {"slaptest", slaptest},
81         {"slapauth", slapauth},
82         {"slapacl", slapacl},
83         /* NOTE: new tools must be added in chronological order,
84          * not in alphabetical order, because for backwards
85          * compatibility name[4] is used to identify the
86          * tools; so name[4]=='a' must refer to "slapadd" and
87          * not to "slapauth".  Alphabetical order can be used
88          * for tools whose name[4] is not used yet */
89         {NULL, NULL}
90 };
91
92 /*
93  * when more than one slapd is running on one machine, each one might have
94  * it's own LOCAL for syslogging and must have its own pid/args files
95  */
96
97 #ifndef HAVE_MKVERSION
98 const char Versionstr[] =
99         OPENLDAP_PACKAGE " " OPENLDAP_VERSION " Standalone LDAP Server (slapd)";
100 #endif
101
102 extern OverlayInit slap_oinfo[];
103 extern BackendInfo slap_binfo[];
104
105 #define CHECK_NONE      0x00
106 #define CHECK_CONFIG    0x01
107 #define CHECK_LOGLEVEL  0x02
108 static int check = CHECK_NONE;
109 static int version = 0;
110
111 void *slap_tls_ctx;
112 LDAP *slap_tls_ld;
113
114 static int
115 slapd_opt_slp( const char *val, void *arg )
116 {
117 #ifdef HAVE_SLP
118         /* NULL is default */
119         if ( val == NULL || *val == '(' || strcasecmp( val, "on" ) == 0 ) {
120                 slapd_register_slp = 1;
121                 slapd_slp_attrs = (val != NULL && *val == '(') ? val : NULL;
122
123         } else if ( strcasecmp( val, "off" ) == 0 ) {
124                 slapd_register_slp = 0;
125
126         /* NOTE: add support for URL specification? */
127
128         } else {
129                 fprintf(stderr, "unrecognized value \"%s\" for SLP option\n", val );
130                 return -1;
131         }
132
133         return 0;
134                 
135 #else
136         fputs( "slapd: SLP support is not available\n", stderr );
137         return 0;
138 #endif
139 }
140
141 /*
142  * Option helper structure:
143  * 
144  * oh_nam       is left-hand part of <option>[=<value>]
145  * oh_fnc       is handler function
146  * oh_arg       is an optional arg to oh_fnc
147  * oh_usage     is the one-line usage string related to the option,
148  *              which is assumed to start with <option>[=<value>]
149  *
150  * please leave valid options in the structure, and optionally #ifdef
151  * their processing inside the helper, so that reasonable and helpful
152  * error messages can be generated if a disabled option is requested.
153  */
154 struct option_helper {
155         struct berval   oh_name;
156         int             (*oh_fnc)(const char *val, void *arg);
157         void            *oh_arg;
158         const char      *oh_usage;
159 } option_helpers[] = {
160         { BER_BVC("slp"),       slapd_opt_slp,  NULL, "slp[={on|off|(attrs)}] enable/disable SLP using (attrs)" },
161         { BER_BVNULL, 0, NULL, NULL }
162 };
163
164 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
165 #ifdef LOG_LOCAL4
166 int
167 parse_syslog_user( const char *arg, int *syslogUser )
168 {
169         static slap_verbmasks syslogUsers[] = {
170                 { BER_BVC( "LOCAL0" ), LOG_LOCAL0 },
171                 { BER_BVC( "LOCAL1" ), LOG_LOCAL1 },
172                 { BER_BVC( "LOCAL2" ), LOG_LOCAL2 },
173                 { BER_BVC( "LOCAL3" ), LOG_LOCAL3 },
174                 { BER_BVC( "LOCAL4" ), LOG_LOCAL4 },
175                 { BER_BVC( "LOCAL5" ), LOG_LOCAL5 },
176                 { BER_BVC( "LOCAL6" ), LOG_LOCAL6 },
177                 { BER_BVC( "LOCAL7" ), LOG_LOCAL7 },
178 #ifdef LOG_USER
179                 { BER_BVC( "USER" ), LOG_USER },
180 #endif /* LOG_USER */
181 #ifdef LOG_DAEMON
182                 { BER_BVC( "DAEMON" ), LOG_DAEMON },
183 #endif /* LOG_DAEMON */
184                 { BER_BVNULL, 0 }
185         };
186         int i = verb_to_mask( arg, syslogUsers );
187
188         if ( BER_BVISNULL( &syslogUsers[ i ].word ) ) {
189                 Debug( LDAP_DEBUG_ANY,
190                         "unrecognized syslog user \"%s\".\n",
191                         arg, 0, 0 );
192                 return 1;
193         }
194
195         *syslogUser = syslogUsers[ i ].mask;
196
197         return 0;
198 }
199 #endif /* LOG_LOCAL4 */
200
201 int
202 parse_syslog_level( const char *arg, int *levelp )
203 {
204         static slap_verbmasks   str2syslog_level[] = {
205                 { BER_BVC( "EMERG" ),   LOG_EMERG },
206                 { BER_BVC( "ALERT" ),   LOG_ALERT },
207                 { BER_BVC( "CRIT" ),    LOG_CRIT },
208                 { BER_BVC( "ERR" ),     LOG_ERR },
209                 { BER_BVC( "WARNING" ), LOG_WARNING },
210                 { BER_BVC( "NOTICE" ),  LOG_NOTICE },
211                 { BER_BVC( "INFO" ),    LOG_INFO },
212                 { BER_BVC( "DEBUG" ),   LOG_DEBUG },
213                 { BER_BVNULL, 0 }
214         };
215         int i = verb_to_mask( arg, str2syslog_level );
216         if ( BER_BVISNULL( &str2syslog_level[ i ].word ) ) {
217                 Debug( LDAP_DEBUG_ANY,
218                         "unknown syslog level \"%s\".\n",
219                         arg, 0, 0 );
220                 return 1;
221         }
222         
223         *levelp = str2syslog_level[ i ].mask;
224
225         return 0;
226 }
227 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
228
229 int
230 parse_debug_unknowns( char **unknowns, int *levelp )
231 {
232         int i, level, rc = 0;
233
234         for ( i = 0; unknowns[ i ] != NULL; i++ ) {
235                 level = 0;
236                 if ( str2loglevel( unknowns[ i ], &level )) {
237                         fprintf( stderr,
238                                 "unrecognized log level \"%s\"\n", unknowns[ i ] );
239                         rc = 1;
240                 } else {
241                         *levelp |= level;
242                 }
243         }
244         return rc;
245 }
246
247 int
248 parse_debug_level( const char *arg, int *levelp, char ***unknowns )
249 {
250         int     level;
251
252         if ( arg && arg[ 0 ] != '-' && !isdigit( (unsigned char) arg[ 0 ] ) )
253         {
254                 int     i;
255                 char    **levels;
256
257                 levels = ldap_str2charray( arg, "," );
258
259                 for ( i = 0; levels[ i ] != NULL; i++ ) {
260                         level = 0;
261
262                         if ( str2loglevel( levels[ i ], &level ) ) {
263                                 /* remember this for later */
264                                 ldap_charray_add( unknowns, levels[ i ] );
265                                 fprintf( stderr,
266                                         "unrecognized log level \"%s\" (deferred)\n",
267                                         levels[ i ] );
268                         } else {
269                                 *levelp |= level;
270                         }
271                 }
272
273                 ldap_charray_free( levels );
274
275         } else {
276                 int rc;
277
278                 if ( arg[0] == '-' ) {
279                         rc = lutil_atoix( &level, arg, 0 );
280                 } else {
281                         unsigned ulevel;
282
283                         rc = lutil_atoux( &ulevel, arg, 0 );
284                         level = (int)ulevel;
285                 }
286
287                 if ( rc ) {
288                         fprintf( stderr,
289                                 "unrecognized log level "
290                                 "\"%s\"\n", arg );
291                         return 1;
292                 }
293
294                 if ( level == 0 ) {
295                         *levelp = 0;
296
297                 } else {
298                         *levelp |= level;
299                 }
300         }
301
302         return 0;
303 }
304
305 static void
306 usage( char *name )
307 {
308         fprintf( stderr,
309                 "usage: %s options\n", name );
310         fprintf( stderr,
311                 "\t-4\t\tIPv4 only\n"
312                 "\t-6\t\tIPv6 only\n"
313                 "\t-T {acl|add|auth|cat|dn|index|passwd|test}\n"
314                 "\t\t\tRun in Tool mode\n"
315                 "\t-c cookie\tSync cookie of consumer\n"
316                 "\t-d level\tDebug level" "\n"
317                 "\t-f filename\tConfiguration file\n"
318                 "\t-F dir\tConfiguration directory\n"
319 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
320                 "\t-g group\tGroup (id or name) to run as\n"
321 #endif
322                 "\t-h URLs\t\tList of URLs to serve\n"
323 #ifdef SLAP_DEFAULT_SYSLOG_USER
324                 "\t-l facility\tSyslog facility (default: LOCAL4)\n"
325 #endif
326                 "\t-n serverName\tService name\n"
327                 "\t-o <opt>[=val] generic means to specify options" );
328         if ( !BER_BVISNULL( &option_helpers[0].oh_name ) ) {
329                 int     i;
330
331                 fprintf( stderr, "; supported options:\n" );
332                 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++) {
333                         fprintf( stderr, "\t\t%s\n", option_helpers[i].oh_usage );
334                 }
335         } else {
336                 fprintf( stderr, "\n" );
337         }
338         fprintf( stderr,        
339 #ifdef HAVE_CHROOT
340                 "\t-r directory\tSandbox directory to chroot to\n"
341 #endif
342                 "\t-s level\tSyslog level\n"
343 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
344                 "\t-u user\t\tUser (id or name) to run as\n"
345 #endif
346                 "\t-V\t\tprint version info (-VV exit afterwards, -VVV print\n"
347                 "\t\t\tinfo about static overlays and backends)\n"
348     );
349 }
350
351 #ifdef HAVE_NT_SERVICE_MANAGER
352 void WINAPI ServiceMain( DWORD argc, LPTSTR *argv )
353 #else
354 int main( int argc, char **argv )
355 #endif
356 {
357         int             i, no_detach = 0;
358         int             rc = 1;
359         char *urls = NULL;
360 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
361         char *username = NULL;
362         char *groupname = NULL;
363 #endif
364 #if defined(HAVE_CHROOT)
365         char *sandbox = NULL;
366 #endif
367 #ifdef SLAP_DEFAULT_SYSLOG_USER
368         int syslogUser = SLAP_DEFAULT_SYSLOG_USER;
369 #endif
370         
371 #ifndef HAVE_WINSOCK
372         int pid, waitfds[2];
373 #endif
374         int g_argc = argc;
375         char **g_argv = argv;
376
377         char *configfile = NULL;
378         char *configdir = NULL;
379         char *serverName;
380         int serverMode = SLAP_SERVER_MODE;
381
382         struct sync_cookie *scp = NULL;
383         struct sync_cookie *scp_entry = NULL;
384
385         char **debug_unknowns = NULL;
386         char **syslog_unknowns = NULL;
387
388         char *serverNamePrefix = "";
389         size_t  l;
390
391         int slapd_pid_file_unlink = 0, slapd_args_file_unlink = 0;
392         int firstopt = 1;
393
394 #ifdef CSRIMALLOC
395         FILE *leakfile;
396         if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
397                 leakfile = stderr;
398         }
399 #endif
400
401         slap_sl_mem_init();
402
403         (void) ldap_pvt_thread_initialize();
404
405         serverName = lutil_progname( "slapd", argc, argv );
406
407         if ( strcmp( serverName, "slapd" ) ) {
408                 for (i=0; tools[i].name; i++) {
409                         if ( !strcmp( serverName, tools[i].name ) ) {
410                                 rc = tools[i].func(argc, argv);
411                                 MAIN_RETURN(rc);
412                         }
413                 }
414         }
415
416 #ifdef HAVE_NT_SERVICE_MANAGER
417         {
418                 int *ip;
419                 char *newConfigFile;
420                 char *newConfigDir;
421                 char *newUrls;
422                 char *regService = NULL;
423
424                 if ( is_NT_Service ) {
425                         lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
426                         if ( strcmp(serverName, SERVICE_NAME) )
427                             regService = serverName;
428                 }
429
430                 ip = (int*)lutil_getRegParam( regService, "DebugLevel" );
431                 if ( ip != NULL ) {
432                         slap_debug = *ip;
433                         Debug( LDAP_DEBUG_ANY,
434                                 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
435                 }
436
437                 newUrls = (char *) lutil_getRegParam(regService, "Urls");
438                 if (newUrls) {
439                     if (urls)
440                         ch_free(urls);
441
442                     urls = ch_strdup(newUrls);
443                     Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
444                                 urls, 0, 0);
445                 }
446
447                 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
448                 if ( newConfigFile != NULL ) {
449                         configfile = ch_strdup(newConfigFile);
450                         Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
451                 }
452
453                 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
454                 if ( newConfigDir != NULL ) {
455                         configdir = ch_strdup(newConfigDir);
456                         Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
457                 }
458         }
459 #endif
460
461         while ( (i = getopt( argc, argv,
462                              "c:d:f:F:h:n:o:s:tT:V"
463 #ifdef LDAP_PF_INET6
464                                 "46"
465 #endif
466 #ifdef HAVE_CHROOT
467                                 "r:"
468 #endif
469 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
470                                 "S:"
471 #ifdef LOG_LOCAL4
472                                 "l:"
473 #endif
474 #endif
475 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
476                                 "u:g:"
477 #endif
478                              )) != EOF ) {
479                 switch ( i ) {
480 #ifdef LDAP_PF_INET6
481                 case '4':
482                         slap_inet4or6 = AF_INET;
483                         break;
484                 case '6':
485                         slap_inet4or6 = AF_INET6;
486                         break;
487 #endif
488
489                 case 'h':       /* listen URLs */
490                         if ( urls != NULL ) free( urls );
491                         urls = ch_strdup( optarg );
492                         break;
493
494                 case 'c':       /* provide sync cookie, override if exist in replica */
495                         scp = (struct sync_cookie *) ch_calloc( 1,
496                                                                                 sizeof( struct sync_cookie ));
497                         ber_str2bv( optarg, 0, 1, &scp->octet_str );
498                         
499                         /* This only parses out the rid at this point */
500                         slap_parse_sync_cookie( scp, NULL );
501
502                         if ( scp->rid == -1 ) {
503                                 Debug( LDAP_DEBUG_ANY,
504                                                 "main: invalid cookie \"%s\"\n",
505                                                 optarg, 0, 0 );
506                                 slap_sync_cookie_free( scp, 1 );
507                                 goto destroy;
508                         }
509
510                         LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
511                                 if ( scp->rid == scp_entry->rid ) {
512                                         Debug( LDAP_DEBUG_ANY,
513                                                     "main: duplicated replica id in cookies\n",
514                                                         0, 0, 0 );
515                                         slap_sync_cookie_free( scp, 1 );
516                                         goto destroy;
517                                 }
518                         }
519                         LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
520                         break;
521
522                 case 'd': {     /* set debug level and 'do not detach' flag */
523                         int     level = 0;
524
525                         if ( strcmp( optarg, "?" ) == 0 ) {
526                                 check |= CHECK_LOGLEVEL;
527                                 break;
528                         }
529
530                         no_detach = 1;
531                         if ( parse_debug_level( optarg, &level, &debug_unknowns ) ) {
532                                 goto destroy;
533                         }
534 #ifdef LDAP_DEBUG
535                         slap_debug |= level;
536 #else
537                         if ( level != 0 )
538                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
539                                        stderr );
540 #endif
541                         } break;
542
543                 case 'f':       /* read config file */
544                         configfile = ch_strdup( optarg );
545                         break;
546
547                 case 'F':       /* use config dir */
548                         configdir = ch_strdup( optarg );
549                         break;
550
551                 case 'o': {
552                         char            *val = strchr( optarg, '=' );
553                         struct berval   opt;
554
555                         opt.bv_val = optarg;
556                         
557                         if ( val ) {
558                                 opt.bv_len = ( val - optarg );
559                                 val++;
560                         
561                         } else {
562                                 opt.bv_len = strlen( optarg );
563                         }
564
565                         for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
566                                 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
567                                         assert( option_helpers[i].oh_fnc != NULL );
568                                         if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
569                                                 /* we assume the option parsing helper
570                                                  * issues appropriate and self-explanatory
571                                                  * error messages... */
572                                                 goto stop;
573                                         }
574                                         break;
575                                 }
576                         }
577
578                         if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
579                                 goto unhandled_option;
580                         }
581                         break;
582                 }
583
584                 case 's':       /* set syslog level */
585                         if ( strcmp( optarg, "?" ) == 0 ) {
586                                 check |= CHECK_LOGLEVEL;
587                                 break;
588                         }
589
590                         if ( parse_debug_level( optarg, &ldap_syslog, &syslog_unknowns ) ) {
591                                 goto destroy;
592                         }
593                         break;
594
595 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
596                 case 'S':
597                         if ( parse_syslog_level( optarg, &ldap_syslog_level ) ) {
598                                 goto destroy;
599                         }
600                         break;
601
602 #ifdef LOG_LOCAL4
603                 case 'l':       /* set syslog local user */
604                         if ( parse_syslog_user( optarg, &syslogUser ) ) {
605                                 goto destroy;
606                         }
607                         break;
608 #endif
609 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
610
611 #ifdef HAVE_CHROOT
612                 case 'r':
613                         if( sandbox ) free(sandbox);
614                         sandbox = ch_strdup( optarg );
615                         break;
616 #endif
617
618 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
619                 case 'u':       /* user name */
620                         if( username ) free(username);
621                         username = ch_strdup( optarg );
622                         break;
623
624                 case 'g':       /* group name */
625                         if( groupname ) free(groupname);
626                         groupname = ch_strdup( optarg );
627                         break;
628 #endif /* SETUID && GETUID */
629
630                 case 'n':  /* NT service name */
631                         serverName = ch_strdup( optarg );
632                         break;
633
634                 case 't':
635                         /* deprecated; use slaptest instead */
636                         fprintf( stderr, "option -t deprecated; "
637                                 "use slaptest command instead\n" );
638                         check |= CHECK_CONFIG;
639                         break;
640
641                 case 'V':
642                         version++;
643                         break;
644
645                 case 'T':
646                         if ( firstopt == 0 ) {
647                                 fprintf( stderr, "warning: \"-T %s\" "
648                                         "should be the first option.\n",
649                                         optarg );
650                         }
651
652                         /* try full option string first */
653                         for ( i = 0; tools[i].name; i++ ) {
654                                 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
655                                         rc = tools[i].func( argc, argv );
656                                         MAIN_RETURN( rc );
657                                 }
658                         }
659
660                         /* try bits of option string (backward compatibility for single char) */
661                         l = strlen( optarg );
662                         for ( i = 0; tools[i].name; i++ ) {
663                                 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
664                                         rc = tools[i].func( argc, argv );
665                                         MAIN_RETURN( rc );
666                                 }
667                         }
668                         
669                         /* issue error */
670                         serverName = optarg;
671                         serverNamePrefix = "slap";
672                         fprintf( stderr, "program name \"%s%s\" unrecognized; "
673                                         "aborting...\n", serverNamePrefix, serverName );
674                         /* FALLTHRU */
675                 default:
676 unhandled_option:;
677                         usage( argv[0] );
678                         rc = 1;
679                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
680                         goto stop;
681                 }
682
683                 if ( firstopt ) {
684                         firstopt = 0;
685                 }
686         }
687
688         if ( optind != argc )
689                 goto unhandled_option;
690
691         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
692         ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
693         ldif_debug = slap_debug;
694
695         if ( version ) {
696                 fprintf( stderr, "%s\n", Versionstr );
697                 if ( version > 2 ) {
698                         if ( slap_oinfo[0].ov_type ) {
699                                 fprintf( stderr, "Included static overlays:\n");
700                                 for ( i= 0 ; slap_oinfo[i].ov_type; i++ ) {
701                                         fprintf( stderr, "    %s\n", slap_oinfo[i].ov_type );
702                                 }
703                         }
704                         if ( slap_binfo[0].bi_type ) {
705                                 fprintf( stderr, "Included static backends:\n");
706                                 for ( i= 0 ; slap_binfo[i].bi_type; i++ ) {
707                                         fprintf( stderr, "    %s\n", slap_binfo[i].bi_type );
708                                 }
709                         }
710                 }
711
712                 if ( version > 1 ) goto stop;
713         }
714
715 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
716         {
717                 char *logName;
718 #ifdef HAVE_EBCDIC
719                 logName = ch_strdup( serverName );
720                 __atoe( logName );
721 #else
722                 logName = serverName;
723 #endif
724
725 #ifdef LOG_LOCAL4
726                 openlog( logName, OPENLOG_OPTIONS, syslogUser );
727 #elif defined LOG_DEBUG
728                 openlog( logName, OPENLOG_OPTIONS );
729 #endif
730 #ifdef HAVE_EBCDIC
731                 free( logName );
732 #endif
733         }
734 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
735
736         Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
737
738         global_host = ldap_pvt_get_fqdn( NULL );
739         ber_str2bv( global_host, 0, 0, &global_host_bv );
740
741         if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
742                 rc = 1;
743                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
744                 goto stop;
745         }
746
747 #if defined(HAVE_CHROOT)
748         if ( sandbox ) {
749                 if ( chdir( sandbox ) ) {
750                         perror("chdir");
751                         rc = 1;
752                         goto stop;
753                 }
754                 if ( chroot( sandbox ) ) {
755                         perror("chroot");
756                         rc = 1;
757                         goto stop;
758                 }
759                 if ( chdir( "/" ) ) {
760                         perror("chdir");
761                         rc = 1;
762                         goto stop;
763                 }
764         }
765 #endif
766
767 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
768         if ( username != NULL || groupname != NULL ) {
769                 slap_init_user( username, groupname );
770         }
771 #endif
772
773         extops_init();
774         lutil_passwd_init();
775
776 #ifdef HAVE_TLS
777         rc = ldap_create( &slap_tls_ld );
778         if ( rc ) {
779                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
780                 goto destroy;
781         }
782         /* Library defaults to full certificate checking. This is correct when
783          * a client is verifying a server because all servers should have a
784          * valid cert. But few clients have valid certs, so we want our default
785          * to be no checking. The config file can override this as usual.
786          */
787         rc = LDAP_OPT_X_TLS_NEVER;
788         (void) ldap_pvt_tls_set_option( slap_tls_ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &rc );
789 #endif
790
791         rc = slap_init( serverMode, serverName );
792         if ( rc ) {
793                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
794                 goto destroy;
795         }
796
797         if ( read_config( configfile, configdir ) != 0 ) {
798                 rc = 1;
799                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
800
801                 if ( check & CHECK_CONFIG ) {
802                         fprintf( stderr, "config check failed\n" );
803                 }
804
805                 goto destroy;
806         }
807
808         if ( debug_unknowns ) {
809                 rc = parse_debug_unknowns( debug_unknowns, &slap_debug );
810                 ldap_charray_free( debug_unknowns );
811                 debug_unknowns = NULL;
812                 if ( rc )
813                         goto destroy;
814         }
815         if ( syslog_unknowns ) {
816                 rc = parse_debug_unknowns( syslog_unknowns, &ldap_syslog );
817                 ldap_charray_free( syslog_unknowns );
818                 syslog_unknowns = NULL;
819                 if ( rc )
820                         goto destroy;
821         }       
822
823         if ( check & CHECK_LOGLEVEL ) {
824                 rc = 0;
825                 goto destroy;
826         }
827
828         if ( check & CHECK_CONFIG ) {
829                 fprintf( stderr, "config check succeeded\n" );
830
831                 check &= ~CHECK_CONFIG;
832                 if ( check == CHECK_NONE ) {
833                         rc = 0;
834                         goto destroy;
835                 }
836         }
837
838         if ( glue_sub_attach( 0 ) != 0 ) {
839                 Debug( LDAP_DEBUG_ANY,
840                     "subordinate config error\n",
841                     0, 0, 0 );
842
843                 goto destroy;
844         }
845
846         if ( slap_schema_check( ) != 0 ) {
847                 Debug( LDAP_DEBUG_ANY,
848                     "schema prep error\n",
849                     0, 0, 0 );
850
851                 goto destroy;
852         }
853
854 #ifdef HAVE_TLS
855         rc = ldap_pvt_tls_init();
856         if( rc != 0) {
857                 Debug( LDAP_DEBUG_ANY,
858                     "main: TLS init failed: %d\n",
859                     rc, 0, 0 );
860                 rc = 1;
861                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
862                 goto destroy;
863         }
864
865         {
866                 int opt = 1;
867
868                 /* Force new ctx to be created */
869                 rc = ldap_pvt_tls_set_option( slap_tls_ld, LDAP_OPT_X_TLS_NEWCTX, &opt );
870                 if( rc == 0 ) {
871                         /* The ctx's refcount is bumped up here */
872                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
873                         load_extop( &slap_EXOP_START_TLS, 0, starttls_extop );
874                 } else if ( rc != LDAP_NOT_SUPPORTED ) {
875                         Debug( LDAP_DEBUG_ANY,
876                             "main: TLS init def ctx failed: %d\n",
877                             rc, 0, 0 );
878                         rc = 1;
879                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
880                         goto destroy;
881                 }
882         }
883 #endif
884
885 #ifdef HAVE_CYRUS_SASL
886         if( sasl_host == NULL ) {
887                 sasl_host = ch_strdup( global_host );
888         }
889 #endif
890
891         (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
892         (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
893
894 #ifdef SIGPIPE
895         (void) SIGNAL( SIGPIPE, SIG_IGN );
896 #endif
897 #ifdef SIGHUP
898         (void) SIGNAL( SIGHUP, slap_sig_shutdown );
899 #endif
900         (void) SIGNAL( SIGINT, slap_sig_shutdown );
901         (void) SIGNAL( SIGTERM, slap_sig_shutdown );
902 #ifdef SIGTRAP
903         (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
904 #endif
905 #ifdef LDAP_SIGCHLD
906         (void) SIGNAL( LDAP_SIGCHLD, wait4child );
907 #endif
908 #ifdef SIGBREAK
909         /* SIGBREAK is generated when Ctrl-Break is pressed. */
910         (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
911 #endif
912
913 #ifndef HAVE_WINSOCK
914         if ( !no_detach ) {
915                 if ( lutil_pair( waitfds ) < 0 ) {
916                         Debug( LDAP_DEBUG_ANY,
917                                 "main: lutil_pair failed: %d\n",
918                                 0, 0, 0 );
919                         rc = 1;
920                         goto destroy;
921                 }
922                 pid = lutil_detach( no_detach, 0 );
923                 if ( pid ) {
924                         char buf[4];
925                         rc = EXIT_SUCCESS;
926                         close( waitfds[1] );
927                         if ( read( waitfds[0], buf, 1 ) != 1 )
928                                 rc = EXIT_FAILURE;
929                         _exit( rc );
930                 } else {
931                         close( waitfds[0] );
932                 }
933         }
934 #endif /* HAVE_WINSOCK */
935
936 #ifdef CSRIMALLOC
937         mal_leaktrace(1);
938 #endif
939
940         if ( slapd_pid_file != NULL ) {
941                 FILE *fp = fopen( slapd_pid_file, "w" );
942
943                 if ( fp == NULL ) {
944                         int save_errno = errno;
945
946                         Debug( LDAP_DEBUG_ANY, "unable to open pid file "
947                                 "\"%s\": %d (%s)\n",
948                                 slapd_pid_file,
949                                 save_errno, strerror( save_errno ) );
950
951                         free( slapd_pid_file );
952                         slapd_pid_file = NULL;
953
954                         rc = 1;
955                         goto destroy;
956                 }
957                 fprintf( fp, "%d\n", (int) getpid() );
958                 fclose( fp );
959                 slapd_pid_file_unlink = 1;
960         }
961
962         if ( slapd_args_file != NULL ) {
963                 FILE *fp = fopen( slapd_args_file, "w" );
964
965                 if ( fp == NULL ) {
966                         int save_errno = errno;
967
968                         Debug( LDAP_DEBUG_ANY, "unable to open args file "
969                                 "\"%s\": %d (%s)\n",
970                                 slapd_args_file,
971                                 save_errno, strerror( save_errno ) );
972
973                         free( slapd_args_file );
974                         slapd_args_file = NULL;
975
976                         rc = 1;
977                         goto destroy;
978                 }
979
980                 for ( i = 0; i < g_argc; i++ ) {
981                         fprintf( fp, "%s ", g_argv[i] );
982                 }
983                 fprintf( fp, "\n" );
984                 fclose( fp );
985                 slapd_args_file_unlink = 1;
986         }
987
988         /*
989          * FIXME: moved here from slapd_daemon_task()
990          * because back-monitor db_open() needs it
991          */
992         time( &starttime );
993
994         connections_init();
995
996         if ( slap_startup( NULL ) != 0 ) {
997                 rc = 1;
998                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
999                 goto shutdown;
1000         }
1001
1002         Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
1003
1004 #ifndef HAVE_WINSOCK
1005         if ( !no_detach ) {
1006                 write( waitfds[1], "1", 1 );
1007                 close( waitfds[1] );
1008         }
1009 #endif
1010
1011 #ifdef HAVE_NT_EVENT_LOG
1012         if (is_NT_Service)
1013         lutil_LogStartedEvent( serverName, slap_debug, configfile ?
1014                 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
1015 #endif
1016
1017         rc = slapd_daemon();
1018
1019 #ifdef HAVE_NT_SERVICE_MANAGER
1020         /* Throw away the event that we used during the startup process. */
1021         if ( is_NT_Service )
1022                 ldap_pvt_thread_cond_destroy( &started_event );
1023 #endif
1024
1025 shutdown:
1026         /* remember an error during shutdown */
1027         rc |= slap_shutdown( NULL );
1028
1029 destroy:
1030         if ( check & CHECK_LOGLEVEL ) {
1031                 (void)loglevel_print( stdout );
1032         }
1033         /* remember an error during destroy */
1034         rc |= slap_destroy();
1035
1036         while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
1037                 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
1038                 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
1039                 ch_free( scp );
1040         }
1041
1042 #ifdef SLAPD_MODULES
1043         module_kill();
1044 #endif
1045
1046         extops_kill();
1047
1048         supported_feature_destroy();
1049         entry_info_destroy();
1050
1051 stop:
1052 #ifdef HAVE_NT_EVENT_LOG
1053         if (is_NT_Service)
1054         lutil_LogStoppedEvent( serverName );
1055 #endif
1056
1057         Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
1058
1059
1060 #ifdef HAVE_NT_SERVICE_MANAGER
1061         lutil_ReportShutdownComplete();
1062 #endif
1063
1064 #ifdef LOG_DEBUG
1065     closelog();
1066 #endif
1067         slapd_daemon_destroy();
1068
1069         controls_destroy();
1070
1071         filter_destroy();
1072
1073         schema_destroy();
1074
1075         lutil_passwd_destroy();
1076
1077 #ifdef HAVE_TLS
1078         if ( slap_tls_ld ) {
1079                 ldap_pvt_tls_ctx_free( slap_tls_ctx );
1080                 ldap_unbind_ext( slap_tls_ld, NULL, NULL );
1081         }
1082         ldap_pvt_tls_destroy();
1083 #endif
1084
1085         slap_sasl_regexp_destroy();
1086
1087         if ( slapd_pid_file_unlink ) {
1088                 unlink( slapd_pid_file );
1089         }
1090         if ( slapd_args_file_unlink ) {
1091                 unlink( slapd_args_file );
1092         }
1093
1094         config_destroy();
1095
1096         if ( configfile )
1097                 ch_free( configfile );
1098         if ( configdir )
1099                 ch_free( configdir );
1100         if ( urls )
1101                 ch_free( urls );
1102         if ( global_host )
1103                 ch_free( global_host );
1104
1105         /* kludge, get symbols referenced */
1106         tavl_free( NULL, NULL );
1107
1108 #ifdef CSRIMALLOC
1109         mal_dumpleaktrace( leakfile );
1110 #endif
1111
1112         MAIN_RETURN(rc);
1113 }
1114
1115
1116 #ifdef LDAP_SIGCHLD
1117
1118 /*
1119  *  Catch and discard terminated child processes, to avoid zombies.
1120  */
1121
1122 static RETSIGTYPE
1123 wait4child( int sig )
1124 {
1125     int save_errno = errno;
1126
1127 #ifdef WNOHANG
1128     do
1129         errno = 0;
1130 #ifdef HAVE_WAITPID
1131     while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR );
1132 #else
1133     while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR );
1134 #endif
1135 #else
1136     (void) wait( NULL );
1137 #endif
1138     (void) SIGNAL_REINSTALL( sig, wait4child );
1139     errno = save_errno;
1140 }
1141
1142 #endif /* LDAP_SIGCHLD */