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