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