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