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