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