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