2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4 * Copyright 1998-2005 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 }
192 "usage: %s options\n", name );
194 "\t-4\t\tIPv4 only\n"
195 "\t-6\t\tIPv6 only\n"
196 "\t-T {acl|add|auth|cat|dn|index|passwd|test}\n"
197 "\t\t\tRun in Tool mode\n"
198 "\t-c cookie\tSync cookie of consumer\n"
199 "\t-d level\tDebug level" "\n"
200 "\t-f filename\tConfiguration file\n"
201 "\t-F dir\tConfiguration directory\n"
202 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
203 "\t-g group\tGroup (id or name) to run as\n"
205 "\t-h URLs\t\tList of URLs to serve\n"
207 "\t-l facility\tSyslog facility (default: LOCAL4)\n"
209 "\t-n serverName\tService name\n"
210 "\t-o <opt>[=val] generic means to specify options" );
211 if ( !BER_BVISNULL( &option_helpers[0].oh_name ) ) {
214 fprintf( stderr, "; supported options:\n" );
215 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++) {
216 fprintf( stderr, "\t\t%s\n", option_helpers[i].oh_usage );
219 fprintf( stderr, "\n" );
223 "\t-r directory\tSandbox directory to chroot to\n"
225 "\t-s level\tSyslog level\n"
226 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
227 "\t-u user\t\tUser (id or name) to run as\n"
229 "\t-V\t\tprint version info (-VV only)\n"
233 #ifdef HAVE_NT_SERVICE_MANAGER
234 void WINAPI ServiceMain( DWORD argc, LPTSTR *argv )
236 int main( int argc, char **argv )
239 int i, no_detach = 0;
242 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
243 char *username = NULL;
244 char *groupname = NULL;
246 #if defined(HAVE_CHROOT)
247 char *sandbox = NULL;
250 int syslogUser = DEFAULT_SYSLOG_USER;
254 char **g_argv = argv;
256 char *configfile = NULL;
257 char *configdir = NULL;
259 int serverMode = SLAP_SERVER_MODE;
261 struct sync_cookie *scp = NULL;
262 struct sync_cookie *scp_entry = NULL;
264 char *serverNamePrefix = "";
267 int slapd_pid_file_unlink = 0, slapd_args_file_unlink = 0;
271 if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
278 (void) ldap_pvt_thread_initialize();
280 serverName = lutil_progname( "slapd", argc, argv );
282 if ( strcmp( serverName, "slapd" ) ) {
283 for (i=0; tools[i].name; i++) {
284 if ( !strcmp( serverName, tools[i].name ) ) {
285 rc = tools[i].func(argc, argv);
291 #ifdef HAVE_NT_SERVICE_MANAGER
297 char *regService = NULL;
299 if ( is_NT_Service ) {
300 lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
301 if ( strcmp(serverName, SERVICE_NAME) )
302 regService = serverName;
305 i = (int*)lutil_getRegParam( regService, "DebugLevel" );
308 Debug( LDAP_DEBUG_ANY,
309 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
312 newUrls = (char *) lutil_getRegParam(regService, "Urls");
317 urls = ch_strdup(newUrls);
318 Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
322 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
323 if ( newConfigFile != NULL ) {
324 configfile = newConfigFile;
325 Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
328 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
329 if ( newConfigDir != NULL ) {
330 configdir = newConfigDir;
331 Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
336 while ( (i = getopt( argc, argv,
337 "c:d:f:F:h:n:o:s:tT:V"
347 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
354 slap_inet4or6 = AF_INET;
357 slap_inet4or6 = AF_INET6;
361 case 'h': /* listen URLs */
362 if ( urls != NULL ) free( urls );
363 urls = ch_strdup( optarg );
366 case 'c': /* provide sync cookie, override if exist in replica */
367 scp = (struct sync_cookie *) ch_calloc( 1,
368 sizeof( struct sync_cookie ));
369 ber_str2bv( optarg, 0, 1, &scp->octet_str );
371 /* This only parses out the rid at this point */
372 slap_parse_sync_cookie( scp, NULL );
374 if ( scp->rid == -1 ) {
375 Debug( LDAP_DEBUG_ANY,
376 "main: invalid cookie \"%s\"\n",
378 slap_sync_cookie_free( scp, 1 );
382 LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
383 if ( scp->rid == scp_entry->rid ) {
384 Debug( LDAP_DEBUG_ANY,
385 "main: duplicated replica id in cookies\n",
387 slap_sync_cookie_free( scp, 1 );
391 LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
394 case 'd': { /* set debug level and 'do not detach' flag */
399 if ( optarg != NULL && optarg[ 0 ] != '-' && !isdigit( optarg[ 0 ] ) )
404 levels = ldap_str2charray( optarg, "," );
406 for ( i = 0; levels[ i ] != NULL; i++ ) {
409 if ( str2loglevel( levels[ i ], &level ) ) {
411 "unrecognized log level "
412 "\"%s\"\n", levels[ i ] );
414 /* but keep parsing... */
421 ldap_charray_free( levels );
428 if ( lutil_atoix( &level, optarg, 0 ) != 0 ) {
430 "unrecognized log level "
431 "\"%s\"\n", optarg );
437 if ( lutil_atoi( &level, optarg ) != 0 || level != 0 )
438 fputs( "must compile with LDAP_DEBUG for debugging\n",
443 case 'f': /* read config file */
444 configfile = ch_strdup( optarg );
447 case 'F': /* use config dir */
448 configdir = ch_strdup( optarg );
452 char *val = strchr( optarg, '=' );
459 opt.bv_len = ( val - optarg );
463 opt.bv_len = strlen( optarg );
466 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
467 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
468 assert( option_helpers[i].oh_fnc != NULL );
469 if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
470 /* we assume the option parsing helper
471 * issues appropriate and self-explanatory
472 * error messages... */
479 if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
480 goto unhandled_option;
485 case 's': /* set syslog level */
486 if ( !isdigit( optarg[ 0 ] ) ) {
487 slap_verbmasks str2syslog_level[] = {
488 { BER_BVC( "EMERG" ), LOG_EMERG },
489 { BER_BVC( "ALERT" ), LOG_ALERT },
490 { BER_BVC( "CRIT" ), LOG_CRIT },
491 { BER_BVC( "ERR" ), LOG_ERR },
492 { BER_BVC( "WARNING" ), LOG_WARNING },
493 { BER_BVC( "NOTICE" ), LOG_NOTICE },
494 { BER_BVC( "INFO" ), LOG_INFO },
495 { BER_BVC( "DEBUG" ), LOG_DEBUG },
498 int i = verb_to_mask( optarg, str2syslog_level );
499 if ( BER_BVISNULL( &str2syslog_level[ i ].word ) ) {
500 Debug( LDAP_DEBUG_ANY,
501 "unknown syslog level \"%s\".\n",
506 ldap_syslog_level = str2syslog_level[ i ].mask;
508 } else if ( lutil_atoi( &ldap_syslog_level, optarg ) != 0 ) {
509 Debug( LDAP_DEBUG_ANY,
510 "unable to parse syslog level \"%s\".\n",
517 case 'l': /* set syslog local user */
518 syslogUser = cnvt_str2int( optarg,
519 syslog_types, DEFAULT_SYSLOG_USER );
525 if( sandbox ) free(sandbox);
526 sandbox = ch_strdup( optarg );
530 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
531 case 'u': /* user name */
532 if( username ) free(username);
533 username = ch_strdup( optarg );
536 case 'g': /* group name */
537 if( groupname ) free(groupname);
538 groupname = ch_strdup( optarg );
540 #endif /* SETUID && GETUID */
542 case 'n': /* NT service name */
543 serverName = ch_strdup( optarg );
547 /* deprecated; use slaptest instead */
548 fprintf( stderr, "option -t deprecated; "
549 "use slaptest command instead\n" );
550 check |= CHECK_CONFIG;
558 /* try full option string first */
559 for ( i = 0; tools[i].name; i++ ) {
560 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
561 rc = tools[i].func( argc, argv );
566 /* try bits of option string (backward compatibility for single char) */
567 l = strlen( optarg );
568 for ( i = 0; tools[i].name; i++ ) {
569 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
570 rc = tools[i].func( argc, argv );
577 serverNamePrefix = "slap";
578 fprintf( stderr, "program name \"%s%s\" unrecognized; "
579 "aborting...\n", serverNamePrefix, serverName );
585 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
590 ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
591 ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
592 ldif_debug = slap_debug;
595 fprintf( stderr, "%s\n", Versionstr );
596 if ( version > 1 ) goto stop;
602 logName = ch_strdup( serverName );
605 logName = serverName;
609 openlog( logName, OPENLOG_OPTIONS, syslogUser );
611 openlog( logName, OPENLOG_OPTIONS );
618 Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
620 if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
622 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
626 #if defined(HAVE_CHROOT)
628 if ( chdir( sandbox ) ) {
633 if ( chroot( sandbox ) ) {
641 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
642 if ( username != NULL || groupname != NULL ) {
643 slap_init_user( username, groupname );
651 rc = slap_init( serverMode, serverName );
653 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
657 if ( read_config( configfile, configdir ) != 0 ) {
659 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
661 if ( check & CHECK_CONFIG ) {
662 fprintf( stderr, "config check failed\n" );
668 if ( check & CHECK_CONFIG ) {
669 fprintf( stderr, "config check succeeded\n" );
671 check &= ~CHECK_CONFIG;
672 if ( check == CHECK_NONE ) {
678 if ( glue_sub_attach( ) != 0 ) {
679 Debug( LDAP_DEBUG_ANY,
680 "subordinate config error\n",
686 if ( slap_schema_check( ) != 0 ) {
687 Debug( LDAP_DEBUG_ANY,
688 "schema prep error\n",
695 rc = ldap_pvt_tls_init();
697 Debug( LDAP_DEBUG_ANY,
698 "main: TLS init failed: %d\n",
701 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
706 void *def_ctx = NULL;
708 /* Save existing default ctx, if any */
709 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &def_ctx );
711 /* Force new ctx to be created */
712 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, NULL );
714 rc = ldap_pvt_tls_init_def_ctx( 1 );
716 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
717 /* Restore previous ctx */
718 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, def_ctx );
719 load_extop( &slap_EXOP_START_TLS, 0, starttls_extop );
720 } else if ( rc != LDAP_NOT_SUPPORTED ) {
721 Debug( LDAP_DEBUG_ANY,
722 "main: TLS init def ctx failed: %d\n",
725 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
731 (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
732 (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
735 (void) SIGNAL( SIGPIPE, SIG_IGN );
738 (void) SIGNAL( SIGHUP, slap_sig_shutdown );
740 (void) SIGNAL( SIGINT, slap_sig_shutdown );
741 (void) SIGNAL( SIGTERM, slap_sig_shutdown );
743 (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
746 (void) SIGNAL( LDAP_SIGCHLD, wait4child );
749 /* SIGBREAK is generated when Ctrl-Break is pressed. */
750 (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
754 lutil_detach( no_detach, 0 );
755 #endif /* HAVE_WINSOCK */
761 if ( slapd_pid_file != NULL ) {
762 FILE *fp = fopen( slapd_pid_file, "w" );
765 int save_errno = errno;
767 Debug( LDAP_DEBUG_ANY, "unable to open pid file "
770 save_errno, strerror( save_errno ) );
772 free( slapd_pid_file );
773 slapd_pid_file = NULL;
778 fprintf( fp, "%d\n", (int) getpid() );
780 slapd_pid_file_unlink = 1;
783 if ( slapd_args_file != NULL ) {
784 FILE *fp = fopen( slapd_args_file, "w" );
787 int save_errno = errno;
789 Debug( LDAP_DEBUG_ANY, "unable to open args file "
792 save_errno, strerror( save_errno ) );
794 free( slapd_args_file );
795 slapd_args_file = NULL;
801 for ( i = 0; i < g_argc; i++ ) {
802 fprintf( fp, "%s ", g_argv[i] );
806 slapd_args_file_unlink = 1;
810 * FIXME: moved here from slapd_daemon_task()
811 * because back-monitor db_open() needs it
815 if ( slap_startup( NULL ) != 0 ) {
817 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
821 Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
823 #ifdef HAVE_NT_EVENT_LOG
825 lutil_LogStartedEvent( serverName, slap_debug, configfile ?
826 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
831 #ifdef HAVE_NT_SERVICE_MANAGER
832 /* Throw away the event that we used during the startup process. */
834 ldap_pvt_thread_cond_destroy( &started_event );
838 /* remember an error during shutdown */
839 rc |= slap_shutdown( NULL );
842 /* remember an error during destroy */
843 rc |= slap_destroy();
845 while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
846 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
847 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
859 supported_feature_destroy();
862 #ifdef HAVE_NT_EVENT_LOG
864 lutil_LogStoppedEvent( serverName );
867 Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
870 #ifdef HAVE_NT_SERVICE_MANAGER
871 lutil_ReportShutdownComplete();
877 slapd_daemon_destroy();
883 lutil_passwd_destroy();
886 ldap_pvt_tls_destroy();
889 if ( slapd_pid_file_unlink ) {
890 unlink( slapd_pid_file );
892 if ( slapd_args_file_unlink ) {
893 unlink( slapd_args_file );
899 ch_free( configfile );
901 ch_free( configdir );
906 mal_dumpleaktrace( leakfile );
916 * Catch and discard terminated child processes, to avoid zombies.
920 wait4child( int sig )
922 int save_errno = errno;
927 while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
930 while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
936 (void) SIGNAL_REINSTALL( sig, wait4child );
940 #endif /* LDAP_SIGCHLD */
946 * Convert a string to an integer by means of a dispatcher table
947 * if the string is not in the table return the default
951 cnvt_str2int( char *stringVal, STRDISP_P dispatcher, int defaultVal )
953 int retVal = defaultVal;
956 for (disp = dispatcher; disp->stringVal; disp++) {
958 if (!strncasecmp (stringVal, disp->stringVal, disp->abbr)) {
960 retVal = disp->intVal;
969 #endif /* LOG_LOCAL4 */