]> git.sur5r.net Git - openldap/blob - servers/slapd/main.c
Plug mutex/rwlock leaks (destroy them)
[openldap] / servers / slapd / main.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2010 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, slapschema;
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         {"slapschema", slapschema},
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 extern OverlayInit slap_oinfo[];
103 extern BackendInfo slap_binfo[];
104
105 #define CHECK_NONE      0x00
106 #define CHECK_CONFIG    0x01
107 #define CHECK_LOGLEVEL  0x02
108 static int check = CHECK_NONE;
109 static int version = 0;
110
111 void *slap_tls_ctx;
112 LDAP *slap_tls_ld;
113
114 static int
115 slapd_opt_slp( const char *val, void *arg )
116 {
117 #ifdef HAVE_SLP
118         /* NULL is default */
119         if ( val == NULL || *val == '(' || strcasecmp( val, "on" ) == 0 ) {
120                 slapd_register_slp = 1;
121                 slapd_slp_attrs = (val != NULL && *val == '(') ? val : NULL;
122
123         } else if ( strcasecmp( val, "off" ) == 0 ) {
124                 slapd_register_slp = 0;
125
126         /* NOTE: add support for URL specification? */
127
128         } else {
129                 fprintf(stderr, "unrecognized value \"%s\" for SLP option\n", val );
130                 return -1;
131         }
132
133         return 0;
134                 
135 #else
136         fputs( "slapd: SLP support is not available\n", stderr );
137         return 0;
138 #endif
139 }
140
141 /*
142  * Option helper structure:
143  * 
144  * oh_nam       is left-hand part of <option>[=<value>]
145  * oh_fnc       is handler function
146  * oh_arg       is an optional arg to oh_fnc
147  * oh_usage     is the one-line usage string related to the option,
148  *              which is assumed to start with <option>[=<value>]
149  *
150  * please leave valid options in the structure, and optionally #ifdef
151  * their processing inside the helper, so that reasonable and helpful
152  * error messages can be generated if a disabled option is requested.
153  */
154 struct option_helper {
155         struct berval   oh_name;
156         int             (*oh_fnc)(const char *val, void *arg);
157         void            *oh_arg;
158         const char      *oh_usage;
159 } option_helpers[] = {
160         { BER_BVC("slp"),       slapd_opt_slp,  NULL, "slp[={on|off|(attrs)}] enable/disable SLP using (attrs)" },
161         { BER_BVNULL, 0, NULL, NULL }
162 };
163
164 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
165 #ifdef LOG_LOCAL4
166 int
167 parse_syslog_user( const char *arg, int *syslogUser )
168 {
169         static slap_verbmasks syslogUsers[] = {
170                 { BER_BVC( "LOCAL0" ), LOG_LOCAL0 },
171                 { BER_BVC( "LOCAL1" ), LOG_LOCAL1 },
172                 { BER_BVC( "LOCAL2" ), LOG_LOCAL2 },
173                 { BER_BVC( "LOCAL3" ), LOG_LOCAL3 },
174                 { BER_BVC( "LOCAL4" ), LOG_LOCAL4 },
175                 { BER_BVC( "LOCAL5" ), LOG_LOCAL5 },
176                 { BER_BVC( "LOCAL6" ), LOG_LOCAL6 },
177                 { BER_BVC( "LOCAL7" ), LOG_LOCAL7 },
178 #ifdef LOG_USER
179                 { BER_BVC( "USER" ), LOG_USER },
180 #endif /* LOG_USER */
181 #ifdef LOG_DAEMON
182                 { BER_BVC( "DAEMON" ), LOG_DAEMON },
183 #endif /* LOG_DAEMON */
184                 { BER_BVNULL, 0 }
185         };
186         int i = verb_to_mask( arg, syslogUsers );
187
188         if ( BER_BVISNULL( &syslogUsers[ i ].word ) ) {
189                 Debug( LDAP_DEBUG_ANY,
190                         "unrecognized syslog user \"%s\".\n",
191                         arg, 0, 0 );
192                 return 1;
193         }
194
195         *syslogUser = syslogUsers[ i ].mask;
196
197         return 0;
198 }
199 #endif /* LOG_LOCAL4 */
200
201 int
202 parse_syslog_level( const char *arg, int *levelp )
203 {
204         static slap_verbmasks   str2syslog_level[] = {
205                 { BER_BVC( "EMERG" ),   LOG_EMERG },
206                 { BER_BVC( "ALERT" ),   LOG_ALERT },
207                 { BER_BVC( "CRIT" ),    LOG_CRIT },
208                 { BER_BVC( "ERR" ),     LOG_ERR },
209                 { BER_BVC( "WARNING" ), LOG_WARNING },
210                 { BER_BVC( "NOTICE" ),  LOG_NOTICE },
211                 { BER_BVC( "INFO" ),    LOG_INFO },
212                 { BER_BVC( "DEBUG" ),   LOG_DEBUG },
213                 { BER_BVNULL, 0 }
214         };
215         int i = verb_to_mask( arg, str2syslog_level );
216         if ( BER_BVISNULL( &str2syslog_level[ i ].word ) ) {
217                 Debug( LDAP_DEBUG_ANY,
218                         "unknown syslog level \"%s\".\n",
219                         arg, 0, 0 );
220                 return 1;
221         }
222         
223         *levelp = str2syslog_level[ i ].mask;
224
225         return 0;
226 }
227 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
228
229 int
230 parse_debug_unknowns( char **unknowns, int *levelp )
231 {
232         int i, level, rc = 0;
233
234         for ( i = 0; unknowns[ i ] != NULL; i++ ) {
235                 level = 0;
236                 if ( str2loglevel( unknowns[ i ], &level )) {
237                         fprintf( stderr,
238                                 "unrecognized log level \"%s\"\n", unknowns[ i ] );
239                         rc = 1;
240                 } else {
241                         *levelp |= level;
242                 }
243         }
244         return rc;
245 }
246
247 int
248 parse_debug_level( const char *arg, int *levelp, char ***unknowns )
249 {
250         int     level;
251
252         if ( arg && arg[ 0 ] != '-' && !isdigit( (unsigned char) arg[ 0 ] ) )
253         {
254                 int     i;
255                 char    **levels;
256
257                 levels = ldap_str2charray( arg, "," );
258
259                 for ( i = 0; levels[ i ] != NULL; i++ ) {
260                         level = 0;
261
262                         if ( str2loglevel( levels[ i ], &level ) ) {
263                                 /* remember this for later */
264                                 ldap_charray_add( unknowns, levels[ i ] );
265                                 fprintf( stderr,
266                                         "unrecognized log level \"%s\" (deferred)\n",
267                                         levels[ i ] );
268                         } else {
269                                 *levelp |= level;
270                         }
271                 }
272
273                 ldap_charray_free( levels );
274
275         } else {
276                 int rc;
277
278                 if ( arg[0] == '-' ) {
279                         rc = lutil_atoix( &level, arg, 0 );
280                 } else {
281                         unsigned ulevel;
282
283                         rc = lutil_atoux( &ulevel, arg, 0 );
284                         level = (int)ulevel;
285                 }
286
287                 if ( rc ) {
288                         fprintf( stderr,
289                                 "unrecognized log level "
290                                 "\"%s\"\n", arg );
291                         return 1;
292                 }
293
294                 if ( level == 0 ) {
295                         *levelp = 0;
296
297                 } else {
298                         *levelp |= level;
299                 }
300         }
301
302         return 0;
303 }
304
305 static void
306 usage( char *name )
307 {
308         fprintf( stderr,
309                 "usage: %s options\n", name );
310         fprintf( stderr,
311                 "\t-4\t\tIPv4 only\n"
312                 "\t-6\t\tIPv6 only\n"
313                 "\t-T {acl|add|auth|cat|dn|index|passwd|test}\n"
314                 "\t\t\tRun in Tool mode\n"
315                 "\t-c cookie\tSync cookie of consumer\n"
316                 "\t-d level\tDebug level" "\n"
317                 "\t-f filename\tConfiguration file\n"
318                 "\t-F dir\tConfiguration directory\n"
319 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
320                 "\t-g group\tGroup (id or name) to run as\n"
321 #endif
322                 "\t-h URLs\t\tList of URLs to serve\n"
323 #ifdef SLAP_DEFAULT_SYSLOG_USER
324                 "\t-l facility\tSyslog facility (default: LOCAL4)\n"
325 #endif
326                 "\t-n serverName\tService name\n"
327                 "\t-o <opt>[=val] generic means to specify options" );
328         if ( !BER_BVISNULL( &option_helpers[0].oh_name ) ) {
329                 int     i;
330
331                 fprintf( stderr, "; supported options:\n" );
332                 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++) {
333                         fprintf( stderr, "\t\t%s\n", option_helpers[i].oh_usage );
334                 }
335         } else {
336                 fprintf( stderr, "\n" );
337         }
338         fprintf( stderr,        
339 #ifdef HAVE_CHROOT
340                 "\t-r directory\tSandbox directory to chroot to\n"
341 #endif
342                 "\t-s level\tSyslog level\n"
343 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
344                 "\t-u user\t\tUser (id or name) to run as\n"
345 #endif
346                 "\t-V\t\tprint version info (-VV exit afterwards, -VVV print\n"
347                 "\t\t\tinfo about static overlays and backends)\n"
348     );
349 }
350
351 #ifdef HAVE_NT_SERVICE_MANAGER
352 void WINAPI ServiceMain( DWORD argc, LPTSTR *argv )
353 #else
354 int main( int argc, char **argv )
355 #endif
356 {
357         int             i, no_detach = 0;
358         int             rc = 1;
359         char *urls = NULL;
360 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
361         char *username = NULL;
362         char *groupname = NULL;
363 #endif
364 #if defined(HAVE_CHROOT)
365         char *sandbox = NULL;
366 #endif
367 #ifdef SLAP_DEFAULT_SYSLOG_USER
368         int syslogUser = SLAP_DEFAULT_SYSLOG_USER;
369 #endif
370         
371         int g_argc = argc;
372         char **g_argv = argv;
373
374         char *configfile = NULL;
375         char *configdir = NULL;
376         char *serverName;
377         int serverMode = SLAP_SERVER_MODE;
378
379         struct sync_cookie *scp = NULL;
380         struct sync_cookie *scp_entry = NULL;
381
382         char **debug_unknowns = NULL;
383         char **syslog_unknowns = NULL;
384
385         char *serverNamePrefix = "";
386         size_t  l;
387
388         int slapd_pid_file_unlink = 0, slapd_args_file_unlink = 0;
389         int firstopt = 1;
390
391 #ifdef CSRIMALLOC
392         FILE *leakfile;
393         if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
394                 leakfile = stderr;
395         }
396 #endif
397
398         slap_sl_mem_init();
399
400         (void) ldap_pvt_thread_initialize();
401
402         serverName = lutil_progname( "slapd", argc, argv );
403
404         if ( strcmp( serverName, "slapd" ) ) {
405                 for (i=0; tools[i].name; i++) {
406                         if ( !strcmp( serverName, tools[i].name ) ) {
407                                 rc = tools[i].func(argc, argv);
408                                 MAIN_RETURN(rc);
409                         }
410                 }
411         }
412
413 #ifdef HAVE_NT_SERVICE_MANAGER
414         {
415                 int *ip;
416                 char *newConfigFile;
417                 char *newConfigDir;
418                 char *newUrls;
419                 char *regService = NULL;
420
421                 if ( is_NT_Service ) {
422                         lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
423                         if ( strcmp(serverName, SERVICE_NAME) )
424                             regService = serverName;
425                 }
426
427                 ip = (int*)lutil_getRegParam( regService, "DebugLevel" );
428                 if ( ip != NULL ) {
429                         slap_debug = *ip;
430                         Debug( LDAP_DEBUG_ANY,
431                                 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
432                 }
433
434                 newUrls = (char *) lutil_getRegParam(regService, "Urls");
435                 if (newUrls) {
436                     if (urls)
437                         ch_free(urls);
438
439                     urls = ch_strdup(newUrls);
440                     Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
441                                 urls, 0, 0);
442                 }
443
444                 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
445                 if ( newConfigFile != NULL ) {
446                         configfile = newConfigFile;
447                         Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
448                 }
449
450                 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
451                 if ( newConfigDir != NULL ) {
452                         configdir = newConfigDir;
453                         Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
454                 }
455         }
456 #endif
457
458         while ( (i = getopt( argc, argv,
459                              "c:d:f:F:h:n:o:s:tT:V"
460 #ifdef LDAP_PF_INET6
461                                 "46"
462 #endif
463 #ifdef HAVE_CHROOT
464                                 "r:"
465 #endif
466 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
467                                 "S:"
468 #ifdef LOG_LOCAL4
469                                 "l:"
470 #endif
471 #endif
472 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
473                                 "u:g:"
474 #endif
475                              )) != EOF ) {
476                 switch ( i ) {
477 #ifdef LDAP_PF_INET6
478                 case '4':
479                         slap_inet4or6 = AF_INET;
480                         break;
481                 case '6':
482                         slap_inet4or6 = AF_INET6;
483                         break;
484 #endif
485
486                 case 'h':       /* listen URLs */
487                         if ( urls != NULL ) free( urls );
488                         urls = ch_strdup( optarg );
489                         break;
490
491                 case 'c':       /* provide sync cookie, override if exist in replica */
492                         scp = (struct sync_cookie *) ch_calloc( 1,
493                                                                                 sizeof( struct sync_cookie ));
494                         ber_str2bv( optarg, 0, 1, &scp->octet_str );
495                         
496                         /* This only parses out the rid at this point */
497                         slap_parse_sync_cookie( scp, NULL );
498
499                         if ( scp->rid == -1 ) {
500                                 Debug( LDAP_DEBUG_ANY,
501                                                 "main: invalid cookie \"%s\"\n",
502                                                 optarg, 0, 0 );
503                                 slap_sync_cookie_free( scp, 1 );
504                                 goto destroy;
505                         }
506
507                         LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
508                                 if ( scp->rid == scp_entry->rid ) {
509                                         Debug( LDAP_DEBUG_ANY,
510                                                     "main: duplicated replica id in cookies\n",
511                                                         0, 0, 0 );
512                                         slap_sync_cookie_free( scp, 1 );
513                                         goto destroy;
514                                 }
515                         }
516                         LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
517                         break;
518
519                 case 'd': {     /* set debug level and 'do not detach' flag */
520                         int     level = 0;
521
522                         if ( strcmp( optarg, "?" ) == 0 ) {
523                                 check |= CHECK_LOGLEVEL;
524                                 break;
525                         }
526
527                         no_detach = 1;
528                         if ( parse_debug_level( optarg, &level, &debug_unknowns ) ) {
529                                 goto destroy;
530                         }
531 #ifdef LDAP_DEBUG
532                         slap_debug |= level;
533 #else
534                         if ( level != 0 )
535                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
536                                        stderr );
537 #endif
538                         } break;
539
540                 case 'f':       /* read config file */
541                         configfile = ch_strdup( optarg );
542                         break;
543
544                 case 'F':       /* use config dir */
545                         configdir = ch_strdup( optarg );
546                         break;
547
548                 case 'o': {
549                         char            *val = strchr( optarg, '=' );
550                         struct berval   opt;
551
552                         opt.bv_val = optarg;
553                         
554                         if ( val ) {
555                                 opt.bv_len = ( val - optarg );
556                                 val++;
557                         
558                         } else {
559                                 opt.bv_len = strlen( optarg );
560                         }
561
562                         for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
563                                 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
564                                         assert( option_helpers[i].oh_fnc != NULL );
565                                         if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
566                                                 /* we assume the option parsing helper
567                                                  * issues appropriate and self-explanatory
568                                                  * error messages... */
569                                                 goto stop;
570                                         }
571                                         break;
572                                 }
573                         }
574
575                         if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
576                                 goto unhandled_option;
577                         }
578                         break;
579                 }
580
581                 case 's':       /* set syslog level */
582                         if ( strcmp( optarg, "?" ) == 0 ) {
583                                 check |= CHECK_LOGLEVEL;
584                                 break;
585                         }
586
587                         if ( parse_debug_level( optarg, &ldap_syslog, &syslog_unknowns ) ) {
588                                 goto destroy;
589                         }
590                         break;
591
592 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
593                 case 'S':
594                         if ( parse_syslog_level( optarg, &ldap_syslog_level ) ) {
595                                 goto destroy;
596                         }
597                         break;
598
599 #ifdef LOG_LOCAL4
600                 case 'l':       /* set syslog local user */
601                         if ( parse_syslog_user( optarg, &syslogUser ) ) {
602                                 goto destroy;
603                         }
604                         break;
605 #endif
606 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
607
608 #ifdef HAVE_CHROOT
609                 case 'r':
610                         if( sandbox ) free(sandbox);
611                         sandbox = ch_strdup( optarg );
612                         break;
613 #endif
614
615 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
616                 case 'u':       /* user name */
617                         if( username ) free(username);
618                         username = ch_strdup( optarg );
619                         break;
620
621                 case 'g':       /* group name */
622                         if( groupname ) free(groupname);
623                         groupname = ch_strdup( optarg );
624                         break;
625 #endif /* SETUID && GETUID */
626
627                 case 'n':  /* NT service name */
628                         serverName = ch_strdup( optarg );
629                         break;
630
631                 case 't':
632                         /* deprecated; use slaptest instead */
633                         fprintf( stderr, "option -t deprecated; "
634                                 "use slaptest command instead\n" );
635                         check |= CHECK_CONFIG;
636                         break;
637
638                 case 'V':
639                         version++;
640                         break;
641
642                 case 'T':
643                         if ( firstopt == 0 ) {
644                                 fprintf( stderr, "warning: \"-T %s\" "
645                                         "should be the first option.\n",
646                                         optarg );
647                         }
648
649                         /* try full option string first */
650                         for ( i = 0; tools[i].name; i++ ) {
651                                 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
652                                         rc = tools[i].func( argc, argv );
653                                         MAIN_RETURN( rc );
654                                 }
655                         }
656
657                         /* try bits of option string (backward compatibility for single char) */
658                         l = strlen( optarg );
659                         for ( i = 0; tools[i].name; i++ ) {
660                                 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
661                                         rc = tools[i].func( argc, argv );
662                                         MAIN_RETURN( rc );
663                                 }
664                         }
665                         
666                         /* issue error */
667                         serverName = optarg;
668                         serverNamePrefix = "slap";
669                         fprintf( stderr, "program name \"%s%s\" unrecognized; "
670                                         "aborting...\n", serverNamePrefix, serverName );
671                         /* FALLTHRU */
672                 default:
673 unhandled_option:;
674                         usage( argv[0] );
675                         rc = 1;
676                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
677                         goto stop;
678                 }
679
680                 if ( firstopt ) {
681                         firstopt = 0;
682                 }
683         }
684
685         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
686         ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
687         ldif_debug = slap_debug;
688
689         if ( version ) {
690                 fprintf( stderr, "%s\n", Versionstr );
691                 if ( version > 2 ) {
692                         if ( slap_oinfo[0].ov_type ) {
693                                 fprintf( stderr, "Included static overlays:\n");
694                                 for ( i= 0 ; slap_oinfo[i].ov_type; i++ ) {
695                                         fprintf( stderr, "    %s\n", slap_oinfo[i].ov_type );
696                                 }
697                         }
698                         if ( slap_binfo[0].bi_type ) {
699                                 fprintf( stderr, "Included static backends:\n");
700                                 for ( i= 0 ; slap_binfo[i].bi_type; i++ ) {
701                                         fprintf( stderr, "    %s\n", slap_binfo[i].bi_type );
702                                 }
703                         }
704                 }
705
706                 if ( version > 1 ) goto stop;
707         }
708
709 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
710         {
711                 char *logName;
712 #ifdef HAVE_EBCDIC
713                 logName = ch_strdup( serverName );
714                 __atoe( logName );
715 #else
716                 logName = serverName;
717 #endif
718
719 #ifdef LOG_LOCAL4
720                 openlog( logName, OPENLOG_OPTIONS, syslogUser );
721 #elif defined LOG_DEBUG
722                 openlog( logName, OPENLOG_OPTIONS );
723 #endif
724 #ifdef HAVE_EBCDIC
725                 free( logName );
726 #endif
727         }
728 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
729
730         Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
731
732         global_host = ldap_pvt_get_fqdn( NULL );
733         ber_str2bv( global_host, 0, 0, &global_host_bv );
734
735         if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
736                 rc = 1;
737                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
738                 goto stop;
739         }
740
741 #if defined(HAVE_CHROOT)
742         if ( sandbox ) {
743                 if ( chdir( sandbox ) ) {
744                         perror("chdir");
745                         rc = 1;
746                         goto stop;
747                 }
748                 if ( chroot( sandbox ) ) {
749                         perror("chroot");
750                         rc = 1;
751                         goto stop;
752                 }
753         }
754 #endif
755
756 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
757         if ( username != NULL || groupname != NULL ) {
758                 slap_init_user( username, groupname );
759         }
760 #endif
761
762         extops_init();
763         lutil_passwd_init();
764
765 #ifdef HAVE_TLS
766         rc = ldap_create( &slap_tls_ld );
767         if ( rc ) {
768                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
769                 goto destroy;
770         }
771         /* Library defaults to full certificate checking. This is correct when
772          * a client is verifying a server because all servers should have a
773          * valid cert. But few clients have valid certs, so we want our default
774          * to be no checking. The config file can override this as usual.
775          */
776         rc = LDAP_OPT_X_TLS_NEVER;
777         (void) ldap_pvt_tls_set_option( slap_tls_ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &rc );
778 #endif
779
780         rc = slap_init( serverMode, serverName );
781         if ( rc ) {
782                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
783                 goto destroy;
784         }
785
786         if ( read_config( configfile, configdir ) != 0 ) {
787                 rc = 1;
788                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
789
790                 if ( check & CHECK_CONFIG ) {
791                         fprintf( stderr, "config check failed\n" );
792                 }
793
794                 goto destroy;
795         }
796
797         if ( debug_unknowns ) {
798                 rc = parse_debug_unknowns( debug_unknowns, &slap_debug );
799                 ldap_charray_free( debug_unknowns );
800                 debug_unknowns = NULL;
801                 if ( rc )
802                         goto destroy;
803         }
804         if ( syslog_unknowns ) {
805                 rc = parse_debug_unknowns( syslog_unknowns, &ldap_syslog );
806                 ldap_charray_free( syslog_unknowns );
807                 syslog_unknowns = NULL;
808                 if ( rc )
809                         goto destroy;
810         }       
811
812         if ( check & CHECK_LOGLEVEL ) {
813                 rc = 0;
814                 goto destroy;
815         }
816
817         if ( check & CHECK_CONFIG ) {
818                 fprintf( stderr, "config check succeeded\n" );
819
820                 check &= ~CHECK_CONFIG;
821                 if ( check == CHECK_NONE ) {
822                         rc = 0;
823                         goto destroy;
824                 }
825         }
826
827         if ( glue_sub_attach( 0 ) != 0 ) {
828                 Debug( LDAP_DEBUG_ANY,
829                     "subordinate config error\n",
830                     0, 0, 0 );
831
832                 goto destroy;
833         }
834
835         if ( slap_schema_check( ) != 0 ) {
836                 Debug( LDAP_DEBUG_ANY,
837                     "schema prep error\n",
838                     0, 0, 0 );
839
840                 goto destroy;
841         }
842
843 #ifdef HAVE_TLS
844         rc = ldap_pvt_tls_init();
845         if( rc != 0) {
846                 Debug( LDAP_DEBUG_ANY,
847                     "main: TLS init failed: %d\n",
848                     0, 0, 0 );
849                 rc = 1;
850                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
851                 goto destroy;
852         }
853
854         {
855                 int opt = 1;
856
857                 /* Force new ctx to be created */
858                 rc = ldap_pvt_tls_set_option( slap_tls_ld, LDAP_OPT_X_TLS_NEWCTX, &opt );
859                 if( rc == 0 ) {
860                         /* The ctx's refcount is bumped up here */
861                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
862                         load_extop( &slap_EXOP_START_TLS, 0, starttls_extop );
863                 } else if ( rc != LDAP_NOT_SUPPORTED ) {
864                         Debug( LDAP_DEBUG_ANY,
865                             "main: TLS init def ctx failed: %d\n",
866                             rc, 0, 0 );
867                         rc = 1;
868                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
869                         goto destroy;
870                 }
871         }
872 #endif
873
874 #ifdef HAVE_CYRUS_SASL
875         if( sasl_host == NULL ) {
876                 sasl_host = ch_strdup( global_host );
877         }
878 #endif
879
880         (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
881         (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
882
883 #ifdef SIGPIPE
884         (void) SIGNAL( SIGPIPE, SIG_IGN );
885 #endif
886 #ifdef SIGHUP
887         (void) SIGNAL( SIGHUP, slap_sig_shutdown );
888 #endif
889         (void) SIGNAL( SIGINT, slap_sig_shutdown );
890         (void) SIGNAL( SIGTERM, slap_sig_shutdown );
891 #ifdef SIGTRAP
892         (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
893 #endif
894 #ifdef LDAP_SIGCHLD
895         (void) SIGNAL( LDAP_SIGCHLD, wait4child );
896 #endif
897 #ifdef SIGBREAK
898         /* SIGBREAK is generated when Ctrl-Break is pressed. */
899         (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
900 #endif
901
902 #ifndef HAVE_WINSOCK
903         lutil_detach( no_detach, 0 );
904 #endif /* HAVE_WINSOCK */
905
906 #ifdef CSRIMALLOC
907         mal_leaktrace(1);
908 #endif
909
910         if ( slapd_pid_file != NULL ) {
911                 FILE *fp = fopen( slapd_pid_file, "w" );
912
913                 if ( fp == NULL ) {
914                         int save_errno = errno;
915
916                         Debug( LDAP_DEBUG_ANY, "unable to open pid file "
917                                 "\"%s\": %d (%s)\n",
918                                 slapd_pid_file,
919                                 save_errno, strerror( save_errno ) );
920
921                         free( slapd_pid_file );
922                         slapd_pid_file = NULL;
923
924                         rc = 1;
925                         goto destroy;
926                 }
927                 fprintf( fp, "%d\n", (int) getpid() );
928                 fclose( fp );
929                 slapd_pid_file_unlink = 1;
930         }
931
932         if ( slapd_args_file != NULL ) {
933                 FILE *fp = fopen( slapd_args_file, "w" );
934
935                 if ( fp == NULL ) {
936                         int save_errno = errno;
937
938                         Debug( LDAP_DEBUG_ANY, "unable to open args file "
939                                 "\"%s\": %d (%s)\n",
940                                 slapd_args_file,
941                                 save_errno, strerror( save_errno ) );
942
943                         free( slapd_args_file );
944                         slapd_args_file = NULL;
945
946                         rc = 1;
947                         goto destroy;
948                 }
949
950                 for ( i = 0; i < g_argc; i++ ) {
951                         fprintf( fp, "%s ", g_argv[i] );
952                 }
953                 fprintf( fp, "\n" );
954                 fclose( fp );
955                 slapd_args_file_unlink = 1;
956         }
957
958         /*
959          * FIXME: moved here from slapd_daemon_task()
960          * because back-monitor db_open() needs it
961          */
962         time( &starttime );
963
964         connections_init();
965
966         if ( slap_startup( NULL ) != 0 ) {
967                 rc = 1;
968                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
969                 goto shutdown;
970         }
971
972         Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
973
974 #ifdef HAVE_NT_EVENT_LOG
975         if (is_NT_Service)
976         lutil_LogStartedEvent( serverName, slap_debug, configfile ?
977                 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
978 #endif
979
980         rc = slapd_daemon();
981
982 #ifdef HAVE_NT_SERVICE_MANAGER
983         /* Throw away the event that we used during the startup process. */
984         if ( is_NT_Service )
985                 ldap_pvt_thread_cond_destroy( &started_event );
986 #endif
987
988 shutdown:
989         /* remember an error during shutdown */
990         rc |= slap_shutdown( NULL );
991
992 destroy:
993         if ( check & CHECK_LOGLEVEL ) {
994                 (void)loglevel_print( stdout );
995         }
996         /* remember an error during destroy */
997         rc |= slap_destroy();
998
999         while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
1000                 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
1001                 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
1002                 ch_free( scp );
1003         }
1004
1005 #ifdef SLAPD_MODULES
1006         module_kill();
1007 #endif
1008
1009         extops_kill();
1010
1011         supported_feature_destroy();
1012         entry_info_destroy();
1013
1014 stop:
1015 #ifdef HAVE_NT_EVENT_LOG
1016         if (is_NT_Service)
1017         lutil_LogStoppedEvent( serverName );
1018 #endif
1019
1020         Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
1021
1022
1023 #ifdef HAVE_NT_SERVICE_MANAGER
1024         lutil_ReportShutdownComplete();
1025 #endif
1026
1027 #ifdef LOG_DEBUG
1028     closelog();
1029 #endif
1030         slapd_daemon_destroy();
1031
1032         controls_destroy();
1033
1034         filter_destroy();
1035
1036         schema_destroy();
1037
1038         lutil_passwd_destroy();
1039
1040 #ifdef HAVE_TLS
1041         if ( slap_tls_ld ) {
1042                 ldap_pvt_tls_ctx_free( slap_tls_ctx );
1043                 ldap_unbind_ext( slap_tls_ld, NULL, NULL );
1044         }
1045         ldap_pvt_tls_destroy();
1046 #endif
1047
1048         slap_sasl_regexp_destroy();
1049
1050         if ( slapd_pid_file_unlink ) {
1051                 unlink( slapd_pid_file );
1052         }
1053         if ( slapd_args_file_unlink ) {
1054                 unlink( slapd_args_file );
1055         }
1056
1057         config_destroy();
1058
1059         if ( configfile )
1060                 ch_free( configfile );
1061         if ( configdir )
1062                 ch_free( configdir );
1063         if ( urls )
1064                 ch_free( urls );
1065         if ( global_host )
1066                 ch_free( global_host );
1067
1068         /* kludge, get symbols referenced */
1069         tavl_free( NULL, NULL );
1070
1071 #ifdef CSRIMALLOC
1072         mal_dumpleaktrace( leakfile );
1073 #endif
1074
1075         MAIN_RETURN(rc);
1076 }
1077
1078
1079 #ifdef LDAP_SIGCHLD
1080
1081 /*
1082  *  Catch and discard terminated child processes, to avoid zombies.
1083  */
1084
1085 static RETSIGTYPE
1086 wait4child( int sig )
1087 {
1088     int save_errno = errno;
1089
1090 #ifdef WNOHANG
1091     do
1092         errno = 0;
1093 #ifdef HAVE_WAITPID
1094     while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR );
1095 #else
1096     while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR );
1097 #endif
1098 #else
1099     (void) wait( NULL );
1100 #endif
1101     (void) SIGNAL_REINSTALL( sig, wait4child );
1102     errno = save_errno;
1103 }
1104
1105 #endif /* LDAP_SIGCHLD */