2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 1998-2006 The OpenLDAP Foundation.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted only as authorized by the OpenLDAP
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>.
15 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
16 * All rights reserved.
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.
31 #include <ac/socket.h>
32 #include <ac/string.h>
34 #include <ac/unistd.h>
43 #include "slapi/slapi.h"
47 static RETSIGTYPE wait4child( int sig );
50 #ifdef HAVE_NT_SERVICE_MANAGER
51 #define MAIN_RETURN(x) return
52 static struct sockaddr_in bind_addr;
54 #define SERVICE_EXIT( e, n ) do { \
55 if ( is_NT_Service ) { \
56 lutil_ServiceStatus.dwWin32ExitCode = (e); \
57 lutil_ServiceStatus.dwServiceSpecificExitCode = (n); \
62 #define SERVICE_EXIT( e, n )
63 #define MAIN_RETURN(x) return(x)
66 typedef int (MainFunc) LDAP_P(( int argc, char *argv[] ));
67 extern MainFunc slapadd, slapcat, slapdn, slapindex, slappasswd,
68 slaptest, slapauth, slapacl;
77 {"slapindex", slapindex},
78 {"slappasswd", slappasswd},
79 {"slaptest", slaptest},
80 {"slapauth", slapauth},
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 */
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
96 #ifndef HAVE_MKVERSION
97 const char Versionstr[] =
98 OPENLDAP_PACKAGE " " OPENLDAP_VERSION " Standalone LDAP Server (slapd)";
102 #define DEFAULT_SYSLOG_USER LOG_LOCAL4
104 typedef struct _str2intDispatch {
108 } STRDISP, *STRDISP_P;
110 /* table to compute syslog-options to integer */
111 static STRDISP syslog_types[] = {
112 { "LOCAL0", sizeof("LOCAL0"), LOG_LOCAL0 },
113 { "LOCAL1", sizeof("LOCAL1"), LOG_LOCAL1 },
114 { "LOCAL2", sizeof("LOCAL2"), LOG_LOCAL2 },
115 { "LOCAL3", sizeof("LOCAL3"), LOG_LOCAL3 },
116 { "LOCAL4", sizeof("LOCAL4"), LOG_LOCAL4 },
117 { "LOCAL5", sizeof("LOCAL5"), LOG_LOCAL5 },
118 { "LOCAL6", sizeof("LOCAL6"), LOG_LOCAL6 },
119 { "LOCAL7", sizeof("LOCAL7"), LOG_LOCAL7 },
121 { "USER", sizeof("USER"), LOG_USER },
124 { "DAEMON", sizeof("DAEMON"), LOG_DAEMON },
129 static int cnvt_str2int( char *, STRDISP_P, int );
130 #endif /* LOG_LOCAL4 */
132 #define CHECK_NONE 0x00
133 #define CHECK_CONFIG 0x01
134 static int check = CHECK_NONE;
135 static int version = 0;
140 slapd_opt_slp( const char *val, void *arg )
143 /* NULL is default */
144 if ( val == NULL || strcasecmp( val, "on" ) == 0 ) {
145 slapd_register_slp = 1;
147 } else if ( strcasecmp( val, "off" ) == 0 ) {
148 slapd_register_slp = 0;
150 /* NOTE: add support for URL specification? */
153 fprintf(stderr, "unrecognized value \"%s\" for SLP option\n", val );
160 fputs( "slapd: SLP support is not available\n", stderr );
166 * Option helper structure:
168 * oh_nam is left-hand part of <option>[=<value>]
169 * oh_fnc is handler function
170 * oh_arg is an optional arg to oh_fnc
171 * oh_usage is the one-line usage string related to the option,
172 * which is assumed to start with <option>[=<value>]
174 * please leave valid options in the structure, and optionally #ifdef
175 * their processing inside the helper, so that reasonable and helpful
176 * error messages can be generated if a disabled option is requested.
178 struct option_helper {
179 struct berval oh_name;
180 int (*oh_fnc)(const char *val, void *arg);
182 const char *oh_usage;
183 } option_helpers[] = {
184 { BER_BVC("slp"), slapd_opt_slp, NULL, "slp[={on|off}] enable/disable SLP" },
185 { BER_BVNULL, 0, NULL, NULL }
189 parse_debug_unknowns( char **unknowns, int *levelp )
191 int i, level, rc = 0;
193 for ( i = 0; unknowns[ i ] != NULL; i++ ) {
195 if ( str2loglevel( unknowns[ i ], &level )) {
197 "unrecognized log level \"%s\"\n", unknowns[ i ] );
207 parse_debug_level( const char *arg, int *levelp, char ***unknowns )
211 if ( arg != NULL && arg[ 0 ] != '-' && !isdigit( arg[ 0 ] ) )
216 levels = ldap_str2charray( arg, "," );
218 for ( i = 0; levels[ i ] != NULL; i++ ) {
221 if ( str2loglevel( levels[ i ], &level ) ) {
222 /* remember this for later */
223 ldap_charray_add( unknowns, levels[ i ] );
225 "unrecognized log level \"%s\" (deferred)\n",
232 ldap_charray_free( levels );
235 if ( lutil_atoix( &level, arg, 0 ) != 0 ) {
237 "unrecognized log level "
257 "usage: %s options\n", name );
259 "\t-4\t\tIPv4 only\n"
260 "\t-6\t\tIPv6 only\n"
261 "\t-T {acl|add|auth|cat|dn|index|passwd|test}\n"
262 "\t\t\tRun in Tool mode\n"
263 "\t-c cookie\tSync cookie of consumer\n"
264 "\t-d level\tDebug level" "\n"
265 "\t-f filename\tConfiguration file\n"
266 "\t-F dir\tConfiguration directory\n"
267 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
268 "\t-g group\tGroup (id or name) to run as\n"
270 "\t-h URLs\t\tList of URLs to serve\n"
272 "\t-l facility\tSyslog facility (default: LOCAL4)\n"
274 "\t-n serverName\tService name\n"
275 "\t-o <opt>[=val] generic means to specify options" );
276 if ( !BER_BVISNULL( &option_helpers[0].oh_name ) ) {
279 fprintf( stderr, "; supported options:\n" );
280 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++) {
281 fprintf( stderr, "\t\t%s\n", option_helpers[i].oh_usage );
284 fprintf( stderr, "\n" );
288 "\t-r directory\tSandbox directory to chroot to\n"
290 "\t-s level\tSyslog level\n"
291 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
292 "\t-u user\t\tUser (id or name) to run as\n"
294 "\t-V\t\tprint version info (-VV only)\n"
298 #ifdef HAVE_NT_SERVICE_MANAGER
299 void WINAPI ServiceMain( DWORD argc, LPTSTR *argv )
301 int main( int argc, char **argv )
304 int i, no_detach = 0;
307 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
308 char *username = NULL;
309 char *groupname = NULL;
311 #if defined(HAVE_CHROOT)
312 char *sandbox = NULL;
315 int syslogUser = DEFAULT_SYSLOG_USER;
319 char **g_argv = argv;
321 char *configfile = NULL;
322 char *configdir = NULL;
324 int serverMode = SLAP_SERVER_MODE;
326 struct sync_cookie *scp = NULL;
327 struct sync_cookie *scp_entry = NULL;
329 char **debug_unknowns = NULL;
330 char **syslog_unknowns = NULL;
332 char *serverNamePrefix = "";
335 int slapd_pid_file_unlink = 0, slapd_args_file_unlink = 0;
339 if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
346 (void) ldap_pvt_thread_initialize();
348 serverName = lutil_progname( "slapd", argc, argv );
350 if ( strcmp( serverName, "slapd" ) ) {
351 for (i=0; tools[i].name; i++) {
352 if ( !strcmp( serverName, tools[i].name ) ) {
353 rc = tools[i].func(argc, argv);
359 #ifdef HAVE_NT_SERVICE_MANAGER
365 char *regService = NULL;
367 if ( is_NT_Service ) {
368 lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
369 if ( strcmp(serverName, SERVICE_NAME) )
370 regService = serverName;
373 i = (int*)lutil_getRegParam( regService, "DebugLevel" );
376 Debug( LDAP_DEBUG_ANY,
377 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
380 newUrls = (char *) lutil_getRegParam(regService, "Urls");
385 urls = ch_strdup(newUrls);
386 Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
390 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
391 if ( newConfigFile != NULL ) {
392 configfile = newConfigFile;
393 Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
396 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
397 if ( newConfigDir != NULL ) {
398 configdir = newConfigDir;
399 Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
404 while ( (i = getopt( argc, argv,
405 "c:d:f:F:h:n:o:s:tT:V"
415 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
422 slap_inet4or6 = AF_INET;
425 slap_inet4or6 = AF_INET6;
429 case 'h': /* listen URLs */
430 if ( urls != NULL ) free( urls );
431 urls = ch_strdup( optarg );
434 case 'c': /* provide sync cookie, override if exist in replica */
435 scp = (struct sync_cookie *) ch_calloc( 1,
436 sizeof( struct sync_cookie ));
437 ber_str2bv( optarg, 0, 1, &scp->octet_str );
439 /* This only parses out the rid at this point */
440 slap_parse_sync_cookie( scp, NULL );
442 if ( scp->rid == -1 ) {
443 Debug( LDAP_DEBUG_ANY,
444 "main: invalid cookie \"%s\"\n",
446 slap_sync_cookie_free( scp, 1 );
450 LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
451 if ( scp->rid == scp_entry->rid ) {
452 Debug( LDAP_DEBUG_ANY,
453 "main: duplicated replica id in cookies\n",
455 slap_sync_cookie_free( scp, 1 );
459 LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
462 case 'd': { /* set debug level and 'do not detach' flag */
466 if ( parse_debug_level( optarg, &level, &debug_unknowns ) ) {
473 fputs( "must compile with LDAP_DEBUG for debugging\n",
478 case 'f': /* read config file */
479 configfile = ch_strdup( optarg );
482 case 'F': /* use config dir */
483 configdir = ch_strdup( optarg );
487 char *val = strchr( optarg, '=' );
494 opt.bv_len = ( val - optarg );
498 opt.bv_len = strlen( optarg );
501 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
502 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
503 assert( option_helpers[i].oh_fnc != NULL );
504 if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
505 /* we assume the option parsing helper
506 * issues appropriate and self-explanatory
507 * error messages... */
514 if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
515 goto unhandled_option;
520 case 's': /* set syslog level */
521 if ( parse_debug_level( optarg, &ldap_syslog, &syslog_unknowns ) ) {
527 case 'l': /* set syslog local user */
528 syslogUser = cnvt_str2int( optarg,
529 syslog_types, DEFAULT_SYSLOG_USER );
535 if( sandbox ) free(sandbox);
536 sandbox = ch_strdup( optarg );
540 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
541 case 'u': /* user name */
542 if( username ) free(username);
543 username = ch_strdup( optarg );
546 case 'g': /* group name */
547 if( groupname ) free(groupname);
548 groupname = ch_strdup( optarg );
550 #endif /* SETUID && GETUID */
552 case 'n': /* NT service name */
553 serverName = ch_strdup( optarg );
557 /* deprecated; use slaptest instead */
558 fprintf( stderr, "option -t deprecated; "
559 "use slaptest command instead\n" );
560 check |= CHECK_CONFIG;
568 /* try full option string first */
569 for ( i = 0; tools[i].name; i++ ) {
570 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
571 rc = tools[i].func( argc, argv );
576 /* try bits of option string (backward compatibility for single char) */
577 l = strlen( optarg );
578 for ( i = 0; tools[i].name; i++ ) {
579 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
580 rc = tools[i].func( argc, argv );
587 serverNamePrefix = "slap";
588 fprintf( stderr, "program name \"%s%s\" unrecognized; "
589 "aborting...\n", serverNamePrefix, serverName );
595 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
600 ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
601 ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
602 ldif_debug = slap_debug;
605 fprintf( stderr, "%s\n", Versionstr );
606 if ( version > 1 ) goto stop;
612 logName = ch_strdup( serverName );
615 logName = serverName;
619 openlog( logName, OPENLOG_OPTIONS, syslogUser );
621 openlog( logName, OPENLOG_OPTIONS );
628 Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
630 if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
632 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
636 #if defined(HAVE_CHROOT)
638 if ( chdir( sandbox ) ) {
643 if ( chroot( sandbox ) ) {
651 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
652 if ( username != NULL || groupname != NULL ) {
653 slap_init_user( username, groupname );
661 rc = slap_init( serverMode, serverName );
663 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
667 if ( read_config( configfile, configdir ) != 0 ) {
669 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
671 if ( check & CHECK_CONFIG ) {
672 fprintf( stderr, "config check failed\n" );
678 if ( debug_unknowns ) {
679 rc = parse_debug_unknowns( debug_unknowns, &slap_debug );
680 ldap_charray_free( debug_unknowns );
681 debug_unknowns = NULL;
685 if ( syslog_unknowns ) {
686 rc = parse_debug_unknowns( syslog_unknowns, &ldap_syslog );
687 ldap_charray_free( syslog_unknowns );
688 syslog_unknowns = NULL;
693 if ( check & CHECK_CONFIG ) {
694 fprintf( stderr, "config check succeeded\n" );
696 check &= ~CHECK_CONFIG;
697 if ( check == CHECK_NONE ) {
703 if ( glue_sub_attach( ) != 0 ) {
704 Debug( LDAP_DEBUG_ANY,
705 "subordinate config error\n",
711 if ( slap_schema_check( ) != 0 ) {
712 Debug( LDAP_DEBUG_ANY,
713 "schema prep error\n",
720 rc = ldap_pvt_tls_init();
722 Debug( LDAP_DEBUG_ANY,
723 "main: TLS init failed: %d\n",
726 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
731 void *def_ctx = NULL;
733 /* Save existing default ctx, if any */
734 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &def_ctx );
736 /* Force new ctx to be created */
737 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, NULL );
739 rc = ldap_pvt_tls_init_def_ctx( 1 );
741 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
742 /* Restore previous ctx */
743 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, def_ctx );
744 load_extop( &slap_EXOP_START_TLS, 0, starttls_extop );
745 } else if ( rc != LDAP_NOT_SUPPORTED ) {
746 Debug( LDAP_DEBUG_ANY,
747 "main: TLS init def ctx failed: %d\n",
750 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
756 (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
757 (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
760 (void) SIGNAL( SIGPIPE, SIG_IGN );
763 (void) SIGNAL( SIGHUP, slap_sig_shutdown );
765 (void) SIGNAL( SIGINT, slap_sig_shutdown );
766 (void) SIGNAL( SIGTERM, slap_sig_shutdown );
768 (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
771 (void) SIGNAL( LDAP_SIGCHLD, wait4child );
774 /* SIGBREAK is generated when Ctrl-Break is pressed. */
775 (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
779 lutil_detach( no_detach, 0 );
780 #endif /* HAVE_WINSOCK */
786 if ( slapd_pid_file != NULL ) {
787 FILE *fp = fopen( slapd_pid_file, "w" );
790 int save_errno = errno;
792 Debug( LDAP_DEBUG_ANY, "unable to open pid file "
795 save_errno, strerror( save_errno ) );
797 free( slapd_pid_file );
798 slapd_pid_file = NULL;
803 fprintf( fp, "%d\n", (int) getpid() );
805 slapd_pid_file_unlink = 1;
808 if ( slapd_args_file != NULL ) {
809 FILE *fp = fopen( slapd_args_file, "w" );
812 int save_errno = errno;
814 Debug( LDAP_DEBUG_ANY, "unable to open args file "
817 save_errno, strerror( save_errno ) );
819 free( slapd_args_file );
820 slapd_args_file = NULL;
826 for ( i = 0; i < g_argc; i++ ) {
827 fprintf( fp, "%s ", g_argv[i] );
831 slapd_args_file_unlink = 1;
835 * FIXME: moved here from slapd_daemon_task()
836 * because back-monitor db_open() needs it
840 if ( slap_startup( NULL ) != 0 ) {
842 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
846 Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
848 #ifdef HAVE_NT_EVENT_LOG
850 lutil_LogStartedEvent( serverName, slap_debug, configfile ?
851 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
856 #ifdef HAVE_NT_SERVICE_MANAGER
857 /* Throw away the event that we used during the startup process. */
859 ldap_pvt_thread_cond_destroy( &started_event );
863 /* remember an error during shutdown */
864 rc |= slap_shutdown( NULL );
867 /* remember an error during destroy */
868 rc |= slap_destroy();
870 while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
871 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
872 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
885 #ifdef HAVE_NT_EVENT_LOG
887 lutil_LogStoppedEvent( serverName );
890 Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
893 #ifdef HAVE_NT_SERVICE_MANAGER
894 lutil_ReportShutdownComplete();
900 slapd_daemon_destroy();
906 lutil_passwd_destroy();
909 ldap_pvt_tls_destroy();
912 if ( slapd_pid_file_unlink ) {
913 unlink( slapd_pid_file );
915 if ( slapd_args_file_unlink ) {
916 unlink( slapd_args_file );
922 ch_free( configfile );
924 ch_free( configdir );
929 mal_dumpleaktrace( leakfile );
939 * Catch and discard terminated child processes, to avoid zombies.
943 wait4child( int sig )
945 int save_errno = errno;
950 while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
953 while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
959 (void) SIGNAL_REINSTALL( sig, wait4child );
963 #endif /* LDAP_SIGCHLD */
969 * Convert a string to an integer by means of a dispatcher table
970 * if the string is not in the table return the default
974 cnvt_str2int( char *stringVal, STRDISP_P dispatcher, int defaultVal )
976 int retVal = defaultVal;
979 for (disp = dispatcher; disp->stringVal; disp++) {
981 if (!strncasecmp (stringVal, disp->stringVal, disp->abbr)) {
983 retVal = disp->intVal;
992 #endif /* LOG_LOCAL4 */