]> git.sur5r.net Git - openldap/blob - servers/slapd/main.c
allow logging to USER and DAEMON (ITS#3187)
[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 #define DEFAULT_SYSLOG_USER  LOG_LOCAL4
104
105 typedef struct _str2intDispatch {
106         char    *stringVal;
107         int      abbr;
108         int      intVal;
109 } STRDISP, *STRDISP_P;
110
111 /* table to compute syslog-options to integer */
112 static STRDISP  syslog_types[] = {
113         { "LOCAL0", sizeof("LOCAL0"), LOG_LOCAL0 },
114         { "LOCAL1", sizeof("LOCAL1"), LOG_LOCAL1 },
115         { "LOCAL2", sizeof("LOCAL2"), LOG_LOCAL2 },
116         { "LOCAL3", sizeof("LOCAL3"), LOG_LOCAL3 },
117         { "LOCAL4", sizeof("LOCAL4"), LOG_LOCAL4 },
118         { "LOCAL5", sizeof("LOCAL5"), LOG_LOCAL5 },
119         { "LOCAL6", sizeof("LOCAL6"), LOG_LOCAL6 },
120         { "LOCAL7", sizeof("LOCAL7"), LOG_LOCAL7 },
121 #ifdef LOG_USER
122         { "USER", sizeof("USER"), LOG_USER },
123 #endif
124 #ifdef LOG_DAEMON
125         { "DAEMON", sizeof("DAEMON"), LOG_DAEMON },
126 #endif
127         { NULL, 0, 0 }
128 };
129
130 static int cnvt_str2int( char *, STRDISP_P, int );
131 #endif  /* LOG_LOCAL4 */
132
133 #define CHECK_NONE      0x00
134 #define CHECK_CONFIG    0x01
135 static int check = CHECK_NONE;
136 static int version = 0;
137
138 void *slap_tls_ctx;
139
140 static int
141 slapd_opt_slp( const char *val, void *arg )
142 {
143 #ifdef HAVE_SLP
144         /* NULL is default */
145         if ( val == NULL || strcasecmp( val, "on" ) == 0 ) {
146                 slapd_register_slp = 1;
147
148         } else if ( strcasecmp( val, "off" ) == 0 ) {
149                 slapd_register_slp = 0;
150
151         /* NOTE: add support for URL specification? */
152
153         } else {
154                 fprintf(stderr, "unrecognized value \"%s\" for SLP option\n", val );
155                 return -1;
156         }
157
158         return 0;
159                 
160 #else
161         fputs( "slapd: SLP support is not available\n", stderr );
162         return 0;
163 #endif
164 }
165
166 /*
167  * Option helper structure:
168  * 
169  * oh_nam       is left-hand part of <option>[=<value>]
170  * oh_fnc       is handler function
171  * oh_arg       is an optional arg to oh_fnc
172  * oh_usage     is the one-line usage string related to the option,
173  *              which is assumed to start with <option>[=<value>]
174  *
175  * please leave valid options in the structure, and optionally #ifdef
176  * their processing inside the helper, so that reasonable and helpful
177  * error messages can be generated if a disabled option is requested.
178  */
179 struct option_helper {
180         struct berval   oh_name;
181         int             (*oh_fnc)(const char *val, void *arg);
182         void            *oh_arg;
183         const char      *oh_usage;
184 } option_helpers[] = {
185         { BER_BVC("slp"),       slapd_opt_slp,  NULL, "slp[={on|off}] enable/disable SLP" },
186         { BER_BVNULL }
187 };
188
189 static void
190 usage( char *name )
191 {
192         fprintf( stderr,
193                 "usage: %s options\n", name );
194         fprintf( stderr,
195                 "\t-4\t\tIPv4 only\n"
196                 "\t-6\t\tIPv6 only\n"
197                 "\t-T {add|auth|cat|dn|index|passwd|test}\n"
198                 "\t\t\tRun in Tool mode\n"
199                 "\t-c cookie\tSync cookie of consumer\n"
200                 "\t-d level\tDebug level" "\n"
201                 "\t-f filename\tConfiguration file\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 #ifdef HAVE_NT_SERVICE_MANAGER
257         char            *configfile = ".\\slapd.conf";
258 #else
259         char            *configfile = SLAPD_DEFAULT_CONFIGFILE;
260 #endif
261         char        *serverName;
262         int         serverMode = SLAP_SERVER_MODE;
263
264         struct berval cookie = BER_BVNULL;
265         struct sync_cookie *scp = NULL;
266         struct sync_cookie *scp_entry = NULL;
267
268 #ifdef CSRIMALLOC
269         FILE *leakfile;
270         if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
271                 leakfile = stderr;
272         }
273 #endif
274         char    *serverNamePrefix = "";
275         size_t  l;
276
277         slap_sl_mem_init();
278
279         serverName = lutil_progname( "slapd", argc, argv );
280
281         if ( strcmp( serverName, "slapd" ) ) {
282                 for (i=0; tools[i].name; i++) {
283                         if ( !strcmp( serverName, tools[i].name ) ) {
284                                 rc = tools[i].func(argc, argv);
285                                 MAIN_RETURN(rc);
286                         }
287                 }
288         }
289
290 #ifdef HAVE_NT_SERVICE_MANAGER
291         {
292                 int *i;
293                 char *newConfigFile;
294                 char *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 #ifdef NEW_LOGGING
307                         lutil_log_initialize( argc, argv );
308                         LDAP_LOG( SLAPD, INFO, 
309                                 "main: new debug level from registry is: %d\n", 
310                                 slap_debug, 0, 0 );
311 #else
312                         Debug( LDAP_DEBUG_ANY,
313                                 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
314 #endif
315                 }
316
317                 newUrls = (char *) lutil_getRegParam(regService, "Urls");
318                 if (newUrls) {
319                     if (urls)
320                         ch_free(urls);
321
322                     urls = ch_strdup(newUrls);
323 #ifdef NEW_LOGGING
324                     LDAP_LOG( SLAPD, INFO, 
325                                 "main: new urls from registry: %s\n", urls, 0, 0 );
326 #else
327                     Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
328                                 urls, 0, 0);
329 #endif
330                 }
331
332                 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
333                 if ( newConfigFile != NULL ) {
334                         configfile = newConfigFile;
335 #ifdef NEW_LOGGING
336                         LDAP_LOG( SLAPD, INFO, 
337                                 "main: new config file from registry is: %s\n", configfile, 0, 0 );
338 #else
339                         Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
340 #endif
341                 }
342         }
343 #endif
344
345         while ( (i = getopt( argc, argv,
346                              "c:d:f:h:n:o:s:StT:V"
347 #if LDAP_PF_INET6
348                                 "46"
349 #endif
350 #ifdef HAVE_CHROOT
351                                 "r:"
352 #endif
353 #ifdef LOG_LOCAL4
354                              "l:"
355 #endif
356 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
357                              "u:g:"
358 #endif
359                              )) != EOF ) {
360                 switch ( i ) {
361 #ifdef LDAP_PF_INET6
362                 case '4':
363                         slap_inet4or6 = AF_INET;
364                         break;
365                 case '6':
366                         slap_inet4or6 = AF_INET6;
367                         break;
368 #endif
369
370                 case 'h':       /* listen URLs */
371                         if ( urls != NULL ) free( urls );
372                         urls = ch_strdup( optarg );
373                         break;
374
375                 case 'c':       /* provide sync cookie, override if exist in replica */
376                         scp = (struct sync_cookie *) ch_calloc( 1,
377                                                                                 sizeof( struct sync_cookie ));
378                         ber_str2bv( optarg, strlen( optarg ), 1, &cookie );
379                         ber_bvarray_add( &scp->octet_str, &cookie );
380                         slap_parse_sync_cookie( scp );
381
382                         LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
383                                 if ( scp->rid == scp_entry->rid ) {
384 #ifdef NEW_LOGGING
385                                         LDAP_LOG( OPERATION, CRIT,
386                                                         "main: duplicated replica id in cookies\n",
387                                                         0, 0, 0 );
388 #else
389                                         Debug( LDAP_DEBUG_ANY,
390                                                     "main: duplicated replica id in cookies\n",
391                                                         0, 0, 0 );
392 #endif
393                                         slap_sync_cookie_free( scp, 1 );
394                                         goto destroy;
395                                 }
396                         }
397                         LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
398                         break;
399
400                 case 'd':       /* set debug level and 'do not detach' flag */
401                         no_detach = 1;
402 #ifdef LDAP_DEBUG
403                         slap_debug |= atoi( optarg );
404 #else
405                         if ( atoi( optarg ) != 0 )
406                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
407                                        stderr );
408 #endif
409                         break;
410
411                 case 'f':       /* read config file */
412                         configfile = ch_strdup( optarg );
413                         break;
414
415                 case 'o': {
416                         char            *val = strchr( optarg, '=' );
417                         struct berval   opt;
418                         int             i;
419
420                         opt.bv_val = optarg;
421                         
422                         if ( val ) {
423                                 opt.bv_len = ( val - optarg );
424                                 val++;
425                         
426                         } else {
427                                 opt.bv_len = strlen( optarg );
428                         }
429
430                         for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
431                                 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
432                                         assert( option_helpers[i].oh_fnc != NULL );
433                                         if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
434                                                 /* we assume the option parsing helper
435                                                  * issues appropriate and self-explanatory
436                                                  * error messages... */
437                                                 goto stop;
438                                         }
439                                         break;
440                                 }
441                         }
442
443                         if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
444                                 goto unhandled_option;
445                         }
446                         break;
447                 }
448
449                 case 's':       /* set syslog level */
450                         ldap_syslog = atoi( optarg );
451                         break;
452
453 #ifdef LOG_LOCAL4
454                 case 'l':       /* set syslog local user */
455                         syslogUser = cnvt_str2int( optarg,
456                                 syslog_types, DEFAULT_SYSLOG_USER );
457                         break;
458 #endif
459
460 #ifdef HAVE_CHROOT
461                 case 'r':
462                         if( sandbox ) free(sandbox);
463                         sandbox = ch_strdup( optarg );
464                         break;
465 #endif
466
467 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
468                 case 'u':       /* user name */
469                         if( username ) free(username);
470                         username = ch_strdup( optarg );
471                         break;
472
473                 case 'g':       /* group name */
474                         if( groupname ) free(groupname);
475                         groupname = ch_strdup( optarg );
476                         break;
477 #endif /* SETUID && GETUID */
478
479                 case 'n':  /* NT service name */
480                         serverName = ch_strdup( optarg );
481                         break;
482
483                 case 't':
484                         /* deprecated; use slaptest instead */
485                         fprintf( stderr, "option -t deprecated; "
486                                 "use slaptest command instead\n" );
487                         check |= CHECK_CONFIG;
488                         break;
489
490                 case 'V':
491                         version++;
492                         break;
493
494                 case 'T':
495                         /* try full option string first */
496                         for ( i = 0; tools[i].name; i++ ) {
497                                 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
498                                         rc = tools[i].func( argc, argv );
499                                         MAIN_RETURN( rc );
500                                 }
501                         }
502
503                         /* try bits of option string (backward compatibility for single char) */
504                         l = strlen( optarg );
505                         for ( i = 0; tools[i].name; i++ ) {
506                                 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
507                                         rc = tools[i].func( argc, argv );
508                                         MAIN_RETURN( rc );
509                                 }
510                         }
511                         
512                         /* issue error */
513                         serverName = optarg;
514                         serverNamePrefix = "slap";
515                         fprintf( stderr, "program name \"%s%s\" unrecognized; "
516                                         "aborting...\n", serverNamePrefix, serverName );
517                         /* FALLTHRU */
518                 default:
519 unhandled_option:;
520                         usage( argv[0] );
521                         rc = 1;
522                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
523                         goto stop;
524                 }
525         }
526
527 #ifdef NEW_LOGGING
528         lutil_log_initialize( argc, argv );
529 #else
530         lutil_set_debug_level( "slapd", slap_debug );
531         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
532         ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
533         ldif_debug = slap_debug;
534 #endif
535
536         if ( version ) {
537                 fprintf( stderr, "%s\n", Versionstr );
538                 if ( version > 1 ) goto stop;
539         }
540
541         {
542                 char *logName;
543 #ifdef HAVE_EBCDIC
544                 logName = ch_strdup( serverName );
545                 __atoe( logName );
546 #else
547                 logName = serverName;
548 #endif
549
550 #ifdef LOG_LOCAL4
551                 openlog( logName, OPENLOG_OPTIONS, syslogUser );
552 #elif LOG_DEBUG
553                 openlog( logName, OPENLOG_OPTIONS );
554 #endif
555 #ifdef HAVE_EBCDIC
556                 free( logName );
557 #endif
558         }
559
560 #ifdef NEW_LOGGING
561         LDAP_LOG( SLAPD, INFO, "%s", Versionstr, 0, 0 );
562 #else
563         Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
564 #endif
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 #ifdef NEW_LOGGING
607                 LDAP_LOG( OPERATION, CRIT, "main: schema initialization error\n", 0, 0, 0 );
608 #else
609                 Debug( LDAP_DEBUG_ANY,
610                     "schema initialization error\n",
611                     0, 0, 0 );
612 #endif
613
614                 goto destroy;
615         }
616
617         if ( slap_init( serverMode, serverName ) != 0 ) {
618                 rc = 1;
619                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
620                 goto destroy;
621         }
622
623         if ( slap_controls_init( ) != 0 ) {
624 #ifdef NEW_LOGGING
625                 LDAP_LOG( OPERATION, CRIT, "main: controls initialization error\n", 0, 0, 0 );
626 #else
627                 Debug( LDAP_DEBUG_ANY,
628                     "controls initialization error\n",
629                     0, 0, 0 );
630 #endif
631
632                 goto destroy;
633         }
634
635 #ifdef HAVE_TLS
636         /* Library defaults to full certificate checking. This is correct when
637          * a client is verifying a server because all servers should have a
638          * valid cert. But few clients have valid certs, so we want our default
639          * to be no checking. The config file can override this as usual.
640          */
641         rc = 0;
642         (void) ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &rc );
643 #endif
644
645 #ifdef LDAP_SLAPI
646         if ( slapi_int_initialize() != 0 ) {
647 #ifdef NEW_LOGGING
648                 LDAP_LOG( OPERATION, CRIT, "main: slapi initialization error\n", 0, 0, 0 );
649 #else
650                 Debug( LDAP_DEBUG_ANY,
651                     "slapi initialization error\n",
652                     0, 0, 0 );
653 #endif
654
655                 goto destroy;
656         }
657 #endif /* LDAP_SLAPI */
658
659         if ( overlay_init() ) {
660                 goto destroy;
661         }
662
663         if ( read_config( configfile, 0 ) != 0 ) {
664                 rc = 1;
665                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
666
667                 if ( check & CHECK_CONFIG ) {
668                         fprintf( stderr, "config check failed\n" );
669                 }
670
671                 goto destroy;
672         }
673
674         if ( check & CHECK_CONFIG ) {
675                 fprintf( stderr, "config check succeeded\n" );
676
677                 check &= ~CHECK_CONFIG;
678                 if ( check == CHECK_NONE ) {
679                         rc = 0;
680                         goto destroy;
681                 }
682         }
683
684         if ( glue_sub_init( ) != 0 ) {
685 #ifdef NEW_LOGGING
686                 LDAP_LOG( SLAPD, CRIT, "main: subordinate config error\n", 0, 0, 0 );
687 #else
688                 Debug( LDAP_DEBUG_ANY,
689                     "subordinate config error\n",
690                     0, 0, 0 );
691 #endif
692                 goto destroy;
693         }
694
695         if ( slap_schema_check( ) != 0 ) {
696 #ifdef NEW_LOGGING
697                 LDAP_LOG( SLAPD, CRIT, "main: schema prep error\n", 0, 0, 0 );
698 #else
699                 Debug( LDAP_DEBUG_ANY,
700                     "schema prep error\n",
701                     0, 0, 0 );
702 #endif
703
704                 goto destroy;
705         }
706
707 #ifdef HAVE_TLS
708         rc = ldap_pvt_tls_init();
709         if( rc != 0) {
710 #ifdef NEW_LOGGING
711                 LDAP_LOG( SLAPD, CRIT, "main: tls init failed: %d\n", rc, 0, 0 );
712 #else
713                 Debug( LDAP_DEBUG_ANY,
714                     "main: TLS init failed: %d\n",
715                     0, 0, 0 );
716 #endif
717                 rc = 1;
718                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
719                 goto destroy;
720         }
721
722         {
723                 void *def_ctx = NULL;
724
725                 /* Save existing default ctx, if any */
726                 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &def_ctx );
727
728                 /* Force new ctx to be created */
729                 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, NULL );
730
731                 rc = ldap_pvt_tls_init_def_ctx();
732                 if( rc != 0) {
733 #ifdef NEW_LOGGING
734                         LDAP_LOG( SLAPD, CRIT, "main: tls init def ctx failed: %d\n", rc, 0, 0 );
735 #else
736                         Debug( LDAP_DEBUG_ANY,
737                             "main: TLS init def ctx failed: %d\n",
738                             rc, 0, 0 );
739 #endif
740                         rc = 1;
741                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
742                         goto destroy;
743                 }
744                 /* Retrieve slapd's own ctx */
745                 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
746                 /* Restore previous ctx */
747                 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, def_ctx );
748         }
749 #endif
750
751         (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
752         (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
753
754 #ifdef SIGPIPE
755         (void) SIGNAL( SIGPIPE, SIG_IGN );
756 #endif
757 #ifdef SIGHUP
758         (void) SIGNAL( SIGHUP, slap_sig_shutdown );
759 #endif
760         (void) SIGNAL( SIGINT, slap_sig_shutdown );
761         (void) SIGNAL( SIGTERM, slap_sig_shutdown );
762 #ifdef LDAP_SIGCHLD
763         (void) SIGNAL( LDAP_SIGCHLD, wait4child );
764 #endif
765 #ifdef SIGBREAK
766         /* SIGBREAK is generated when Ctrl-Break is pressed. */
767         (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
768 #endif
769
770 #ifndef HAVE_WINSOCK
771         lutil_detach( no_detach, 0 );
772 #endif /* HAVE_WINSOCK */
773
774 #ifdef CSRIMALLOC
775         mal_leaktrace(1);
776 #endif
777
778         /*
779          * FIXME: moved here from slapd_daemon_task()
780          * because back-monitor db_open() needs it
781          */
782         time( &starttime );
783
784         if ( slap_startup( NULL )  != 0 ) {
785                 rc = 1;
786                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
787                 goto shutdown;
788         }
789
790 #ifdef NEW_LOGGING
791         LDAP_LOG( SLAPD, INFO, "main: slapd starting.\n", 0, 0, 0 );
792 #else
793         Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
794 #endif
795
796
797         if ( slapd_pid_file != NULL ) {
798                 FILE *fp = fopen( slapd_pid_file, "w" );
799
800                 if( fp != NULL ) {
801                         fprintf( fp, "%d\n", (int) getpid() );
802                         fclose( fp );
803
804                 } else {
805                         free(slapd_pid_file);
806                         slapd_pid_file = NULL;
807                 }
808         }
809
810         if ( slapd_args_file != NULL ) {
811                 FILE *fp = fopen( slapd_args_file, "w" );
812
813                 if( fp != NULL ) {
814                         for ( i = 0; i < g_argc; i++ ) {
815                                 fprintf( fp, "%s ", g_argv[i] );
816                         }
817                         fprintf( fp, "\n" );
818                         fclose( fp );
819                 } else {
820                         free(slapd_args_file);
821                         slapd_args_file = NULL;
822                 }
823         }
824
825 #ifdef HAVE_NT_EVENT_LOG
826         if (is_NT_Service)
827         lutil_LogStartedEvent( serverName, slap_debug, configfile, urls );
828 #endif
829
830         rc = slapd_daemon();
831
832 #ifdef HAVE_NT_SERVICE_MANAGER
833         /* Throw away the event that we used during the startup process. */
834         if ( is_NT_Service )
835                 ldap_pvt_thread_cond_destroy( &started_event );
836 #endif
837
838 shutdown:
839         /* remember an error during shutdown */
840         rc |= slap_shutdown( NULL );
841
842 destroy:
843         /* remember an error during destroy */
844         rc |= slap_destroy();
845
846         while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
847                 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
848                 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
849                 ch_free( scp );
850         }
851
852 #ifdef SLAPD_MODULES
853         module_kill();
854 #endif
855
856         slap_op_destroy();
857
858         extops_kill();
859
860 stop:
861 #ifdef HAVE_NT_EVENT_LOG
862         if (is_NT_Service)
863         lutil_LogStoppedEvent( serverName );
864 #endif
865
866 #ifdef NEW_LOGGING
867         LDAP_LOG( SLAPD, CRIT, "main: slapd stopped.\n", 0, 0, 0 );
868 #else
869         Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
870 #endif
871
872
873 #ifdef HAVE_NT_SERVICE_MANAGER
874         lutil_ReportShutdownComplete();
875 #endif
876
877 #ifdef LOG_DEBUG
878     closelog();
879 #endif
880         slapd_daemon_destroy();
881
882         controls_destroy();
883
884         schema_destroy();
885
886         lutil_passwd_destroy();
887
888 #ifdef HAVE_TLS
889         ldap_pvt_tls_destroy();
890 #endif
891
892         if ( slapd_pid_file != NULL ) {
893                 unlink( slapd_pid_file );
894         }
895         if ( slapd_args_file != NULL ) {
896                 unlink( slapd_args_file );
897         }
898
899         config_destroy();
900
901 #ifdef CSRIMALLOC
902         mal_dumpleaktrace( leakfile );
903 #endif
904
905         MAIN_RETURN(rc);
906 }
907
908
909 #ifdef LDAP_SIGCHLD
910
911 /*
912  *  Catch and discard terminated child processes, to avoid zombies.
913  */
914
915 static RETSIGTYPE
916 wait4child( int sig )
917 {
918     int save_errno = errno;
919
920 #ifdef WNOHANG
921     errno = 0;
922 #ifdef HAVE_WAITPID
923     while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
924         ;       /* NULL */
925 #else
926     while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
927         ;       /* NULL */
928 #endif
929 #else
930     (void) wait( NULL );
931 #endif
932     (void) SIGNAL_REINSTALL( sig, wait4child );
933     errno = save_errno;
934 }
935
936 #endif /* LDAP_SIGCHLD */
937
938
939 #ifdef LOG_LOCAL4
940
941 /*
942  *  Convert a string to an integer by means of a dispatcher table
943  *  if the string is not in the table return the default
944  */
945
946 static int
947 cnvt_str2int( char *stringVal, STRDISP_P dispatcher, int defaultVal )
948 {
949     int        retVal = defaultVal;
950     STRDISP_P  disp;
951
952     for (disp = dispatcher; disp->stringVal; disp++) {
953
954         if (!strncasecmp (stringVal, disp->stringVal, disp->abbr)) {
955
956             retVal = disp->intVal;
957             break;
958
959         }
960     }
961
962     return (retVal);
963 }
964
965 #endif  /* LOG_LOCAL4 */