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