]> git.sur5r.net Git - openldap/blob - servers/slapd/main.c
89e6a98d79a4b43b1638084805dcc96ecec82d88
[openldap] / servers / slapd / main.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2005 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;
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         {"slaptest", slaptest},
80         {"slapauth", slapauth},
81         {"slapacl", slapacl},
82         /* NOTE: new tools must be added in chronological order,
83          * not in alphabetical order, because for backwards
84          * compatibility name[4] is used to identify the
85          * tools; so name[4]=='a' must refer to "slapadd" and
86          * not to "slapauth".  Alphabetical order can be used
87          * for tools whose name[4] is not used yet */
88         {NULL, NULL}
89 };
90
91 /*
92  * when more than one slapd is running on one machine, each one might have
93  * it's own LOCAL for syslogging and must have its own pid/args files
94  */
95
96 #ifndef HAVE_MKVERSION
97 const char Versionstr[] =
98         OPENLDAP_PACKAGE " " OPENLDAP_VERSION " Standalone LDAP Server (slapd)";
99 #endif
100
101 #define CHECK_NONE      0x00
102 #define CHECK_CONFIG    0x01
103 static int check = CHECK_NONE;
104 static int version = 0;
105
106 void *slap_tls_ctx;
107
108 #ifdef LOG_LOCAL4
109 #define DEFAULT_SYSLOG_USER     LOG_LOCAL4
110 #endif /* LOG_LOCAL4 */
111
112 static int
113 slapd_opt_slp( const char *val, void *arg )
114 {
115 #ifdef HAVE_SLP
116         /* NULL is default */
117         if ( val == NULL || strcasecmp( val, "on" ) == 0 ) {
118                 slapd_register_slp = 1;
119
120         } else if ( strcasecmp( val, "off" ) == 0 ) {
121                 slapd_register_slp = 0;
122
123         /* NOTE: add support for URL specification? */
124
125         } else {
126                 fprintf(stderr, "unrecognized value \"%s\" for SLP option\n", val );
127                 return -1;
128         }
129
130         return 0;
131                 
132 #else
133         fputs( "slapd: SLP support is not available\n", stderr );
134         return 0;
135 #endif
136 }
137
138 /*
139  * Option helper structure:
140  * 
141  * oh_nam       is left-hand part of <option>[=<value>]
142  * oh_fnc       is handler function
143  * oh_arg       is an optional arg to oh_fnc
144  * oh_usage     is the one-line usage string related to the option,
145  *              which is assumed to start with <option>[=<value>]
146  *
147  * please leave valid options in the structure, and optionally #ifdef
148  * their processing inside the helper, so that reasonable and helpful
149  * error messages can be generated if a disabled option is requested.
150  */
151 struct option_helper {
152         struct berval   oh_name;
153         int             (*oh_fnc)(const char *val, void *arg);
154         void            *oh_arg;
155         const char      *oh_usage;
156 } option_helpers[] = {
157         { BER_BVC("slp"),       slapd_opt_slp,  NULL, "slp[={on|off}] enable/disable SLP" },
158         { BER_BVNULL, 0, NULL, NULL }
159 };
160
161 #ifdef LOG_LOCAL4
162 static int
163 parse_syslog_user( const char *arg, int *syslogUser )
164 {
165         static slap_verbmasks syslogUsers[] = {
166                 { BER_BVC( "LOCAL0" ), LOG_LOCAL0 },
167                 { BER_BVC( "LOCAL1" ), LOG_LOCAL1 },
168                 { BER_BVC( "LOCAL2" ), LOG_LOCAL2 },
169                 { BER_BVC( "LOCAL3" ), LOG_LOCAL3 },
170                 { BER_BVC( "LOCAL4" ), LOG_LOCAL4 },
171                 { BER_BVC( "LOCAL5" ), LOG_LOCAL5 },
172                 { BER_BVC( "LOCAL6" ), LOG_LOCAL6 },
173                 { BER_BVC( "LOCAL7" ), LOG_LOCAL7 },
174 #ifdef LOG_USER
175                 { BER_BVC( "USER" ), LOG_USER },
176 #endif /* LOG_USER */
177 #ifdef LOG_DAEMON
178                 { BER_BVC( "DAEMON" ), LOG_DAEMON },
179 #endif /* LOG_DAEMON */
180                 { BER_BVNULL, 0 }
181         };
182         int i = verb_to_mask( optarg, syslogUsers );
183
184         if ( BER_BVISNULL( &syslogUsers[ i ].word ) ) {
185                 Debug( LDAP_DEBUG_ANY,
186                         "unrecognized syslog user \"%s\".\n",
187                         optarg, 0, 0 );
188                 return 1;
189         }
190
191         *syslogUser = syslogUsers[ i ].mask;
192
193         return 0;
194 }
195 #endif /* LOG_LOCAL4 */
196
197 static int
198 parse_syslog_level( const char *arg, int *levelp )
199 {
200         static slap_verbmasks   str2syslog_level[] = {
201                 { BER_BVC( "EMERG" ),   LOG_EMERG },
202                 { BER_BVC( "ALERT" ),   LOG_ALERT },
203                 { BER_BVC( "CRIT" ),    LOG_CRIT },
204                 { BER_BVC( "ERR" ),     LOG_ERR },
205                 { BER_BVC( "WARNING" ), LOG_WARNING },
206                 { BER_BVC( "NOTICE" ),  LOG_NOTICE },
207                 { BER_BVC( "INFO" ),    LOG_INFO },
208                 { BER_BVC( "DEBUG" ),   LOG_DEBUG },
209                 { BER_BVNULL, 0 }
210         };
211         int i = verb_to_mask( arg, str2syslog_level );
212         if ( BER_BVISNULL( &str2syslog_level[ i ].word ) ) {
213                 Debug( LDAP_DEBUG_ANY,
214                         "unknown syslog level \"%s\".\n",
215                         arg, 0, 0 );
216                 return 1;
217         }
218         
219         *levelp = str2syslog_level[ i ].mask;
220
221         return 0;
222 }
223
224 int
225 parse_debug_level( const char *arg, int *levelp )
226 {
227         int     level;
228
229         if ( arg != NULL && arg[ 0 ] != '-' && !isdigit( arg[ 0 ] ) )
230         {
231                 int     i, goterr = 0;
232                 char    **levels;
233
234                 levels = ldap_str2charray( arg, "," );
235
236                 for ( i = 0; levels[ i ] != NULL; i++ ) {
237                         level = 0;
238
239                         if ( str2loglevel( levels[ i ], &level ) ) {
240                                 fprintf( stderr,
241                                         "unrecognized log level "
242                                         "\"%s\"\n", levels[ i ] );
243                                 goterr = 1;
244                                 /* but keep parsing... */
245
246                         } else {
247                                 *levelp |= level;
248                         }
249                 }
250
251                 ldap_charray_free( levels );
252
253                 if ( goterr ) {
254                         return 1;
255                 }
256
257         } else {
258                 if ( lutil_atoix( &level, arg, 0 ) != 0 ) {
259                         fprintf( stderr,
260                                 "unrecognized log level "
261                                 "\"%s\"\n", arg );
262                         return 1;
263                 }
264
265                 if ( level == 0 ) {
266                         *levelp = 0;
267
268                 } else {
269                         *levelp |= level;
270                 }
271         }
272
273         return 0;
274 }
275
276 static void
277 usage( char *name )
278 {
279         fprintf( stderr,
280                 "usage: %s options\n", name );
281         fprintf( stderr,
282                 "\t-4\t\tIPv4 only\n"
283                 "\t-6\t\tIPv6 only\n"
284                 "\t-T {acl|add|auth|cat|dn|index|passwd|test}\n"
285                 "\t\t\tRun in Tool mode\n"
286                 "\t-c cookie\tSync cookie of consumer\n"
287                 "\t-d level\tDebug level" "\n"
288                 "\t-f filename\tConfiguration file\n"
289                 "\t-F dir\tConfiguration directory\n"
290 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
291                 "\t-g group\tGroup (id or name) to run as\n"
292 #endif
293                 "\t-h URLs\t\tList of URLs to serve\n"
294 #ifdef LOG_LOCAL4
295                 "\t-l facility\tSyslog facility (default: LOCAL4)\n"
296 #endif
297                 "\t-n serverName\tService name\n"
298                 "\t-o <opt>[=val] generic means to specify options" );
299         if ( !BER_BVISNULL( &option_helpers[0].oh_name ) ) {
300                 int     i;
301
302                 fprintf( stderr, "; supported options:\n" );
303                 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++) {
304                         fprintf( stderr, "\t\t%s\n", option_helpers[i].oh_usage );
305                 }
306         } else {
307                 fprintf( stderr, "\n" );
308         }
309         fprintf( stderr,        
310 #ifdef HAVE_CHROOT
311                 "\t-r directory\tSandbox directory to chroot to\n"
312 #endif
313                 "\t-s level\tSyslog level\n"
314 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
315                 "\t-u user\t\tUser (id or name) to run as\n"
316 #endif
317                 "\t-V\t\tprint version info (-VV only)\n"
318     );
319 }
320
321 #ifdef HAVE_NT_SERVICE_MANAGER
322 void WINAPI ServiceMain( DWORD argc, LPTSTR *argv )
323 #else
324 int main( int argc, char **argv )
325 #endif
326 {
327         int             i, no_detach = 0;
328         int             rc = 1;
329         char *urls = NULL;
330 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
331         char *username = NULL;
332         char *groupname = NULL;
333 #endif
334 #if defined(HAVE_CHROOT)
335         char *sandbox = NULL;
336 #endif
337 #ifdef LOG_LOCAL4
338         int syslogUser = DEFAULT_SYSLOG_USER;
339 #endif
340         
341         int g_argc = argc;
342         char **g_argv = argv;
343
344         char *configfile = NULL;
345         char *configdir = NULL;
346         char *serverName;
347         int serverMode = SLAP_SERVER_MODE;
348
349         struct sync_cookie *scp = NULL;
350         struct sync_cookie *scp_entry = NULL;
351
352         char *serverNamePrefix = "";
353         size_t  l;
354
355         int slapd_pid_file_unlink = 0, slapd_args_file_unlink = 0;
356
357 #ifdef CSRIMALLOC
358         FILE *leakfile;
359         if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
360                 leakfile = stderr;
361         }
362 #endif
363
364         slap_sl_mem_init();
365
366         (void) ldap_pvt_thread_initialize();
367
368         serverName = lutil_progname( "slapd", argc, argv );
369
370         if ( strcmp( serverName, "slapd" ) ) {
371                 for (i=0; tools[i].name; i++) {
372                         if ( !strcmp( serverName, tools[i].name ) ) {
373                                 rc = tools[i].func(argc, argv);
374                                 MAIN_RETURN(rc);
375                         }
376                 }
377         }
378
379 #ifdef HAVE_NT_SERVICE_MANAGER
380         {
381                 int *i;
382                 char *newConfigFile;
383                 char *newConfigDir;
384                 char *newUrls;
385                 char *regService = NULL;
386
387                 if ( is_NT_Service ) {
388                         lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
389                         if ( strcmp(serverName, SERVICE_NAME) )
390                             regService = serverName;
391                 }
392
393                 i = (int*)lutil_getRegParam( regService, "DebugLevel" );
394                 if ( i != NULL ) {
395                         slap_debug = *i;
396                         Debug( LDAP_DEBUG_ANY,
397                                 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
398                 }
399
400                 newUrls = (char *) lutil_getRegParam(regService, "Urls");
401                 if (newUrls) {
402                     if (urls)
403                         ch_free(urls);
404
405                     urls = ch_strdup(newUrls);
406                     Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
407                                 urls, 0, 0);
408                 }
409
410                 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
411                 if ( newConfigFile != NULL ) {
412                         configfile = newConfigFile;
413                         Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
414                 }
415
416                 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
417                 if ( newConfigDir != NULL ) {
418                         configdir = newConfigDir;
419                         Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
420                 }
421         }
422 #endif
423
424         while ( (i = getopt( argc, argv,
425                              "c:d:f:F:h:n:o:s:tT:V"
426 #if LDAP_PF_INET6
427                                 "46"
428 #endif
429 #ifdef HAVE_CHROOT
430                                 "r:"
431 #endif
432 #ifdef LDAP_SYSLOG
433                                 "S:"
434 #endif
435 #ifdef LOG_LOCAL4
436                                 "l:"
437 #endif
438 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
439                                 "u:g:"
440 #endif
441                              )) != EOF ) {
442                 switch ( i ) {
443 #ifdef LDAP_PF_INET6
444                 case '4':
445                         slap_inet4or6 = AF_INET;
446                         break;
447                 case '6':
448                         slap_inet4or6 = AF_INET6;
449                         break;
450 #endif
451
452                 case 'h':       /* listen URLs */
453                         if ( urls != NULL ) free( urls );
454                         urls = ch_strdup( optarg );
455                         break;
456
457                 case 'c':       /* provide sync cookie, override if exist in replica */
458                         scp = (struct sync_cookie *) ch_calloc( 1,
459                                                                                 sizeof( struct sync_cookie ));
460                         ber_str2bv( optarg, 0, 1, &scp->octet_str );
461                         
462                         /* This only parses out the rid at this point */
463                         slap_parse_sync_cookie( scp, NULL );
464
465                         if ( scp->rid == -1 ) {
466                                 Debug( LDAP_DEBUG_ANY,
467                                                 "main: invalid cookie \"%s\"\n",
468                                                 optarg, 0, 0 );
469                                 slap_sync_cookie_free( scp, 1 );
470                                 goto destroy;
471                         }
472
473                         LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
474                                 if ( scp->rid == scp_entry->rid ) {
475                                         Debug( LDAP_DEBUG_ANY,
476                                                     "main: duplicated replica id in cookies\n",
477                                                         0, 0, 0 );
478                                         slap_sync_cookie_free( scp, 1 );
479                                         goto destroy;
480                                 }
481                         }
482                         LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
483                         break;
484
485                 case 'd': {     /* set debug level and 'do not detach' flag */
486                         int     level = 0;
487
488                         no_detach = 1;
489                         if ( parse_debug_level( optarg, &level ) ) {
490                                 goto destroy;
491                         }
492 #ifdef LDAP_DEBUG
493                         slap_debug |= level;
494 #else
495                         if ( level != 0 )
496                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
497                                        stderr );
498 #endif
499                         } break;
500
501                 case 'f':       /* read config file */
502                         configfile = ch_strdup( optarg );
503                         break;
504
505                 case 'F':       /* use config dir */
506                         configdir = ch_strdup( optarg );
507                         break;
508
509                 case 'o': {
510                         char            *val = strchr( optarg, '=' );
511                         struct berval   opt;
512                         int             i;
513
514                         opt.bv_val = optarg;
515                         
516                         if ( val ) {
517                                 opt.bv_len = ( val - optarg );
518                                 val++;
519                         
520                         } else {
521                                 opt.bv_len = strlen( optarg );
522                         }
523
524                         for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
525                                 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
526                                         assert( option_helpers[i].oh_fnc != NULL );
527                                         if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
528                                                 /* we assume the option parsing helper
529                                                  * issues appropriate and self-explanatory
530                                                  * error messages... */
531                                                 goto stop;
532                                         }
533                                         break;
534                                 }
535                         }
536
537                         if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
538                                 goto unhandled_option;
539                         }
540                         break;
541                 }
542
543                 case 's':       /* set syslog level */
544                         if ( parse_debug_level( optarg, &ldap_syslog ) ) {
545                                 goto destroy;
546                         }
547                         break;
548
549 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
550                 case 'S':
551                         if ( parse_syslog_level( optarg, &ldap_syslog_level ) ) {
552                                 goto destroy;
553                         }
554                         break;
555 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
556
557 #ifdef LOG_LOCAL4
558                 case 'l':       /* set syslog local user */
559                         if ( parse_syslog_user( optarg, &syslogUser ) ) {
560                                 goto destroy;
561                         }
562                         break;
563 #endif
564
565 #ifdef HAVE_CHROOT
566                 case 'r':
567                         if( sandbox ) free(sandbox);
568                         sandbox = ch_strdup( optarg );
569                         break;
570 #endif
571
572 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
573                 case 'u':       /* user name */
574                         if( username ) free(username);
575                         username = ch_strdup( optarg );
576                         break;
577
578                 case 'g':       /* group name */
579                         if( groupname ) free(groupname);
580                         groupname = ch_strdup( optarg );
581                         break;
582 #endif /* SETUID && GETUID */
583
584                 case 'n':  /* NT service name */
585                         serverName = ch_strdup( optarg );
586                         break;
587
588                 case 't':
589                         /* deprecated; use slaptest instead */
590                         fprintf( stderr, "option -t deprecated; "
591                                 "use slaptest command instead\n" );
592                         check |= CHECK_CONFIG;
593                         break;
594
595                 case 'V':
596                         version++;
597                         break;
598
599                 case 'T':
600                         /* try full option string first */
601                         for ( i = 0; tools[i].name; i++ ) {
602                                 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
603                                         rc = tools[i].func( argc, argv );
604                                         MAIN_RETURN( rc );
605                                 }
606                         }
607
608                         /* try bits of option string (backward compatibility for single char) */
609                         l = strlen( optarg );
610                         for ( i = 0; tools[i].name; i++ ) {
611                                 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
612                                         rc = tools[i].func( argc, argv );
613                                         MAIN_RETURN( rc );
614                                 }
615                         }
616                         
617                         /* issue error */
618                         serverName = optarg;
619                         serverNamePrefix = "slap";
620                         fprintf( stderr, "program name \"%s%s\" unrecognized; "
621                                         "aborting...\n", serverNamePrefix, serverName );
622                         /* FALLTHRU */
623                 default:
624 unhandled_option:;
625                         usage( argv[0] );
626                         rc = 1;
627                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
628                         goto stop;
629                 }
630         }
631
632         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
633         ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
634         ldif_debug = slap_debug;
635
636         if ( version ) {
637                 fprintf( stderr, "%s\n", Versionstr );
638                 if ( version > 1 ) goto stop;
639         }
640
641         {
642                 char *logName;
643 #ifdef HAVE_EBCDIC
644                 logName = ch_strdup( serverName );
645                 __atoe( logName );
646 #else
647                 logName = serverName;
648 #endif
649
650 #ifdef LOG_LOCAL4
651                 openlog( logName, OPENLOG_OPTIONS, syslogUser );
652 #elif LOG_DEBUG
653                 openlog( logName, OPENLOG_OPTIONS );
654 #endif
655 #ifdef HAVE_EBCDIC
656                 free( logName );
657 #endif
658         }
659
660         Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
661
662         if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
663                 rc = 1;
664                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
665                 goto stop;
666         }
667
668 #if defined(HAVE_CHROOT)
669         if ( sandbox ) {
670                 if ( chdir( sandbox ) ) {
671                         perror("chdir");
672                         rc = 1;
673                         goto stop;
674                 }
675                 if ( chroot( sandbox ) ) {
676                         perror("chroot");
677                         rc = 1;
678                         goto stop;
679                 }
680         }
681 #endif
682
683 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
684         if ( username != NULL || groupname != NULL ) {
685                 slap_init_user( username, groupname );
686         }
687 #endif
688
689         extops_init();
690         lutil_passwd_init();
691         slap_op_init();
692
693         rc = slap_init( serverMode, serverName );
694         if ( rc ) {
695                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
696                 goto destroy;
697         }
698
699         if ( read_config( configfile, configdir ) != 0 ) {
700                 rc = 1;
701                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
702
703                 if ( check & CHECK_CONFIG ) {
704                         fprintf( stderr, "config check failed\n" );
705                 }
706
707                 goto destroy;
708         }
709
710         if ( check & CHECK_CONFIG ) {
711                 fprintf( stderr, "config check succeeded\n" );
712
713                 check &= ~CHECK_CONFIG;
714                 if ( check == CHECK_NONE ) {
715                         rc = 0;
716                         goto destroy;
717                 }
718         }
719
720         if ( glue_sub_attach( ) != 0 ) {
721                 Debug( LDAP_DEBUG_ANY,
722                     "subordinate config error\n",
723                     0, 0, 0 );
724
725                 goto destroy;
726         }
727
728         if ( slap_schema_check( ) != 0 ) {
729                 Debug( LDAP_DEBUG_ANY,
730                     "schema prep error\n",
731                     0, 0, 0 );
732
733                 goto destroy;
734         }
735
736 #ifdef HAVE_TLS
737         rc = ldap_pvt_tls_init();
738         if( rc != 0) {
739                 Debug( LDAP_DEBUG_ANY,
740                     "main: TLS init failed: %d\n",
741                     0, 0, 0 );
742                 rc = 1;
743                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
744                 goto destroy;
745         }
746
747         {
748                 void *def_ctx = NULL;
749
750                 /* Save existing default ctx, if any */
751                 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &def_ctx );
752
753                 /* Force new ctx to be created */
754                 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, NULL );
755
756                 rc = ldap_pvt_tls_init_def_ctx( 1 );
757                 if( rc == 0 ) {
758                         ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
759                         /* Restore previous ctx */
760                         ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, def_ctx );
761                         load_extop( &slap_EXOP_START_TLS, 0, starttls_extop );
762                 } else if ( rc != LDAP_NOT_SUPPORTED ) {
763                         Debug( LDAP_DEBUG_ANY,
764                             "main: TLS init def ctx failed: %d\n",
765                             rc, 0, 0 );
766                         rc = 1;
767                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
768                         goto destroy;
769                 }
770         }
771 #endif
772
773         (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
774         (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
775
776 #ifdef SIGPIPE
777         (void) SIGNAL( SIGPIPE, SIG_IGN );
778 #endif
779 #ifdef SIGHUP
780         (void) SIGNAL( SIGHUP, slap_sig_shutdown );
781 #endif
782         (void) SIGNAL( SIGINT, slap_sig_shutdown );
783         (void) SIGNAL( SIGTERM, slap_sig_shutdown );
784 #ifdef SIGTRAP
785         (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
786 #endif
787 #ifdef LDAP_SIGCHLD
788         (void) SIGNAL( LDAP_SIGCHLD, wait4child );
789 #endif
790 #ifdef SIGBREAK
791         /* SIGBREAK is generated when Ctrl-Break is pressed. */
792         (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
793 #endif
794
795 #ifndef HAVE_WINSOCK
796         lutil_detach( no_detach, 0 );
797 #endif /* HAVE_WINSOCK */
798
799 #ifdef CSRIMALLOC
800         mal_leaktrace(1);
801 #endif
802
803         if ( slapd_pid_file != NULL ) {
804                 FILE *fp = fopen( slapd_pid_file, "w" );
805
806                 if ( fp == NULL ) {
807                         int save_errno = errno;
808
809                         Debug( LDAP_DEBUG_ANY, "unable to open pid file "
810                                 "\"%s\": %d (%s)\n",
811                                 slapd_pid_file,
812                                 save_errno, strerror( save_errno ) );
813
814                         free( slapd_pid_file );
815                         slapd_pid_file = NULL;
816
817                         rc = 1;
818                         goto destroy;
819                 }
820                 fprintf( fp, "%d\n", (int) getpid() );
821                 fclose( fp );
822                 slapd_pid_file_unlink = 1;
823         }
824
825         if ( slapd_args_file != NULL ) {
826                 FILE *fp = fopen( slapd_args_file, "w" );
827
828                 if ( fp == NULL ) {
829                         int save_errno = errno;
830
831                         Debug( LDAP_DEBUG_ANY, "unable to open args file "
832                                 "\"%s\": %d (%s)\n",
833                                 slapd_args_file,
834                                 save_errno, strerror( save_errno ) );
835
836                         free( slapd_args_file );
837                         slapd_args_file = NULL;
838
839                         rc = 1;
840                         goto destroy;
841                 }
842
843                 for ( i = 0; i < g_argc; i++ ) {
844                         fprintf( fp, "%s ", g_argv[i] );
845                 }
846                 fprintf( fp, "\n" );
847                 fclose( fp );
848                 slapd_args_file_unlink = 1;
849         }
850
851         /*
852          * FIXME: moved here from slapd_daemon_task()
853          * because back-monitor db_open() needs it
854          */
855         time( &starttime );
856
857         if ( slap_startup( NULL ) != 0 ) {
858                 rc = 1;
859                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
860                 goto shutdown;
861         }
862
863         Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
864
865 #ifdef HAVE_NT_EVENT_LOG
866         if (is_NT_Service)
867         lutil_LogStartedEvent( serverName, slap_debug, configfile ?
868                 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
869 #endif
870
871         rc = slapd_daemon();
872
873 #ifdef HAVE_NT_SERVICE_MANAGER
874         /* Throw away the event that we used during the startup process. */
875         if ( is_NT_Service )
876                 ldap_pvt_thread_cond_destroy( &started_event );
877 #endif
878
879 shutdown:
880         /* remember an error during shutdown */
881         rc |= slap_shutdown( NULL );
882
883 destroy:
884         /* remember an error during destroy */
885         rc |= slap_destroy();
886
887         while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
888                 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
889                 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
890                 ch_free( scp );
891         }
892
893 #ifdef SLAPD_MODULES
894         module_kill();
895 #endif
896
897         slap_op_destroy();
898
899         extops_kill();
900
901         supported_feature_destroy();
902         entry_info_destroy();
903
904 stop:
905 #ifdef HAVE_NT_EVENT_LOG
906         if (is_NT_Service)
907         lutil_LogStoppedEvent( serverName );
908 #endif
909
910         Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
911
912
913 #ifdef HAVE_NT_SERVICE_MANAGER
914         lutil_ReportShutdownComplete();
915 #endif
916
917 #ifdef LOG_DEBUG
918     closelog();
919 #endif
920         slapd_daemon_destroy();
921
922         controls_destroy();
923
924         schema_destroy();
925
926         lutil_passwd_destroy();
927
928 #ifdef HAVE_TLS
929         ldap_pvt_tls_destroy();
930 #endif
931
932         if ( slapd_pid_file_unlink ) {
933                 unlink( slapd_pid_file );
934         }
935         if ( slapd_args_file_unlink ) {
936                 unlink( slapd_args_file );
937         }
938
939         config_destroy();
940
941         if ( configfile )
942                 ch_free( configfile );
943         if ( configdir )
944                 ch_free( configdir );
945         if ( urls )
946                 ch_free( urls );
947
948 #ifdef CSRIMALLOC
949         mal_dumpleaktrace( leakfile );
950 #endif
951
952         MAIN_RETURN(rc);
953 }
954
955
956 #ifdef LDAP_SIGCHLD
957
958 /*
959  *  Catch and discard terminated child processes, to avoid zombies.
960  */
961
962 static RETSIGTYPE
963 wait4child( int sig )
964 {
965     int save_errno = errno;
966
967 #ifdef WNOHANG
968     errno = 0;
969 #ifdef HAVE_WAITPID
970     while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
971         ;       /* NULL */
972 #else
973     while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
974         ;       /* NULL */
975 #endif
976 #else
977     (void) wait( NULL );
978 #endif
979     (void) SIGNAL_REINSTALL( sig, wait4child );
980     errno = save_errno;
981 }
982
983 #endif /* LDAP_SIGCHLD */
984