]> git.sur5r.net Git - openldap/blob - servers/slapd/main.c
ITS#3682, dup entry and free the DB's copy before sending it
[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/socket.h>
31 #include <ac/string.h>
32 #include <ac/time.h>
33 #include <ac/unistd.h>
34 #include <ac/wait.h>
35 #include <ac/errno.h>
36
37 #include "slap.h"
38 #include "lutil.h"
39 #include "ldif.h"
40
41 #ifdef LDAP_SLAPI
42 #include "slapi/slapi.h"
43 #endif
44
45 #ifdef LDAP_SIGCHLD
46 static RETSIGTYPE wait4child( int sig );
47 #endif
48
49 #ifdef HAVE_NT_SERVICE_MANAGER
50 #define MAIN_RETURN(x) return
51 static struct sockaddr_in       bind_addr;
52
53 #define SERVICE_EXIT( e, n )    do { \
54         if ( is_NT_Service ) { \
55                 lutil_ServiceStatus.dwWin32ExitCode                             = (e); \
56                 lutil_ServiceStatus.dwServiceSpecificExitCode   = (n); \
57         } \
58 } while ( 0 )
59
60 #else
61 #define SERVICE_EXIT( e, n )
62 #define MAIN_RETURN(x) return(x)
63 #endif
64
65 typedef int (MainFunc) LDAP_P(( int argc, char *argv[] ));
66 extern MainFunc slapadd, slapcat, slapdn, slapindex, slappasswd,
67         slaptest, slapauth, slapacl;
68
69 static struct {
70         char *name;
71         MainFunc *func;
72 } tools[] = {
73         {"slapadd", slapadd},
74         {"slapcat", slapcat},
75         {"slapdn", slapdn},
76         {"slapindex", slapindex},
77         {"slappasswd", slappasswd},
78         {"slaptest", slaptest},
79         {"slapauth", slapauth},
80         {"slapacl", slapacl},
81         /* NOTE: new tools must be added in chronological order,
82          * not in alphabetical order, because for backwards
83          * compatibility name[4] is used to identify the
84          * tools; so name[4]=='a' must refer to "slapadd" and
85          * not to "slapauth".  Alphabetical order can be used
86          * for tools whose name[4] is not used yet */
87         {NULL, NULL}
88 };
89
90 /*
91  * when more than one slapd is running on one machine, each one might have
92  * it's own LOCAL for syslogging and must have its own pid/args files
93  */
94
95 #ifndef HAVE_MKVERSION
96 const char Versionstr[] =
97         OPENLDAP_PACKAGE " " OPENLDAP_VERSION " Standalone LDAP Server (slapd)";
98 #endif
99
100 #ifdef LOG_LOCAL4
101 #define DEFAULT_SYSLOG_USER  LOG_LOCAL4
102
103 typedef struct _str2intDispatch {
104         char    *stringVal;
105         int      abbr;
106         int      intVal;
107 } STRDISP, *STRDISP_P;
108
109 /* table to compute syslog-options to integer */
110 static STRDISP  syslog_types[] = {
111         { "LOCAL0", sizeof("LOCAL0"), LOG_LOCAL0 },
112         { "LOCAL1", sizeof("LOCAL1"), LOG_LOCAL1 },
113         { "LOCAL2", sizeof("LOCAL2"), LOG_LOCAL2 },
114         { "LOCAL3", sizeof("LOCAL3"), LOG_LOCAL3 },
115         { "LOCAL4", sizeof("LOCAL4"), LOG_LOCAL4 },
116         { "LOCAL5", sizeof("LOCAL5"), LOG_LOCAL5 },
117         { "LOCAL6", sizeof("LOCAL6"), LOG_LOCAL6 },
118         { "LOCAL7", sizeof("LOCAL7"), LOG_LOCAL7 },
119 #ifdef LOG_USER
120         { "USER", sizeof("USER"), LOG_USER },
121 #endif
122 #ifdef LOG_DAEMON
123         { "DAEMON", sizeof("DAEMON"), LOG_DAEMON },
124 #endif
125         { NULL, 0, 0 }
126 };
127
128 static int cnvt_str2int( char *, STRDISP_P, int );
129 #endif  /* LOG_LOCAL4 */
130
131 #define CHECK_NONE      0x00
132 #define CHECK_CONFIG    0x01
133 static int check = CHECK_NONE;
134 static int version = 0;
135
136 void *slap_tls_ctx;
137
138 static int
139 slapd_opt_slp( const char *val, void *arg )
140 {
141 #ifdef HAVE_SLP
142         /* NULL is default */
143         if ( val == NULL || strcasecmp( val, "on" ) == 0 ) {
144                 slapd_register_slp = 1;
145
146         } else if ( strcasecmp( val, "off" ) == 0 ) {
147                 slapd_register_slp = 0;
148
149         /* NOTE: add support for URL specification? */
150
151         } else {
152                 fprintf(stderr, "unrecognized value \"%s\" for SLP option\n", val );
153                 return -1;
154         }
155
156         return 0;
157                 
158 #else
159         fputs( "slapd: SLP support is not available\n", stderr );
160         return 0;
161 #endif
162 }
163
164 /*
165  * Option helper structure:
166  * 
167  * oh_nam       is left-hand part of <option>[=<value>]
168  * oh_fnc       is handler function
169  * oh_arg       is an optional arg to oh_fnc
170  * oh_usage     is the one-line usage string related to the option,
171  *              which is assumed to start with <option>[=<value>]
172  *
173  * please leave valid options in the structure, and optionally #ifdef
174  * their processing inside the helper, so that reasonable and helpful
175  * error messages can be generated if a disabled option is requested.
176  */
177 struct option_helper {
178         struct berval   oh_name;
179         int             (*oh_fnc)(const char *val, void *arg);
180         void            *oh_arg;
181         const char      *oh_usage;
182 } option_helpers[] = {
183         { BER_BVC("slp"),       slapd_opt_slp,  NULL, "slp[={on|off}] enable/disable SLP" },
184         { BER_BVNULL }
185 };
186
187 static void
188 usage( char *name )
189 {
190         fprintf( stderr,
191                 "usage: %s options\n", name );
192         fprintf( stderr,
193                 "\t-4\t\tIPv4 only\n"
194                 "\t-6\t\tIPv6 only\n"
195                 "\t-T {acl|add|auth|cat|dn|index|passwd|test}\n"
196                 "\t\t\tRun in Tool mode\n"
197                 "\t-c cookie\tSync cookie of consumer\n"
198                 "\t-d level\tDebug level" "\n"
199                 "\t-f filename\tConfiguration file\n"
200                 "\t-F dir\tConfiguration directory\n"
201 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
202                 "\t-g group\tGroup (id or name) to run as\n"
203 #endif
204                 "\t-h URLs\t\tList of URLs to serve\n"
205 #ifdef LOG_LOCAL4
206                 "\t-l facility\tSyslog facility (default: LOCAL4)\n"
207 #endif
208                 "\t-n serverName\tService name\n"
209                 "\t-o <opt>[=val] generic means to specify options" );
210         if ( !BER_BVISNULL( &option_helpers[0].oh_name ) ) {
211                 int     i;
212
213                 fprintf( stderr, "; supported options:\n" );
214                 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++) {
215                         fprintf( stderr, "\t\t%s\n", option_helpers[i].oh_usage );
216                 }
217         } else {
218                 fprintf( stderr, "\n" );
219         }
220         fprintf( stderr,        
221 #ifdef HAVE_CHROOT
222                 "\t-r directory\tSandbox directory to chroot to\n"
223 #endif
224                 "\t-s level\tSyslog level\n"
225 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
226                 "\t-u user\t\tUser (id or name) to run as\n"
227 #endif
228                 "\t-V\t\tprint version info (-VV only)\n"
229     );
230 }
231
232 #ifdef HAVE_NT_SERVICE_MANAGER
233 void WINAPI ServiceMain( DWORD argc, LPTSTR *argv )
234 #else
235 int main( int argc, char **argv )
236 #endif
237 {
238         int             i, no_detach = 0;
239         int             rc = 1;
240         char *urls = NULL;
241 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
242         char *username = NULL;
243         char *groupname = NULL;
244 #endif
245 #if defined(HAVE_CHROOT)
246         char *sandbox = NULL;
247 #endif
248 #ifdef LOG_LOCAL4
249     int     syslogUser = DEFAULT_SYSLOG_USER;
250 #endif
251         
252         int g_argc = argc;
253         char **g_argv = argv;
254
255 #ifdef HAVE_NT_SERVICE_MANAGER
256         char            *configfile = ".\\slapd.conf";
257         char            *configdir = ".\\slapd.d";
258 #else
259         char            *configfile = SLAPD_DEFAULT_CONFIGFILE;
260         char            *configdir = SLAPD_DEFAULT_CONFIGDIR;
261 #endif
262         char        *serverName;
263         int         serverMode = SLAP_SERVER_MODE;
264
265         struct sync_cookie *scp = NULL;
266         struct sync_cookie *scp_entry = NULL;
267
268 #ifdef CSRIMALLOC
269         FILE *leakfile;
270         if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
271                 leakfile = stderr;
272         }
273 #endif
274         char    *serverNamePrefix = "";
275         size_t  l;
276
277         slap_sl_mem_init();
278
279         serverName = lutil_progname( "slapd", argc, argv );
280
281         if ( strcmp( serverName, "slapd" ) ) {
282                 for (i=0; tools[i].name; i++) {
283                         if ( !strcmp( serverName, tools[i].name ) ) {
284                                 rc = tools[i].func(argc, argv);
285                                 MAIN_RETURN(rc);
286                         }
287                 }
288         }
289
290 #ifdef HAVE_NT_SERVICE_MANAGER
291         {
292                 int *i;
293                 char *newConfigFile;
294                 char *newConfigDir;
295                 char *newUrls;
296                 char *regService = NULL;
297
298                 if ( is_NT_Service ) {
299                         lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
300                         if ( strcmp(serverName, SERVICE_NAME) )
301                             regService = serverName;
302                 }
303
304                 i = (int*)lutil_getRegParam( regService, "DebugLevel" );
305                 if ( i != NULL ) {
306                         slap_debug = *i;
307                         Debug( LDAP_DEBUG_ANY,
308                                 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
309                 }
310
311                 newUrls = (char *) lutil_getRegParam(regService, "Urls");
312                 if (newUrls) {
313                     if (urls)
314                         ch_free(urls);
315
316                     urls = ch_strdup(newUrls);
317                     Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
318                                 urls, 0, 0);
319                 }
320
321                 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
322                 if ( newConfigFile != NULL ) {
323                         configfile = newConfigFile;
324                         Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
325                 }
326
327                 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
328                 if ( newConfigDir != NULL ) {
329                         configdir = newConfigDir;
330                         Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
331                 }
332         }
333 #endif
334
335         while ( (i = getopt( argc, argv,
336                              "c:d:f:F:h:n:o:s:StT:V"
337 #if LDAP_PF_INET6
338                                 "46"
339 #endif
340 #ifdef HAVE_CHROOT
341                                 "r:"
342 #endif
343 #ifdef LOG_LOCAL4
344                              "l:"
345 #endif
346 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
347                              "u:g:"
348 #endif
349                              )) != EOF ) {
350                 switch ( i ) {
351 #ifdef LDAP_PF_INET6
352                 case '4':
353                         slap_inet4or6 = AF_INET;
354                         break;
355                 case '6':
356                         slap_inet4or6 = AF_INET6;
357                         break;
358 #endif
359
360                 case 'h':       /* listen URLs */
361                         if ( urls != NULL ) free( urls );
362                         urls = ch_strdup( optarg );
363                         break;
364
365                 case 'c':       /* provide sync cookie, override if exist in replica */
366                         scp = (struct sync_cookie *) ch_calloc( 1,
367                                                                                 sizeof( struct sync_cookie ));
368                         ber_str2bv( optarg, 0, 1, &scp->octet_str );
369                         slap_parse_sync_cookie( scp );
370
371                         LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
372                                 if ( scp->rid == scp_entry->rid ) {
373                                         Debug( LDAP_DEBUG_ANY,
374                                                     "main: duplicated replica id in cookies\n",
375                                                         0, 0, 0 );
376                                         slap_sync_cookie_free( scp, 1 );
377                                         goto destroy;
378                                 }
379                         }
380                         LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
381                         break;
382
383                 case 'd':       /* set debug level and 'do not detach' flag */
384                         no_detach = 1;
385 #ifdef LDAP_DEBUG
386                         slap_debug |= atoi( optarg );
387 #else
388                         if ( atoi( optarg ) != 0 )
389                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
390                                        stderr );
391 #endif
392                         break;
393
394                 case 'f':       /* read config file */
395                         configfile = ch_strdup( optarg );
396                         break;
397
398                 case 'F':       /* use config dir */
399                         configdir = ch_strdup( optarg );
400                         break;
401
402                 case 'o': {
403                         char            *val = strchr( optarg, '=' );
404                         struct berval   opt;
405                         int             i;
406
407                         opt.bv_val = optarg;
408                         
409                         if ( val ) {
410                                 opt.bv_len = ( val - optarg );
411                                 val++;
412                         
413                         } else {
414                                 opt.bv_len = strlen( optarg );
415                         }
416
417                         for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
418                                 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
419                                         assert( option_helpers[i].oh_fnc != NULL );
420                                         if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
421                                                 /* we assume the option parsing helper
422                                                  * issues appropriate and self-explanatory
423                                                  * error messages... */
424                                                 goto stop;
425                                         }
426                                         break;
427                                 }
428                         }
429
430                         if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
431                                 goto unhandled_option;
432                         }
433                         break;
434                 }
435
436                 case 's':       /* set syslog level */
437                         ldap_syslog = atoi( optarg );
438                         break;
439
440 #ifdef LOG_LOCAL4
441                 case 'l':       /* set syslog local user */
442                         syslogUser = cnvt_str2int( optarg,
443                                 syslog_types, DEFAULT_SYSLOG_USER );
444                         break;
445 #endif
446
447 #ifdef HAVE_CHROOT
448                 case 'r':
449                         if( sandbox ) free(sandbox);
450                         sandbox = ch_strdup( optarg );
451                         break;
452 #endif
453
454 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
455                 case 'u':       /* user name */
456                         if( username ) free(username);
457                         username = ch_strdup( optarg );
458                         break;
459
460                 case 'g':       /* group name */
461                         if( groupname ) free(groupname);
462                         groupname = ch_strdup( optarg );
463                         break;
464 #endif /* SETUID && GETUID */
465
466                 case 'n':  /* NT service name */
467                         serverName = ch_strdup( optarg );
468                         break;
469
470                 case 't':
471                         /* deprecated; use slaptest instead */
472                         fprintf( stderr, "option -t deprecated; "
473                                 "use slaptest command instead\n" );
474                         check |= CHECK_CONFIG;
475                         break;
476
477                 case 'V':
478                         version++;
479                         break;
480
481                 case 'T':
482                         /* try full option string first */
483                         for ( i = 0; tools[i].name; i++ ) {
484                                 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
485                                         rc = tools[i].func( argc, argv );
486                                         MAIN_RETURN( rc );
487                                 }
488                         }
489
490                         /* try bits of option string (backward compatibility for single char) */
491                         l = strlen( optarg );
492                         for ( i = 0; tools[i].name; i++ ) {
493                                 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
494                                         rc = tools[i].func( argc, argv );
495                                         MAIN_RETURN( rc );
496                                 }
497                         }
498                         
499                         /* issue error */
500                         serverName = optarg;
501                         serverNamePrefix = "slap";
502                         fprintf( stderr, "program name \"%s%s\" unrecognized; "
503                                         "aborting...\n", serverNamePrefix, serverName );
504                         /* FALLTHRU */
505                 default:
506 unhandled_option:;
507                         usage( argv[0] );
508                         rc = 1;
509                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
510                         goto stop;
511                 }
512         }
513
514         (void) ldap_pvt_thread_initialize();
515
516         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
517         ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
518         ldif_debug = slap_debug;
519
520         if ( version ) {
521                 fprintf( stderr, "%s\n", Versionstr );
522                 if ( version > 1 ) goto stop;
523         }
524
525         {
526                 char *logName;
527 #ifdef HAVE_EBCDIC
528                 logName = ch_strdup( serverName );
529                 __atoe( logName );
530 #else
531                 logName = serverName;
532 #endif
533
534 #ifdef LOG_LOCAL4
535                 openlog( logName, OPENLOG_OPTIONS, syslogUser );
536 #elif LOG_DEBUG
537                 openlog( logName, OPENLOG_OPTIONS );
538 #endif
539 #ifdef HAVE_EBCDIC
540                 free( logName );
541 #endif
542         }
543
544         Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
545
546         if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
547                 rc = 1;
548                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
549                 goto stop;
550         }
551
552 #if defined(HAVE_CHROOT)
553         if ( sandbox ) {
554                 if ( chdir( sandbox ) ) {
555                         perror("chdir");
556                         rc = 1;
557                         goto stop;
558                 }
559                 if ( chroot( sandbox ) ) {
560                         perror("chroot");
561                         rc = 1;
562                         goto stop;
563                 }
564         }
565 #endif
566
567 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
568         if ( username != NULL || groupname != NULL ) {
569                 slap_init_user( username, groupname );
570         }
571 #endif
572
573         extops_init();
574         lutil_passwd_init();
575         slap_op_init();
576
577 #ifdef SLAPD_MODULES
578         if ( module_init() != 0 ) {
579                 rc = 1;
580                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 17 );
581                 goto destroy;
582         }
583 #endif
584
585         if ( slap_schema_init( ) != 0 ) {
586                 Debug( LDAP_DEBUG_ANY,
587                     "schema initialization error\n",
588                     0, 0, 0 );
589
590                 goto destroy;
591         }
592
593         if ( slap_init( serverMode, serverName ) != 0 ) {
594                 rc = 1;
595                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
596                 goto destroy;
597         }
598
599         if ( slap_controls_init( ) != 0 ) {
600                 Debug( LDAP_DEBUG_ANY,
601                     "controls initialization error\n",
602                     0, 0, 0 );
603
604                 goto destroy;
605         }
606
607 #ifdef HAVE_TLS
608         /* Library defaults to full certificate checking. This is correct when
609          * a client is verifying a server because all servers should have a
610          * valid cert. But few clients have valid certs, so we want our default
611          * to be no checking. The config file can override this as usual.
612          */
613         rc = 0;
614         (void) ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &rc );
615 #endif
616
617 #ifdef LDAP_SLAPI
618         if ( slapi_int_initialize() != 0 ) {
619                 Debug( LDAP_DEBUG_ANY,
620                     "slapi initialization error\n",
621                     0, 0, 0 );
622
623                 goto destroy;
624         }
625 #endif /* LDAP_SLAPI */
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, urls );
782 #endif
783
784         rc = slapd_daemon();
785
786 #ifdef HAVE_NT_SERVICE_MANAGER
787         /* Throw away the event that we used during the startup process. */
788         if ( is_NT_Service )
789                 ldap_pvt_thread_cond_destroy( &started_event );
790 #endif
791
792 shutdown:
793         /* remember an error during shutdown */
794         rc |= slap_shutdown( NULL );
795
796 destroy:
797         /* remember an error during destroy */
798         rc |= slap_destroy();
799
800         while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
801                 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
802                 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
803                 ch_free( scp );
804         }
805
806 #ifdef SLAPD_MODULES
807         module_kill();
808 #endif
809
810         slap_op_destroy();
811
812         extops_kill();
813
814 stop:
815 #ifdef HAVE_NT_EVENT_LOG
816         if (is_NT_Service)
817         lutil_LogStoppedEvent( serverName );
818 #endif
819
820         Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
821
822
823 #ifdef HAVE_NT_SERVICE_MANAGER
824         lutil_ReportShutdownComplete();
825 #endif
826
827 #ifdef LOG_DEBUG
828     closelog();
829 #endif
830         slapd_daemon_destroy();
831
832         controls_destroy();
833
834         schema_destroy();
835
836         lutil_passwd_destroy();
837
838 #ifdef HAVE_TLS
839         ldap_pvt_tls_destroy();
840 #endif
841
842         if ( slapd_pid_file != NULL ) {
843                 unlink( slapd_pid_file );
844         }
845         if ( slapd_args_file != NULL ) {
846                 unlink( slapd_args_file );
847         }
848
849         config_destroy();
850
851 #ifdef CSRIMALLOC
852         mal_dumpleaktrace( leakfile );
853 #endif
854
855         MAIN_RETURN(rc);
856 }
857
858
859 #ifdef LDAP_SIGCHLD
860
861 /*
862  *  Catch and discard terminated child processes, to avoid zombies.
863  */
864
865 static RETSIGTYPE
866 wait4child( int sig )
867 {
868     int save_errno = errno;
869
870 #ifdef WNOHANG
871     errno = 0;
872 #ifdef HAVE_WAITPID
873     while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
874         ;       /* NULL */
875 #else
876     while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
877         ;       /* NULL */
878 #endif
879 #else
880     (void) wait( NULL );
881 #endif
882     (void) SIGNAL_REINSTALL( sig, wait4child );
883     errno = save_errno;
884 }
885
886 #endif /* LDAP_SIGCHLD */
887
888
889 #ifdef LOG_LOCAL4
890
891 /*
892  *  Convert a string to an integer by means of a dispatcher table
893  *  if the string is not in the table return the default
894  */
895
896 static int
897 cnvt_str2int( char *stringVal, STRDISP_P dispatcher, int defaultVal )
898 {
899     int        retVal = defaultVal;
900     STRDISP_P  disp;
901
902     for (disp = dispatcher; disp->stringVal; disp++) {
903
904         if (!strncasecmp (stringVal, disp->stringVal, disp->abbr)) {
905
906             retVal = disp->intVal;
907             break;
908
909         }
910     }
911
912     return (retVal);
913 }
914
915 #endif  /* LOG_LOCAL4 */