]> git.sur5r.net Git - openldap/blob - servers/slapd/main.c
ec4b40ab28138b39f1eafde90005631a202db67f
[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                         no_detach = 1;
394 #ifdef LDAP_DEBUG
395                         if ( optarg != NULL && optarg[ 0 ] != '-' && !isdigit( optarg[ 0 ] ) )
396                         {
397                                 int     level, i, goterr = 0;
398                                 char    **levels;
399
400                                 levels = ldap_str2charray( optarg, "," );
401
402                                 for ( i = 0; levels[ i ] != NULL; i++ ) {
403                                         if ( str2loglevel( levels[ i ], &level ) ) {
404                                                 fprintf( stderr,
405                                                         "unrecognized log level "
406                                                         "\"%s\"\n", levels[ i ] );
407                                                 goterr = 1;
408
409                                         } else {
410                                                 slap_debug |= level;
411                                         }
412                                 }
413
414                                 ldap_charray_free( levels );
415
416                                 if ( goterr ) {
417                                         goto destroy;
418                                 }
419
420                         } else {
421                                 int     level;
422
423                                 if ( lutil_atoix( &level, optarg, 0 ) != 0 ) {
424                                         fprintf( stderr,
425                                                 "unrecognized log level "
426                                                 "\"%s\"\n", optarg );
427                                         goto destroy;
428                                 }
429                                 slap_debug |= level;
430                         }
431 #else
432                         if ( lutil_atoi( &level, optarg ) != 0 || level != 0 )
433                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
434                                        stderr );
435 #endif
436                         break;
437
438                 case 'f':       /* read config file */
439                         configfile = ch_strdup( optarg );
440                         break;
441
442                 case 'F':       /* use config dir */
443                         configdir = ch_strdup( optarg );
444                         break;
445
446                 case 'o': {
447                         char            *val = strchr( optarg, '=' );
448                         struct berval   opt;
449                         int             i;
450
451                         opt.bv_val = optarg;
452                         
453                         if ( val ) {
454                                 opt.bv_len = ( val - optarg );
455                                 val++;
456                         
457                         } else {
458                                 opt.bv_len = strlen( optarg );
459                         }
460
461                         for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
462                                 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
463                                         assert( option_helpers[i].oh_fnc != NULL );
464                                         if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
465                                                 /* we assume the option parsing helper
466                                                  * issues appropriate and self-explanatory
467                                                  * error messages... */
468                                                 goto stop;
469                                         }
470                                         break;
471                                 }
472                         }
473
474                         if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
475                                 goto unhandled_option;
476                         }
477                         break;
478                 }
479
480                 case 's':       /* set syslog level */
481                         if ( lutil_atoi( &ldap_syslog, optarg ) != 0 ) {
482                                 fprintf( stderr, "unable to parse syslog level \"%s\"", optarg );
483                                 goto destroy;
484                         }
485                         break;
486
487 #ifdef LOG_LOCAL4
488                 case 'l':       /* set syslog local user */
489                         syslogUser = cnvt_str2int( optarg,
490                                 syslog_types, DEFAULT_SYSLOG_USER );
491                         break;
492 #endif
493
494 #ifdef HAVE_CHROOT
495                 case 'r':
496                         if( sandbox ) free(sandbox);
497                         sandbox = ch_strdup( optarg );
498                         break;
499 #endif
500
501 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
502                 case 'u':       /* user name */
503                         if( username ) free(username);
504                         username = ch_strdup( optarg );
505                         break;
506
507                 case 'g':       /* group name */
508                         if( groupname ) free(groupname);
509                         groupname = ch_strdup( optarg );
510                         break;
511 #endif /* SETUID && GETUID */
512
513                 case 'n':  /* NT service name */
514                         serverName = ch_strdup( optarg );
515                         break;
516
517                 case 't':
518                         /* deprecated; use slaptest instead */
519                         fprintf( stderr, "option -t deprecated; "
520                                 "use slaptest command instead\n" );
521                         check |= CHECK_CONFIG;
522                         break;
523
524                 case 'V':
525                         version++;
526                         break;
527
528                 case 'T':
529                         /* try full option string first */
530                         for ( i = 0; tools[i].name; i++ ) {
531                                 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
532                                         rc = tools[i].func( argc, argv );
533                                         MAIN_RETURN( rc );
534                                 }
535                         }
536
537                         /* try bits of option string (backward compatibility for single char) */
538                         l = strlen( optarg );
539                         for ( i = 0; tools[i].name; i++ ) {
540                                 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
541                                         rc = tools[i].func( argc, argv );
542                                         MAIN_RETURN( rc );
543                                 }
544                         }
545                         
546                         /* issue error */
547                         serverName = optarg;
548                         serverNamePrefix = "slap";
549                         fprintf( stderr, "program name \"%s%s\" unrecognized; "
550                                         "aborting...\n", serverNamePrefix, serverName );
551                         /* FALLTHRU */
552                 default:
553 unhandled_option:;
554                         usage( argv[0] );
555                         rc = 1;
556                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
557                         goto stop;
558                 }
559         }
560
561         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
562         ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
563         ldif_debug = slap_debug;
564
565         if ( version ) {
566                 fprintf( stderr, "%s\n", Versionstr );
567                 if ( version > 1 ) goto stop;
568         }
569
570         {
571                 char *logName;
572 #ifdef HAVE_EBCDIC
573                 logName = ch_strdup( serverName );
574                 __atoe( logName );
575 #else
576                 logName = serverName;
577 #endif
578
579 #ifdef LOG_LOCAL4
580                 openlog( logName, OPENLOG_OPTIONS, syslogUser );
581 #elif LOG_DEBUG
582                 openlog( logName, OPENLOG_OPTIONS );
583 #endif
584 #ifdef HAVE_EBCDIC
585                 free( logName );
586 #endif
587         }
588
589         Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
590
591         if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
592                 rc = 1;
593                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
594                 goto stop;
595         }
596
597 #if defined(HAVE_CHROOT)
598         if ( sandbox ) {
599                 if ( chdir( sandbox ) ) {
600                         perror("chdir");
601                         rc = 1;
602                         goto stop;
603                 }
604                 if ( chroot( sandbox ) ) {
605                         perror("chroot");
606                         rc = 1;
607                         goto stop;
608                 }
609         }
610 #endif
611
612 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
613         if ( username != NULL || groupname != NULL ) {
614                 slap_init_user( username, groupname );
615         }
616 #endif
617
618         extops_init();
619         lutil_passwd_init();
620         slap_op_init();
621
622         rc = slap_init( serverMode, serverName );
623         if ( rc ) {
624                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
625                 goto destroy;
626         }
627
628         if ( read_config( configfile, configdir ) != 0 ) {
629                 rc = 1;
630                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
631
632                 if ( check & CHECK_CONFIG ) {
633                         fprintf( stderr, "config check failed\n" );
634                 }
635
636                 goto destroy;
637         }
638
639         if ( check & CHECK_CONFIG ) {
640                 fprintf( stderr, "config check succeeded\n" );
641
642                 check &= ~CHECK_CONFIG;
643                 if ( check == CHECK_NONE ) {
644                         rc = 0;
645                         goto destroy;
646                 }
647         }
648
649         if ( glue_sub_attach( ) != 0 ) {
650                 Debug( LDAP_DEBUG_ANY,
651                     "subordinate config error\n",
652                     0, 0, 0 );
653
654                 goto destroy;
655         }
656
657         if ( slap_schema_check( ) != 0 ) {
658                 Debug( LDAP_DEBUG_ANY,
659                     "schema prep error\n",
660                     0, 0, 0 );
661
662                 goto destroy;
663         }
664
665 #ifdef HAVE_TLS
666         rc = ldap_pvt_tls_init();
667         if( rc != 0) {
668                 Debug( LDAP_DEBUG_ANY,
669                     "main: TLS init failed: %d\n",
670                     0, 0, 0 );
671                 rc = 1;
672                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
673                 goto destroy;
674         }
675
676         {
677                 void *def_ctx = NULL;
678
679                 /* Save existing default ctx, if any */
680                 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &def_ctx );
681
682                 /* Force new ctx to be created */
683                 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, NULL );
684
685                 rc = ldap_pvt_tls_init_def_ctx( 1 );
686                 if( rc == 0 ) {
687                         ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
688                         /* Restore previous ctx */
689                         ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, def_ctx );
690                         load_extop( &slap_EXOP_START_TLS, 0, starttls_extop );
691                 } else if ( rc != LDAP_NOT_SUPPORTED ) {
692                         Debug( LDAP_DEBUG_ANY,
693                             "main: TLS init def ctx failed: %d\n",
694                             rc, 0, 0 );
695                         rc = 1;
696                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
697                         goto destroy;
698                 }
699         }
700 #endif
701
702         (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
703         (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
704
705 #ifdef SIGPIPE
706         (void) SIGNAL( SIGPIPE, SIG_IGN );
707 #endif
708 #ifdef SIGHUP
709         (void) SIGNAL( SIGHUP, slap_sig_shutdown );
710 #endif
711         (void) SIGNAL( SIGINT, slap_sig_shutdown );
712         (void) SIGNAL( SIGTERM, slap_sig_shutdown );
713 #ifdef SIGTRAP
714         (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
715 #endif
716 #ifdef LDAP_SIGCHLD
717         (void) SIGNAL( LDAP_SIGCHLD, wait4child );
718 #endif
719 #ifdef SIGBREAK
720         /* SIGBREAK is generated when Ctrl-Break is pressed. */
721         (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
722 #endif
723
724 #ifndef HAVE_WINSOCK
725         lutil_detach( no_detach, 0 );
726 #endif /* HAVE_WINSOCK */
727
728 #ifdef CSRIMALLOC
729         mal_leaktrace(1);
730 #endif
731
732         if ( slapd_pid_file != NULL ) {
733                 FILE *fp = fopen( slapd_pid_file, "w" );
734
735                 if ( fp == NULL ) {
736                         int save_errno = errno;
737
738                         Debug( LDAP_DEBUG_ANY, "unable to open pid file "
739                                 "\"%s\": %d (%s)\n",
740                                 slapd_pid_file,
741                                 save_errno, strerror( save_errno ) );
742
743                         free( slapd_pid_file );
744                         slapd_pid_file = NULL;
745
746                         rc = 1;
747                         goto destroy;
748                 }
749
750                 fprintf( fp, "%d\n", (int) getpid() );
751                 fclose( fp );
752         }
753
754         if ( slapd_args_file != NULL ) {
755                 FILE *fp = fopen( slapd_args_file, "w" );
756
757                 if ( fp == NULL ) {
758                         int save_errno = errno;
759
760                         Debug( LDAP_DEBUG_ANY, "unable to open args file "
761                                 "\"%s\": %d (%s)\n",
762                                 slapd_args_file,
763                                 save_errno, strerror( save_errno ) );
764
765                         free( slapd_args_file );
766                         slapd_args_file = NULL;
767
768                         rc = 1;
769                         goto destroy;
770                 }
771
772                 for ( i = 0; i < g_argc; i++ ) {
773                         fprintf( fp, "%s ", g_argv[i] );
774                 }
775                 fprintf( fp, "\n" );
776                 fclose( fp );
777         }
778
779         /*
780          * FIXME: moved here from slapd_daemon_task()
781          * because back-monitor db_open() needs it
782          */
783         time( &starttime );
784
785         if ( slap_startup( NULL ) != 0 ) {
786                 rc = 1;
787                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
788                 goto shutdown;
789         }
790
791         Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
792
793 #ifdef HAVE_NT_EVENT_LOG
794         if (is_NT_Service)
795         lutil_LogStartedEvent( serverName, slap_debug, configfile ?
796                 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
797 #endif
798
799         rc = slapd_daemon();
800
801 #ifdef HAVE_NT_SERVICE_MANAGER
802         /* Throw away the event that we used during the startup process. */
803         if ( is_NT_Service )
804                 ldap_pvt_thread_cond_destroy( &started_event );
805 #endif
806
807 shutdown:
808         /* remember an error during shutdown */
809         rc |= slap_shutdown( NULL );
810
811 destroy:
812         /* remember an error during destroy */
813         rc |= slap_destroy();
814
815         while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
816                 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
817                 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
818                 ch_free( scp );
819         }
820
821 #ifdef SLAPD_MODULES
822         module_kill();
823 #endif
824
825         slap_op_destroy();
826
827         extops_kill();
828
829         supported_feature_destroy();
830
831 stop:
832 #ifdef HAVE_NT_EVENT_LOG
833         if (is_NT_Service)
834         lutil_LogStoppedEvent( serverName );
835 #endif
836
837         Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
838
839
840 #ifdef HAVE_NT_SERVICE_MANAGER
841         lutil_ReportShutdownComplete();
842 #endif
843
844 #ifdef LOG_DEBUG
845     closelog();
846 #endif
847         slapd_daemon_destroy();
848
849         controls_destroy();
850
851         schema_destroy();
852
853         lutil_passwd_destroy();
854
855 #ifdef HAVE_TLS
856         ldap_pvt_tls_destroy();
857 #endif
858
859         if ( slapd_pid_file != NULL ) {
860                 unlink( slapd_pid_file );
861         }
862         if ( slapd_args_file != NULL ) {
863                 unlink( slapd_args_file );
864         }
865
866         config_destroy();
867
868         if ( configfile )
869                 ch_free( configfile );
870         if ( configdir )
871                 ch_free( configdir );
872         if ( urls )
873                 ch_free( urls );
874
875 #ifdef CSRIMALLOC
876         mal_dumpleaktrace( leakfile );
877 #endif
878
879         MAIN_RETURN(rc);
880 }
881
882
883 #ifdef LDAP_SIGCHLD
884
885 /*
886  *  Catch and discard terminated child processes, to avoid zombies.
887  */
888
889 static RETSIGTYPE
890 wait4child( int sig )
891 {
892     int save_errno = errno;
893
894 #ifdef WNOHANG
895     errno = 0;
896 #ifdef HAVE_WAITPID
897     while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
898         ;       /* NULL */
899 #else
900     while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
901         ;       /* NULL */
902 #endif
903 #else
904     (void) wait( NULL );
905 #endif
906     (void) SIGNAL_REINSTALL( sig, wait4child );
907     errno = save_errno;
908 }
909
910 #endif /* LDAP_SIGCHLD */
911
912
913 #ifdef LOG_LOCAL4
914
915 /*
916  *  Convert a string to an integer by means of a dispatcher table
917  *  if the string is not in the table return the default
918  */
919
920 static int
921 cnvt_str2int( char *stringVal, STRDISP_P dispatcher, int defaultVal )
922 {
923     int        retVal = defaultVal;
924     STRDISP_P  disp;
925
926     for (disp = dispatcher; disp->stringVal; disp++) {
927
928         if (!strncasecmp (stringVal, disp->stringVal, disp->abbr)) {
929
930             retVal = disp->intVal;
931             break;
932
933         }
934     }
935
936     return (retVal);
937 }
938
939 #endif  /* LOG_LOCAL4 */