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;
266 if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
270 char *serverNamePrefix = "";
275 if (( rc = slap_schema_init( )) != 0 ) {
276 Debug( LDAP_DEBUG_ANY,
277 "schema initialization error\n",
283 serverName = lutil_progname( "slapd", argc, argv );
285 if ( strcmp( serverName, "slapd" ) ) {
286 for (i=0; tools[i].name; i++) {
287 if ( !strcmp( serverName, tools[i].name ) ) {
288 rc = tools[i].func(argc, argv);
294 #ifdef HAVE_NT_SERVICE_MANAGER
300 char *regService = NULL;
302 if ( is_NT_Service ) {
303 lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
304 if ( strcmp(serverName, SERVICE_NAME) )
305 regService = serverName;
308 i = (int*)lutil_getRegParam( regService, "DebugLevel" );
311 Debug( LDAP_DEBUG_ANY,
312 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
315 newUrls = (char *) lutil_getRegParam(regService, "Urls");
320 urls = ch_strdup(newUrls);
321 Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
325 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
326 if ( newConfigFile != NULL ) {
327 configfile = newConfigFile;
328 Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
331 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
332 if ( newConfigDir != NULL ) {
333 configdir = newConfigDir;
334 Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
339 while ( (i = getopt( argc, argv,
340 "c:d:f:F:h:n:o:s:StT:V"
350 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
357 slap_inet4or6 = AF_INET;
360 slap_inet4or6 = AF_INET6;
364 case 'h': /* listen URLs */
365 if ( urls != NULL ) free( urls );
366 urls = ch_strdup( optarg );
369 case 'c': /* provide sync cookie, override if exist in replica */
370 scp = (struct sync_cookie *) ch_calloc( 1,
371 sizeof( struct sync_cookie ));
372 ber_str2bv( optarg, 0, 1, &scp->octet_str );
373 slap_parse_sync_cookie( scp, NULL );
375 LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
376 if ( scp->rid == scp_entry->rid ) {
377 Debug( LDAP_DEBUG_ANY,
378 "main: duplicated replica id in cookies\n",
380 slap_sync_cookie_free( scp, 1 );
384 LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
387 case 'd': /* set debug level and 'do not detach' flag */
390 if ( optarg != NULL && optarg[ 0 ] != '-' && !isdigit( optarg[ 0 ] ) )
394 if ( str2loglevel( optarg, &level ) ) {
396 "unrecognized log level "
397 "\"%s\"\n", optarg );
403 slap_debug |= atoi( optarg );
406 if ( atoi( optarg ) != 0 )
407 fputs( "must compile with LDAP_DEBUG for debugging\n",
412 case 'f': /* read config file */
413 configfile = ch_strdup( optarg );
416 case 'F': /* use config dir */
417 configdir = ch_strdup( optarg );
421 char *val = strchr( optarg, '=' );
428 opt.bv_len = ( val - optarg );
432 opt.bv_len = strlen( optarg );
435 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
436 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
437 assert( option_helpers[i].oh_fnc != NULL );
438 if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
439 /* we assume the option parsing helper
440 * issues appropriate and self-explanatory
441 * error messages... */
448 if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
449 goto unhandled_option;
454 case 's': /* set syslog level */
455 ldap_syslog = atoi( optarg );
459 case 'l': /* set syslog local user */
460 syslogUser = cnvt_str2int( optarg,
461 syslog_types, DEFAULT_SYSLOG_USER );
467 if( sandbox ) free(sandbox);
468 sandbox = ch_strdup( optarg );
472 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
473 case 'u': /* user name */
474 if( username ) free(username);
475 username = ch_strdup( optarg );
478 case 'g': /* group name */
479 if( groupname ) free(groupname);
480 groupname = ch_strdup( optarg );
482 #endif /* SETUID && GETUID */
484 case 'n': /* NT service name */
485 serverName = ch_strdup( optarg );
489 /* deprecated; use slaptest instead */
490 fprintf( stderr, "option -t deprecated; "
491 "use slaptest command instead\n" );
492 check |= CHECK_CONFIG;
500 /* try full option string first */
501 for ( i = 0; tools[i].name; i++ ) {
502 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
503 rc = tools[i].func( argc, argv );
508 /* try bits of option string (backward compatibility for single char) */
509 l = strlen( optarg );
510 for ( i = 0; tools[i].name; i++ ) {
511 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
512 rc = tools[i].func( argc, argv );
519 serverNamePrefix = "slap";
520 fprintf( stderr, "program name \"%s%s\" unrecognized; "
521 "aborting...\n", serverNamePrefix, serverName );
527 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
532 (void) ldap_pvt_thread_initialize();
534 ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
535 ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
536 ldif_debug = slap_debug;
539 fprintf( stderr, "%s\n", Versionstr );
540 if ( version > 1 ) goto stop;
546 logName = ch_strdup( serverName );
549 logName = serverName;
553 openlog( logName, OPENLOG_OPTIONS, syslogUser );
555 openlog( logName, OPENLOG_OPTIONS );
562 Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
564 if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
566 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
570 #if defined(HAVE_CHROOT)
572 if ( chdir( sandbox ) ) {
577 if ( chroot( sandbox ) ) {
585 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
586 if ( username != NULL || groupname != NULL ) {
587 slap_init_user( username, groupname );
596 if ( module_init() != 0 ) {
598 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 17 );
604 if ( slap_init( serverMode, serverName ) != 0 ) {
606 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
610 if ( slap_controls_init( ) != 0 ) {
611 Debug( LDAP_DEBUG_ANY,
612 "controls initialization error\n",
619 /* Library defaults to full certificate checking. This is correct when
620 * a client is verifying a server because all servers should have a
621 * valid cert. But few clients have valid certs, so we want our default
622 * to be no checking. The config file can override this as usual.
625 (void) ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &rc );
628 if ( frontend_init() ) {
632 if ( overlay_init() ) {
640 #endif /* SLAP_DYNACL */
642 if ( read_config( configfile, configdir ) != 0 ) {
644 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
646 if ( check & CHECK_CONFIG ) {
647 fprintf( stderr, "config check failed\n" );
653 if ( check & CHECK_CONFIG ) {
654 fprintf( stderr, "config check succeeded\n" );
656 check &= ~CHECK_CONFIG;
657 if ( check == CHECK_NONE ) {
663 if ( slap_schema_check( ) != 0 ) {
664 Debug( LDAP_DEBUG_ANY,
665 "schema prep error\n",
672 rc = ldap_pvt_tls_init();
674 Debug( LDAP_DEBUG_ANY,
675 "main: TLS init failed: %d\n",
678 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
683 void *def_ctx = NULL;
685 /* Save existing default ctx, if any */
686 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &def_ctx );
688 /* Force new ctx to be created */
689 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, NULL );
691 rc = ldap_pvt_tls_init_def_ctx();
693 Debug( LDAP_DEBUG_ANY,
694 "main: TLS init def ctx failed: %d\n",
697 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
700 /* Retrieve slapd's own ctx */
701 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
702 /* Restore previous ctx */
703 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, def_ctx );
707 (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
708 (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
711 (void) SIGNAL( SIGPIPE, SIG_IGN );
714 (void) SIGNAL( SIGHUP, slap_sig_shutdown );
716 (void) SIGNAL( SIGINT, slap_sig_shutdown );
717 (void) SIGNAL( SIGTERM, slap_sig_shutdown );
719 (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
722 (void) SIGNAL( LDAP_SIGCHLD, wait4child );
725 /* SIGBREAK is generated when Ctrl-Break is pressed. */
726 (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
730 lutil_detach( no_detach, 0 );
731 #endif /* HAVE_WINSOCK */
738 * FIXME: moved here from slapd_daemon_task()
739 * because back-monitor db_open() needs it
743 if ( slap_startup( NULL ) != 0 ) {
745 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
749 Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
752 if ( slapd_pid_file != NULL ) {
753 FILE *fp = fopen( slapd_pid_file, "w" );
756 fprintf( fp, "%d\n", (int) getpid() );
760 free(slapd_pid_file);
761 slapd_pid_file = NULL;
765 if ( slapd_args_file != NULL ) {
766 FILE *fp = fopen( slapd_args_file, "w" );
769 for ( i = 0; i < g_argc; i++ ) {
770 fprintf( fp, "%s ", g_argv[i] );
775 free(slapd_args_file);
776 slapd_args_file = NULL;
780 #ifdef HAVE_NT_EVENT_LOG
782 lutil_LogStartedEvent( serverName, slap_debug, configfile ?
783 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
788 #ifdef HAVE_NT_SERVICE_MANAGER
789 /* Throw away the event that we used during the startup process. */
791 ldap_pvt_thread_cond_destroy( &started_event );
795 /* remember an error during shutdown */
796 rc |= slap_shutdown( NULL );
799 /* remember an error during destroy */
800 rc |= slap_destroy();
802 while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
803 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
804 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
817 #ifdef HAVE_NT_EVENT_LOG
819 lutil_LogStoppedEvent( serverName );
822 Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
825 #ifdef HAVE_NT_SERVICE_MANAGER
826 lutil_ReportShutdownComplete();
832 slapd_daemon_destroy();
838 lutil_passwd_destroy();
841 ldap_pvt_tls_destroy();
844 if ( slapd_pid_file != NULL ) {
845 unlink( slapd_pid_file );
847 if ( slapd_args_file != NULL ) {
848 unlink( slapd_args_file );
854 ch_free( configfile );
856 ch_free( configdir );
861 mal_dumpleaktrace( leakfile );
871 * Catch and discard terminated child processes, to avoid zombies.
875 wait4child( int sig )
877 int save_errno = errno;
882 while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
885 while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
891 (void) SIGNAL_REINSTALL( sig, wait4child );
895 #endif /* LDAP_SIGCHLD */
901 * Convert a string to an integer by means of a dispatcher table
902 * if the string is not in the table return the default
906 cnvt_str2int( char *stringVal, STRDISP_P dispatcher, int defaultVal )
908 int retVal = defaultVal;
911 for (disp = dispatcher; disp->stringVal; disp++) {
913 if (!strncasecmp (stringVal, disp->stringVal, disp->abbr)) {
915 retVal = disp->intVal;
924 #endif /* LOG_LOCAL4 */