]> git.sur5r.net Git - openldap/blob - servers/slapd/main.c
fix previous commit
[openldap] / servers / slapd / main.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2004 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 "ldap_pvt.h"
38
39 #include "slap.h"
40 #include "lutil.h"
41 #include "ldif.h"
42
43 #ifdef LDAP_SLAPI
44 #include "slapi/slapi.h"
45 #endif
46
47 #ifdef LDAP_SIGCHLD
48 static RETSIGTYPE wait4child( int sig );
49 #endif
50
51 #ifdef HAVE_NT_SERVICE_MANAGER
52 #define MAIN_RETURN(x) return
53 static struct sockaddr_in       bind_addr;
54
55 #define SERVICE_EXIT( e, n )    do { \
56         if ( is_NT_Service ) { \
57                 lutil_ServiceStatus.dwWin32ExitCode                             = (e); \
58                 lutil_ServiceStatus.dwServiceSpecificExitCode   = (n); \
59         } \
60 } while ( 0 )
61
62 #else
63 #define SERVICE_EXIT( e, n )
64 #define MAIN_RETURN(x) return(x)
65 #endif
66
67 typedef int (MainFunc) LDAP_P(( int argc, char *argv[] ));
68 extern MainFunc slapadd, slapcat, slapdn, slapindex, slappasswd,
69         slaptest, slapauth, slapacl;
70
71 static struct {
72         char *name;
73         MainFunc *func;
74 } tools[] = {
75         {"slapadd", slapadd},
76         {"slapcat", slapcat},
77         {"slapdn", slapdn},
78         {"slapindex", slapindex},
79         {"slappasswd", slappasswd},
80         {"slaptest", slaptest},
81         {"slapauth", slapauth},
82         {"slapacl", slapacl},
83         /* NOTE: new tools must be added in chronological order,
84          * not in alphabetical order, because for backwards
85          * compatibility name[4] is used to identify the
86          * tools; so name[4]=='a' must refer to "slapadd" and
87          * not to "slapauth".  Alphabetical order can be used
88          * for tools whose name[4] is not used yet */
89         {NULL, NULL}
90 };
91
92 /*
93  * when more than one slapd is running on one machine, each one might have
94  * it's own LOCAL for syslogging and must have its own pid/args files
95  */
96
97 #ifndef HAVE_MKVERSION
98 const char Versionstr[] =
99         OPENLDAP_PACKAGE " " OPENLDAP_VERSION " Standalone LDAP Server (slapd)";
100 #endif
101
102 #ifdef LOG_LOCAL4
103
104 #define DEFAULT_SYSLOG_USER  LOG_LOCAL4
105
106 typedef struct _str2intDispatch {
107         char    *stringVal;
108         int      abbr;
109         int      intVal;
110 } STRDISP, *STRDISP_P;
111
112
113 /* table to compute syslog-options to integer */
114 static STRDISP  syslog_types[] = {
115         { "LOCAL0", sizeof("LOCAL0"), LOG_LOCAL0 },
116         { "LOCAL1", sizeof("LOCAL1"), LOG_LOCAL1 },
117         { "LOCAL2", sizeof("LOCAL2"), LOG_LOCAL2 },
118         { "LOCAL3", sizeof("LOCAL3"), LOG_LOCAL3 },
119         { "LOCAL4", sizeof("LOCAL4"), LOG_LOCAL4 },
120         { "LOCAL5", sizeof("LOCAL5"), LOG_LOCAL5 },
121         { "LOCAL6", sizeof("LOCAL6"), LOG_LOCAL6 },
122         { "LOCAL7", sizeof("LOCAL7"), LOG_LOCAL7 },
123         { NULL, 0, 0 }
124 };
125
126 static int   cnvt_str2int( char *, STRDISP_P, int );
127
128 #endif  /* LOG_LOCAL4 */
129
130 #define CHECK_NONE      0x00
131 #define CHECK_CONFIG    0x01
132 static int check = CHECK_NONE;
133 static int version = 0;
134
135 void *slap_tls_ctx;
136
137 static int
138 slapd_opt_slp( const char *val, void *arg )
139 {
140 #ifdef HAVE_SLP
141         /* NULL is default */
142         if ( val == NULL || strcasecmp( val, "on" ) == 0 ) {
143                 slapd_register_slp = 1;
144
145         } else if ( strcasecmp( val, "off" ) == 0 ) {
146                 slapd_register_slp = 0;
147
148         /* NOTE: add support for URL specification? */
149
150         } else {
151                 fprintf(stderr, "unrecognized value \"%s\" for SLP option\n", val );
152                 return -1;
153         }
154
155         return 0;
156                 
157 #else
158         fputs( "slapd: SLP support is not available\n", stderr );
159         return 0;
160 #endif
161 }
162
163 struct option_helper {
164         struct berval   oh_name;
165         int             (*oh_fnc)(const char *val, void *arg);
166         void            *oh_arg;
167 } option_helpers[] = {
168         { BER_BVC("slp"),       slapd_opt_slp,  NULL },
169         { BER_BVNULL }
170 };
171
172 static void
173 usage( char *name )
174 {
175         fprintf( stderr,
176                 "usage: %s options\n", name );
177         fprintf( stderr,
178                 "\t-4\t\tIPv4 only\n"
179                 "\t-6\t\tIPv6 only\n"
180                 "\t-T {add|auth|cat|dn|index|passwd|test}\n"
181                 "\t\t\tRun in Tool mode\n"
182                 "\t-c cookie\tSync cookie of consumer\n"
183                 "\t-d level\tDebug level" "\n"
184                 "\t-f filename\tConfiguration file\n"
185 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
186                 "\t-g group\tGroup (id or name) to run as\n"
187 #endif
188                 "\t-h URLs\t\tList of URLs to serve\n"
189 #ifdef LOG_LOCAL4
190                 "\t-l facility\tSyslog facility (default: LOCAL4)\n"
191 #endif
192                 "\t-n serverName\tService name\n"
193                 "\t-o <opt>[=val]\tGeneric means to specify options; details in slapd(8)\n"
194 #ifdef HAVE_CHROOT
195                 "\t-r directory\tSandbox directory to chroot to\n"
196 #endif
197                 "\t-s level\tSyslog level\n"
198 #ifdef HAVE_SLP
199                 "\t-S enable SLP registration\n"
200 #endif
201 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
202                 "\t-u user\t\tUser (id or name) to run as\n"
203 #endif
204                 "\t-V\t\tprint version info (-VV only)\n"
205     );
206 }
207
208 #ifdef HAVE_NT_SERVICE_MANAGER
209 void WINAPI ServiceMain( DWORD argc, LPTSTR *argv )
210 #else
211 int main( int argc, char **argv )
212 #endif
213 {
214         int             i, no_detach = 0;
215         int             rc = 1;
216         char *urls = NULL;
217 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
218         char *username = NULL;
219         char *groupname = NULL;
220 #endif
221 #if defined(HAVE_CHROOT)
222         char *sandbox = NULL;
223 #endif
224 #ifdef LOG_LOCAL4
225     int     syslogUser = DEFAULT_SYSLOG_USER;
226 #endif
227         
228         int g_argc = argc;
229         char **g_argv = argv;
230
231 #ifdef HAVE_NT_SERVICE_MANAGER
232         char            *configfile = ".\\slapd.conf";
233 #else
234         char            *configfile = SLAPD_DEFAULT_CONFIGFILE;
235 #endif
236         char        *serverName;
237         int         serverMode = SLAP_SERVER_MODE;
238
239         struct berval cookie = BER_BVNULL;
240         struct sync_cookie *scp = NULL;
241         struct sync_cookie *scp_entry = NULL;
242
243 #ifdef CSRIMALLOC
244         FILE *leakfile;
245         if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
246                 leakfile = stderr;
247         }
248 #endif
249         char    *serverNamePrefix = "";
250         size_t  l;
251
252         slap_sl_mem_init();
253
254         serverName = lutil_progname( "slapd", argc, argv );
255
256         if ( strcmp( serverName, "slapd" ) ) {
257                 for (i=0; tools[i].name; i++) {
258                         if ( !strcmp( serverName, tools[i].name ) ) {
259                                 rc = tools[i].func(argc, argv);
260                                 MAIN_RETURN(rc);
261                         }
262                 }
263         }
264
265 #ifdef HAVE_NT_SERVICE_MANAGER
266         {
267                 int *i;
268                 char *newConfigFile;
269                 char *newUrls;
270                 char *regService = NULL;
271
272                 if ( is_NT_Service ) {
273                         lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
274                         if ( strcmp(serverName, SERVICE_NAME) )
275                             regService = serverName;
276                 }
277
278                 i = (int*)lutil_getRegParam( regService, "DebugLevel" );
279                 if ( i != NULL ) {
280                         slap_debug = *i;
281 #ifdef NEW_LOGGING
282                         lutil_log_initialize( argc, argv );
283                         LDAP_LOG( SLAPD, INFO, 
284                                 "main: new debug level from registry is: %d\n", 
285                                 slap_debug, 0, 0 );
286 #else
287                         Debug( LDAP_DEBUG_ANY,
288                                 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
289 #endif
290                 }
291
292                 newUrls = (char *) lutil_getRegParam(regService, "Urls");
293                 if (newUrls) {
294                     if (urls)
295                         ch_free(urls);
296
297                     urls = ch_strdup(newUrls);
298 #ifdef NEW_LOGGING
299                     LDAP_LOG( SLAPD, INFO, 
300                                 "main: new urls from registry: %s\n", urls, 0, 0 );
301 #else
302                     Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
303                                 urls, 0, 0);
304 #endif
305                 }
306
307                 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
308                 if ( newConfigFile != NULL ) {
309                         configfile = newConfigFile;
310 #ifdef NEW_LOGGING
311                         LDAP_LOG( SLAPD, INFO, 
312                                 "main: new config file from registry is: %s\n", configfile, 0, 0 );
313 #else
314                         Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
315 #endif
316                 }
317         }
318 #endif
319
320         while ( (i = getopt( argc, argv,
321                              "c:d:f:h:n:o:s:StT:V"
322 #if LDAP_PF_INET6
323                                 "46"
324 #endif
325 #ifdef HAVE_CHROOT
326                                 "r:"
327 #endif
328 #ifdef LOG_LOCAL4
329                              "l:"
330 #endif
331 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
332                              "u:g:"
333 #endif
334                              )) != EOF ) {
335                 switch ( i ) {
336 #ifdef LDAP_PF_INET6
337                 case '4':
338                         slap_inet4or6 = AF_INET;
339                         break;
340                 case '6':
341                         slap_inet4or6 = AF_INET6;
342                         break;
343 #endif
344
345                 case 'h':       /* listen URLs */
346                         if ( urls != NULL ) free( urls );
347                         urls = ch_strdup( optarg );
348                         break;
349
350                 case 'c':       /* provide sync cookie, override if exist in replica */
351                         scp = (struct sync_cookie *) ch_calloc( 1,
352                                                                                 sizeof( struct sync_cookie ));
353                         ber_str2bv( optarg, strlen( optarg ), 1, &cookie );
354                         ber_bvarray_add( &scp->octet_str, &cookie );
355                         slap_parse_sync_cookie( scp );
356
357                         LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
358                                 if ( scp->rid == scp_entry->rid ) {
359 #ifdef NEW_LOGGING
360                                         LDAP_LOG( OPERATION, CRIT,
361                                                         "main: duplicated replica id in cookies\n",
362                                                         0, 0, 0 );
363 #else
364                                         Debug( LDAP_DEBUG_ANY,
365                                                     "main: duplicated replica id in cookies\n",
366                                                         0, 0, 0 );
367 #endif
368                                         slap_sync_cookie_free( scp, 1 );
369                                         goto destroy;
370                                 }
371                         }
372                         LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
373                         break;
374
375                 case 'd':       /* set debug level and 'do not detach' flag */
376                         no_detach = 1;
377 #ifdef LDAP_DEBUG
378                         slap_debug |= atoi( optarg );
379 #else
380                         if ( atoi( optarg ) != 0 )
381                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
382                                        stderr );
383 #endif
384                         break;
385
386                 case 'f':       /* read config file */
387                         configfile = ch_strdup( optarg );
388                         break;
389
390                 case 'o': {
391                         char            *val = strchr( optarg, '=' );
392                         struct berval   opt;
393                         int             i;
394
395                         opt.bv_val = optarg;
396                         
397                         if ( val ) {
398                                 opt.bv_len = ( val - optarg );
399                                 val++;
400                         
401                         } else {
402                                 opt.bv_len = strlen( optarg );
403                         }
404
405                         for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
406                                 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
407                                         assert( option_helpers[i].oh_fnc != NULL );
408                                         if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
409                                                 /* we assume the option parsing helper
410                                                  * issues appropriate and self-explanatory
411                                                  * error messages... */
412                                                 goto stop;
413                                         }
414                                         break;
415                                 }
416                         }
417
418                         if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
419                                 goto unhandled_option;
420                         }
421                         break;
422                 }
423
424                 case 's':       /* set syslog level */
425                         ldap_syslog = atoi( optarg );
426                         break;
427
428                 case 'S':       /* enable SLP */
429 #ifdef HAVE_SLP
430                         slapd_register_slp++;
431 #else
432                         fputs( "slapd: SLP support is not available\n", stderr );
433 #endif
434                         break;
435
436 #ifdef LOG_LOCAL4
437                 case 'l':       /* set syslog local user */
438                         syslogUser = cnvt_str2int( optarg,
439                         syslog_types, DEFAULT_SYSLOG_USER );
440                         break;
441 #endif
442
443 #ifdef HAVE_CHROOT
444                 case 'r':
445                         if( sandbox ) free(sandbox);
446                         sandbox = ch_strdup( optarg );
447                         break;
448 #endif
449
450 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
451                 case 'u':       /* user name */
452                         if( username ) free(username);
453                         username = ch_strdup( optarg );
454                         break;
455
456                 case 'g':       /* group name */
457                         if( groupname ) free(groupname);
458                         groupname = ch_strdup( optarg );
459                         break;
460 #endif /* SETUID && GETUID */
461
462                 case 'n':  /* NT service name */
463                         serverName = ch_strdup( optarg );
464                         break;
465
466                 case 't':
467                         /* deprecated; use slaptest instead */
468                         fprintf( stderr, "option -t deprecated; "
469                                 "use slaptest command instead\n" );
470                         check |= CHECK_CONFIG;
471                         break;
472
473                 case 'V':
474                         version++;
475                         break;
476
477                 case 'T':
478                         /* try full option string first */
479                         for ( i = 0; tools[i].name; i++ ) {
480                                 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
481                                         rc = tools[i].func( argc, argv );
482                                         MAIN_RETURN( rc );
483                                 }
484                         }
485
486                         /* try bits of option string (backward compatibility for single char) */
487                         l = strlen( optarg );
488                         for ( i = 0; tools[i].name; i++ ) {
489                                 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
490                                         rc = tools[i].func( argc, argv );
491                                         MAIN_RETURN( rc );
492                                 }
493                         }
494                         
495                         /* issue error */
496                         serverName = optarg;
497                         serverNamePrefix = "slap";
498                         fprintf( stderr, "program name \"%s%s\" unrecognized; "
499                                         "aborting...\n", serverNamePrefix, serverName );
500                         /* FALLTHRU */
501                 default:
502 unhandled_option:;
503                         usage( argv[0] );
504                         rc = 1;
505                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
506                         goto stop;
507                 }
508         }
509
510 #ifdef NEW_LOGGING
511         lutil_log_initialize( argc, argv );
512 #else
513         lutil_set_debug_level( "slapd", slap_debug );
514         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
515         ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
516         ldif_debug = slap_debug;
517 #endif
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 #ifdef NEW_LOGGING
544         LDAP_LOG( SLAPD, INFO, "%s", Versionstr, 0, 0 );
545 #else
546         Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
547 #endif
548
549         if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
550                 rc = 1;
551                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
552                 goto stop;
553         }
554
555 #if defined(HAVE_CHROOT)
556         if ( sandbox ) {
557                 if ( chdir( sandbox ) ) {
558                         perror("chdir");
559                         rc = 1;
560                         goto stop;
561                 }
562                 if ( chroot( sandbox ) ) {
563                         perror("chroot");
564                         rc = 1;
565                         goto stop;
566                 }
567         }
568 #endif
569
570 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
571         if ( username != NULL || groupname != NULL ) {
572                 slap_init_user( username, groupname );
573         }
574 #endif
575
576         extops_init();
577         lutil_passwd_init();
578         slap_op_init();
579
580 #ifdef SLAPD_MODULES
581         if ( module_init() != 0 ) {
582                 rc = 1;
583                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 17 );
584                 goto destroy;
585         }
586 #endif
587
588         if ( slap_schema_init( ) != 0 ) {
589 #ifdef NEW_LOGGING
590                 LDAP_LOG( OPERATION, CRIT, "main: schema initialization error\n", 0, 0, 0 );
591 #else
592                 Debug( LDAP_DEBUG_ANY,
593                     "schema initialization error\n",
594                     0, 0, 0 );
595 #endif
596
597                 goto destroy;
598         }
599
600         if ( slap_init( serverMode, serverName ) != 0 ) {
601                 rc = 1;
602                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
603                 goto destroy;
604         }
605
606         if ( slap_controls_init( ) != 0 ) {
607 #ifdef NEW_LOGGING
608                 LDAP_LOG( OPERATION, CRIT, "main: controls initialization error\n", 0, 0, 0 );
609 #else
610                 Debug( LDAP_DEBUG_ANY,
611                     "controls initialization error\n",
612                     0, 0, 0 );
613 #endif
614
615                 goto destroy;
616         }
617
618 #ifdef HAVE_TLS
619         /* Library defaults to full certificate checking. This is correct when
620          * a client is verifying a server because all servers should have a
621          * valid cert. But few clients have valid certs, so we want our default
622          * to be no checking. The config file can override this as usual.
623          */
624         rc = 0;
625         (void) ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &rc );
626 #endif
627
628 #ifdef LDAP_SLAPI
629         if ( slapi_int_initialize() != 0 ) {
630 #ifdef NEW_LOGGING
631                 LDAP_LOG( OPERATION, CRIT, "main: slapi initialization error\n", 0, 0, 0 );
632 #else
633                 Debug( LDAP_DEBUG_ANY,
634                     "slapi initialization error\n",
635                     0, 0, 0 );
636 #endif
637
638                 goto destroy;
639         }
640 #endif /* LDAP_SLAPI */
641
642         if ( overlay_init() ) {
643                 goto destroy;
644         }
645
646         if ( read_config( configfile, 0 ) != 0 ) {
647                 rc = 1;
648                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
649
650                 if ( check & CHECK_CONFIG ) {
651                         fprintf( stderr, "config check failed\n" );
652                 }
653
654                 goto destroy;
655         }
656
657         if ( check & CHECK_CONFIG ) {
658                 fprintf( stderr, "config check succeeded\n" );
659
660                 check &= ~CHECK_CONFIG;
661                 if ( check == CHECK_NONE ) {
662                         rc = 0;
663                         goto destroy;
664                 }
665         }
666
667         if ( glue_sub_init( ) != 0 ) {
668 #ifdef NEW_LOGGING
669                 LDAP_LOG( SLAPD, CRIT, "main: subordinate config error\n", 0, 0, 0 );
670 #else
671                 Debug( LDAP_DEBUG_ANY,
672                     "subordinate config error\n",
673                     0, 0, 0 );
674 #endif
675                 goto destroy;
676         }
677
678         if ( slap_schema_check( ) != 0 ) {
679 #ifdef NEW_LOGGING
680                 LDAP_LOG( SLAPD, CRIT, "main: schema prep error\n", 0, 0, 0 );
681 #else
682                 Debug( LDAP_DEBUG_ANY,
683                     "schema prep error\n",
684                     0, 0, 0 );
685 #endif
686
687                 goto destroy;
688         }
689
690 #ifdef HAVE_TLS
691         rc = ldap_pvt_tls_init();
692         if( rc != 0) {
693 #ifdef NEW_LOGGING
694                 LDAP_LOG( SLAPD, CRIT, "main: tls init failed: %d\n", rc, 0, 0 );
695 #else
696                 Debug( LDAP_DEBUG_ANY,
697                     "main: TLS init failed: %d\n",
698                     0, 0, 0 );
699 #endif
700                 rc = 1;
701                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
702                 goto destroy;
703         }
704
705         {
706                 void *def_ctx = NULL;
707
708                 /* Save existing default ctx, if any */
709                 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &def_ctx );
710
711                 /* Force new ctx to be created */
712                 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, NULL );
713
714                 rc = ldap_pvt_tls_init_def_ctx();
715                 if( rc != 0) {
716 #ifdef NEW_LOGGING
717                         LDAP_LOG( SLAPD, CRIT, "main: tls init def ctx failed: %d\n", rc, 0, 0 );
718 #else
719                         Debug( LDAP_DEBUG_ANY,
720                             "main: TLS init def ctx failed: %d\n",
721                             rc, 0, 0 );
722 #endif
723                         rc = 1;
724                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
725                         goto destroy;
726                 }
727                 /* Retrieve slapd's own ctx */
728                 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
729                 /* Restore previous ctx */
730                 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, def_ctx );
731         }
732 #endif
733
734         (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
735         (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
736
737 #ifdef SIGPIPE
738         (void) SIGNAL( SIGPIPE, SIG_IGN );
739 #endif
740 #ifdef SIGHUP
741         (void) SIGNAL( SIGHUP, slap_sig_shutdown );
742 #endif
743         (void) SIGNAL( SIGINT, slap_sig_shutdown );
744         (void) SIGNAL( SIGTERM, slap_sig_shutdown );
745 #ifdef LDAP_SIGCHLD
746         (void) SIGNAL( LDAP_SIGCHLD, wait4child );
747 #endif
748 #ifdef SIGBREAK
749         /* SIGBREAK is generated when Ctrl-Break is pressed. */
750         (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
751 #endif
752
753 #ifndef HAVE_WINSOCK
754         lutil_detach( no_detach, 0 );
755 #endif /* HAVE_WINSOCK */
756
757 #ifdef CSRIMALLOC
758         mal_leaktrace(1);
759 #endif
760
761         /*
762          * FIXME: moved here from slapd_daemon_task()
763          * because back-monitor db_open() needs it
764          */
765         time( &starttime );
766
767         if ( slap_startup( NULL )  != 0 ) {
768                 rc = 1;
769                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
770                 goto shutdown;
771         }
772
773 #ifdef NEW_LOGGING
774         LDAP_LOG( SLAPD, INFO, "main: slapd starting.\n", 0, 0, 0 );
775 #else
776         Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
777 #endif
778
779
780         if ( slapd_pid_file != NULL ) {
781                 FILE *fp = fopen( slapd_pid_file, "w" );
782
783                 if( fp != NULL ) {
784                         fprintf( fp, "%d\n", (int) getpid() );
785                         fclose( fp );
786
787                 } else {
788                         free(slapd_pid_file);
789                         slapd_pid_file = NULL;
790                 }
791         }
792
793         if ( slapd_args_file != NULL ) {
794                 FILE *fp = fopen( slapd_args_file, "w" );
795
796                 if( fp != NULL ) {
797                         for ( i = 0; i < g_argc; i++ ) {
798                                 fprintf( fp, "%s ", g_argv[i] );
799                         }
800                         fprintf( fp, "\n" );
801                         fclose( fp );
802                 } else {
803                         free(slapd_args_file);
804                         slapd_args_file = NULL;
805                 }
806         }
807
808 #ifdef HAVE_NT_EVENT_LOG
809         if (is_NT_Service)
810         lutil_LogStartedEvent( serverName, slap_debug, configfile, urls );
811 #endif
812
813         rc = slapd_daemon();
814
815 #ifdef HAVE_NT_SERVICE_MANAGER
816         /* Throw away the event that we used during the startup process. */
817         if ( is_NT_Service )
818                 ldap_pvt_thread_cond_destroy( &started_event );
819 #endif
820
821 shutdown:
822         /* remember an error during shutdown */
823         rc |= slap_shutdown( NULL );
824
825 destroy:
826         /* remember an error during destroy */
827         rc |= slap_destroy();
828
829         while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
830                 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
831                 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
832                 ch_free( scp );
833         }
834
835 #ifdef SLAPD_MODULES
836         module_kill();
837 #endif
838
839         slap_op_destroy();
840
841         extops_kill();
842
843 stop:
844 #ifdef HAVE_NT_EVENT_LOG
845         if (is_NT_Service)
846         lutil_LogStoppedEvent( serverName );
847 #endif
848
849 #ifdef NEW_LOGGING
850         LDAP_LOG( SLAPD, CRIT, "main: slapd stopped.\n", 0, 0, 0 );
851 #else
852         Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
853 #endif
854
855
856 #ifdef HAVE_NT_SERVICE_MANAGER
857         lutil_ReportShutdownComplete();
858 #endif
859
860 #ifdef LOG_DEBUG
861     closelog();
862 #endif
863         slapd_daemon_destroy();
864
865         controls_destroy();
866
867         schema_destroy();
868
869         lutil_passwd_destroy();
870
871 #ifdef HAVE_TLS
872         ldap_pvt_tls_destroy();
873 #endif
874
875         if ( slapd_pid_file != NULL ) {
876                 unlink( slapd_pid_file );
877         }
878         if ( slapd_args_file != NULL ) {
879                 unlink( slapd_args_file );
880         }
881
882         config_destroy();
883
884 #ifdef CSRIMALLOC
885         mal_dumpleaktrace( leakfile );
886 #endif
887
888         MAIN_RETURN(rc);
889 }
890
891
892 #ifdef LDAP_SIGCHLD
893
894 /*
895  *  Catch and discard terminated child processes, to avoid zombies.
896  */
897
898 static RETSIGTYPE
899 wait4child( int sig )
900 {
901     int save_errno = errno;
902
903 #ifdef WNOHANG
904     errno = 0;
905 #ifdef HAVE_WAITPID
906     while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
907         ;       /* NULL */
908 #else
909     while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
910         ;       /* NULL */
911 #endif
912 #else
913     (void) wait( NULL );
914 #endif
915     (void) SIGNAL_REINSTALL( sig, wait4child );
916     errno = save_errno;
917 }
918
919 #endif /* LDAP_SIGCHLD */
920
921
922 #ifdef LOG_LOCAL4
923
924 /*
925  *  Convert a string to an integer by means of a dispatcher table
926  *  if the string is not in the table return the default
927  */
928
929 static int
930 cnvt_str2int( char *stringVal, STRDISP_P dispatcher, int defaultVal )
931 {
932     int        retVal = defaultVal;
933     STRDISP_P  disp;
934
935     for (disp = dispatcher; disp->stringVal; disp++) {
936
937         if (!strncasecmp (stringVal, disp->stringVal, disp->abbr)) {
938
939             retVal = disp->intVal;
940             break;
941
942         }
943     }
944
945     return (retVal);
946 }
947
948 #endif  /* LOG_LOCAL4 */