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.
30 #include <ac/socket.h>
31 #include <ac/string.h>
33 #include <ac/unistd.h>
42 #include "slapi/slapi.h"
46 static RETSIGTYPE wait4child( int sig );
49 #ifdef HAVE_NT_SERVICE_MANAGER
50 #define MAIN_RETURN(x) return
51 static struct sockaddr_in bind_addr;
53 #define SERVICE_EXIT( e, n ) do { \
54 if ( is_NT_Service ) { \
55 lutil_ServiceStatus.dwWin32ExitCode = (e); \
56 lutil_ServiceStatus.dwServiceSpecificExitCode = (n); \
61 #define SERVICE_EXIT( e, n )
62 #define MAIN_RETURN(x) return(x)
65 typedef int (MainFunc) LDAP_P(( int argc, char *argv[] ));
66 extern MainFunc slapadd, slapcat, slapdn, slapindex, slappasswd,
67 slaptest, slapauth, slapacl;
76 {"slapindex", slapindex},
77 {"slappasswd", slappasswd},
78 {"slaptest", slaptest},
79 {"slapauth", slapauth},
81 /* NOTE: new tools must be added in chronological order,
82 * not in alphabetical order, because for backwards
83 * compatibility name[4] is used to identify the
84 * tools; so name[4]=='a' must refer to "slapadd" and
85 * not to "slapauth". Alphabetical order can be used
86 * for tools whose name[4] is not used yet */
91 * when more than one slapd is running on one machine, each one might have
92 * it's own LOCAL for syslogging and must have its own pid/args files
95 #ifndef HAVE_MKVERSION
96 const char Versionstr[] =
97 OPENLDAP_PACKAGE " " OPENLDAP_VERSION " Standalone LDAP Server (slapd)";
101 #define DEFAULT_SYSLOG_USER LOG_LOCAL4
103 typedef struct _str2intDispatch {
107 } STRDISP, *STRDISP_P;
109 /* table to compute syslog-options to integer */
110 static STRDISP syslog_types[] = {
111 { "LOCAL0", sizeof("LOCAL0"), LOG_LOCAL0 },
112 { "LOCAL1", sizeof("LOCAL1"), LOG_LOCAL1 },
113 { "LOCAL2", sizeof("LOCAL2"), LOG_LOCAL2 },
114 { "LOCAL3", sizeof("LOCAL3"), LOG_LOCAL3 },
115 { "LOCAL4", sizeof("LOCAL4"), LOG_LOCAL4 },
116 { "LOCAL5", sizeof("LOCAL5"), LOG_LOCAL5 },
117 { "LOCAL6", sizeof("LOCAL6"), LOG_LOCAL6 },
118 { "LOCAL7", sizeof("LOCAL7"), LOG_LOCAL7 },
120 { "USER", sizeof("USER"), LOG_USER },
123 { "DAEMON", sizeof("DAEMON"), LOG_DAEMON },
128 static int cnvt_str2int( char *, STRDISP_P, int );
129 #endif /* LOG_LOCAL4 */
131 #define CHECK_NONE 0x00
132 #define CHECK_CONFIG 0x01
133 static int check = CHECK_NONE;
134 static int version = 0;
139 slapd_opt_slp( const char *val, void *arg )
142 /* NULL is default */
143 if ( val == NULL || strcasecmp( val, "on" ) == 0 ) {
144 slapd_register_slp = 1;
146 } else if ( strcasecmp( val, "off" ) == 0 ) {
147 slapd_register_slp = 0;
149 /* NOTE: add support for URL specification? */
152 fprintf(stderr, "unrecognized value \"%s\" for SLP option\n", val );
159 fputs( "slapd: SLP support is not available\n", stderr );
165 * Option helper structure:
167 * oh_nam is left-hand part of <option>[=<value>]
168 * oh_fnc is handler function
169 * oh_arg is an optional arg to oh_fnc
170 * oh_usage is the one-line usage string related to the option,
171 * which is assumed to start with <option>[=<value>]
173 * please leave valid options in the structure, and optionally #ifdef
174 * their processing inside the helper, so that reasonable and helpful
175 * error messages can be generated if a disabled option is requested.
177 struct option_helper {
178 struct berval oh_name;
179 int (*oh_fnc)(const char *val, void *arg);
181 const char *oh_usage;
182 } option_helpers[] = {
183 { BER_BVC("slp"), slapd_opt_slp, NULL, "slp[={on|off}] enable/disable SLP" },
184 { BER_BVNULL, 0, NULL, NULL }
191 "usage: %s options\n", name );
193 "\t-4\t\tIPv4 only\n"
194 "\t-6\t\tIPv6 only\n"
195 "\t-T {acl|add|auth|cat|dn|index|passwd|test}\n"
196 "\t\t\tRun in Tool mode\n"
197 "\t-c cookie\tSync cookie of consumer\n"
198 "\t-d level\tDebug level" "\n"
199 "\t-f filename\tConfiguration file\n"
200 "\t-F dir\tConfiguration directory\n"
201 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
202 "\t-g group\tGroup (id or name) to run as\n"
204 "\t-h URLs\t\tList of URLs to serve\n"
206 "\t-l facility\tSyslog facility (default: LOCAL4)\n"
208 "\t-n serverName\tService name\n"
209 "\t-o <opt>[=val] generic means to specify options" );
210 if ( !BER_BVISNULL( &option_helpers[0].oh_name ) ) {
213 fprintf( stderr, "; supported options:\n" );
214 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++) {
215 fprintf( stderr, "\t\t%s\n", option_helpers[i].oh_usage );
218 fprintf( stderr, "\n" );
222 "\t-r directory\tSandbox directory to chroot to\n"
224 "\t-s level\tSyslog level\n"
225 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
226 "\t-u user\t\tUser (id or name) to run as\n"
228 "\t-V\t\tprint version info (-VV only)\n"
232 #ifdef HAVE_NT_SERVICE_MANAGER
233 void WINAPI ServiceMain( DWORD argc, LPTSTR *argv )
235 int main( int argc, char **argv )
238 int i, no_detach = 0;
241 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
242 char *username = NULL;
243 char *groupname = NULL;
245 #if defined(HAVE_CHROOT)
246 char *sandbox = NULL;
249 int syslogUser = DEFAULT_SYSLOG_USER;
253 char **g_argv = argv;
255 char *configfile = NULL;
256 char *configdir = NULL;
258 int serverMode = SLAP_SERVER_MODE;
260 struct sync_cookie *scp = NULL;
261 struct sync_cookie *scp_entry = NULL;
265 if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
269 char *serverNamePrefix = "";
274 if (( rc = slap_schema_init( )) != 0 ) {
275 Debug( LDAP_DEBUG_ANY,
276 "schema initialization error\n",
282 serverName = lutil_progname( "slapd", argc, argv );
284 if ( strcmp( serverName, "slapd" ) ) {
285 for (i=0; tools[i].name; i++) {
286 if ( !strcmp( serverName, tools[i].name ) ) {
287 rc = tools[i].func(argc, argv);
293 #ifdef HAVE_NT_SERVICE_MANAGER
299 char *regService = NULL;
301 if ( is_NT_Service ) {
302 lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
303 if ( strcmp(serverName, SERVICE_NAME) )
304 regService = serverName;
307 i = (int*)lutil_getRegParam( regService, "DebugLevel" );
310 Debug( LDAP_DEBUG_ANY,
311 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
314 newUrls = (char *) lutil_getRegParam(regService, "Urls");
319 urls = ch_strdup(newUrls);
320 Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
324 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
325 if ( newConfigFile != NULL ) {
326 configfile = newConfigFile;
327 Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
330 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
331 if ( newConfigDir != NULL ) {
332 configdir = newConfigDir;
333 Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
338 while ( (i = getopt( argc, argv,
339 "c:d:f:F:h:n:o:s:StT:V"
349 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
356 slap_inet4or6 = AF_INET;
359 slap_inet4or6 = AF_INET6;
363 case 'h': /* listen URLs */
364 if ( urls != NULL ) free( urls );
365 urls = ch_strdup( optarg );
368 case 'c': /* provide sync cookie, override if exist in replica */
369 scp = (struct sync_cookie *) ch_calloc( 1,
370 sizeof( struct sync_cookie ));
371 ber_str2bv( optarg, 0, 1, &scp->octet_str );
372 slap_parse_sync_cookie( scp, NULL );
374 LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
375 if ( scp->rid == scp_entry->rid ) {
376 Debug( LDAP_DEBUG_ANY,
377 "main: duplicated replica id in cookies\n",
379 slap_sync_cookie_free( scp, 1 );
383 LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
386 case 'd': /* set debug level and 'do not detach' flag */
389 if ( optarg != NULL && optarg[ 0 ] != '-' && !isdigit( optarg[ 0 ] ) )
393 if ( str2loglevel( optarg, &level ) ) {
395 "unrecognized log level "
396 "\"%s\"\n", optarg );
402 slap_debug |= atoi( optarg );
405 if ( atoi( optarg ) != 0 )
406 fputs( "must compile with LDAP_DEBUG for debugging\n",
411 case 'f': /* read config file */
412 configfile = ch_strdup( optarg );
415 case 'F': /* use config dir */
416 configdir = ch_strdup( optarg );
420 char *val = strchr( optarg, '=' );
427 opt.bv_len = ( val - optarg );
431 opt.bv_len = strlen( optarg );
434 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
435 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
436 assert( option_helpers[i].oh_fnc != NULL );
437 if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
438 /* we assume the option parsing helper
439 * issues appropriate and self-explanatory
440 * error messages... */
447 if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
448 goto unhandled_option;
453 case 's': /* set syslog level */
454 ldap_syslog = atoi( optarg );
458 case 'l': /* set syslog local user */
459 syslogUser = cnvt_str2int( optarg,
460 syslog_types, DEFAULT_SYSLOG_USER );
466 if( sandbox ) free(sandbox);
467 sandbox = ch_strdup( optarg );
471 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
472 case 'u': /* user name */
473 if( username ) free(username);
474 username = ch_strdup( optarg );
477 case 'g': /* group name */
478 if( groupname ) free(groupname);
479 groupname = ch_strdup( optarg );
481 #endif /* SETUID && GETUID */
483 case 'n': /* NT service name */
484 serverName = ch_strdup( optarg );
488 /* deprecated; use slaptest instead */
489 fprintf( stderr, "option -t deprecated; "
490 "use slaptest command instead\n" );
491 check |= CHECK_CONFIG;
499 /* try full option string first */
500 for ( i = 0; tools[i].name; i++ ) {
501 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
502 rc = tools[i].func( argc, argv );
507 /* try bits of option string (backward compatibility for single char) */
508 l = strlen( optarg );
509 for ( i = 0; tools[i].name; i++ ) {
510 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
511 rc = tools[i].func( argc, argv );
518 serverNamePrefix = "slap";
519 fprintf( stderr, "program name \"%s%s\" unrecognized; "
520 "aborting...\n", serverNamePrefix, serverName );
526 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
531 (void) ldap_pvt_thread_initialize();
533 ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
534 ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
535 ldif_debug = slap_debug;
538 fprintf( stderr, "%s\n", Versionstr );
539 if ( version > 1 ) goto stop;
545 logName = ch_strdup( serverName );
548 logName = serverName;
552 openlog( logName, OPENLOG_OPTIONS, syslogUser );
554 openlog( logName, OPENLOG_OPTIONS );
561 Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
563 if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
565 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
569 #if defined(HAVE_CHROOT)
571 if ( chdir( sandbox ) ) {
576 if ( chroot( sandbox ) ) {
584 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
585 if ( username != NULL || groupname != NULL ) {
586 slap_init_user( username, groupname );
595 if ( module_init() != 0 ) {
597 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 17 );
603 if ( slap_init( serverMode, serverName ) != 0 ) {
605 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
609 if ( slap_controls_init( ) != 0 ) {
610 Debug( LDAP_DEBUG_ANY,
611 "controls initialization error\n",
618 /* Library defaults to full certificate checking. This is correct when
619 * a client is verifying a server because all servers should have a
620 * valid cert. But few clients have valid certs, so we want our default
621 * to be no checking. The config file can override this as usual.
624 (void) ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &rc );
627 if ( frontend_init() ) {
631 if ( overlay_init() ) {
639 #endif /* SLAP_DYNACL */
641 if ( read_config( configfile, configdir ) != 0 ) {
643 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
645 if ( check & CHECK_CONFIG ) {
646 fprintf( stderr, "config check failed\n" );
652 if ( check & CHECK_CONFIG ) {
653 fprintf( stderr, "config check succeeded\n" );
655 check &= ~CHECK_CONFIG;
656 if ( check == CHECK_NONE ) {
662 if ( slap_schema_check( ) != 0 ) {
663 Debug( LDAP_DEBUG_ANY,
664 "schema prep error\n",
671 rc = ldap_pvt_tls_init();
673 Debug( LDAP_DEBUG_ANY,
674 "main: TLS init failed: %d\n",
677 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
682 void *def_ctx = NULL;
684 /* Save existing default ctx, if any */
685 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &def_ctx );
687 /* Force new ctx to be created */
688 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, NULL );
690 rc = ldap_pvt_tls_init_def_ctx();
692 Debug( LDAP_DEBUG_ANY,
693 "main: TLS init def ctx failed: %d\n",
696 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
699 /* Retrieve slapd's own ctx */
700 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
701 /* Restore previous ctx */
702 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, def_ctx );
706 (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
707 (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
710 (void) SIGNAL( SIGPIPE, SIG_IGN );
713 (void) SIGNAL( SIGHUP, slap_sig_shutdown );
715 (void) SIGNAL( SIGINT, slap_sig_shutdown );
716 (void) SIGNAL( SIGTERM, slap_sig_shutdown );
718 (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
721 (void) SIGNAL( LDAP_SIGCHLD, wait4child );
724 /* SIGBREAK is generated when Ctrl-Break is pressed. */
725 (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
729 lutil_detach( no_detach, 0 );
730 #endif /* HAVE_WINSOCK */
737 * FIXME: moved here from slapd_daemon_task()
738 * because back-monitor db_open() needs it
742 if ( slap_startup( NULL ) != 0 ) {
744 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
748 Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
751 if ( slapd_pid_file != NULL ) {
752 FILE *fp = fopen( slapd_pid_file, "w" );
755 fprintf( fp, "%d\n", (int) getpid() );
759 free(slapd_pid_file);
760 slapd_pid_file = NULL;
764 if ( slapd_args_file != NULL ) {
765 FILE *fp = fopen( slapd_args_file, "w" );
768 for ( i = 0; i < g_argc; i++ ) {
769 fprintf( fp, "%s ", g_argv[i] );
774 free(slapd_args_file);
775 slapd_args_file = NULL;
779 #ifdef HAVE_NT_EVENT_LOG
781 lutil_LogStartedEvent( serverName, slap_debug, configfile ?
782 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
787 #ifdef HAVE_NT_SERVICE_MANAGER
788 /* Throw away the event that we used during the startup process. */
790 ldap_pvt_thread_cond_destroy( &started_event );
794 /* remember an error during shutdown */
795 rc |= slap_shutdown( NULL );
798 /* remember an error during destroy */
799 rc |= slap_destroy();
801 while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
802 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
803 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
816 #ifdef HAVE_NT_EVENT_LOG
818 lutil_LogStoppedEvent( serverName );
821 Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
824 #ifdef HAVE_NT_SERVICE_MANAGER
825 lutil_ReportShutdownComplete();
831 slapd_daemon_destroy();
837 lutil_passwd_destroy();
840 ldap_pvt_tls_destroy();
843 if ( slapd_pid_file != NULL ) {
844 unlink( slapd_pid_file );
846 if ( slapd_args_file != NULL ) {
847 unlink( slapd_args_file );
853 ch_free( configfile );
855 ch_free( configdir );
860 mal_dumpleaktrace( leakfile );
870 * Catch and discard terminated child processes, to avoid zombies.
874 wait4child( int sig )
876 int save_errno = errno;
881 while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
884 while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
890 (void) SIGNAL_REINSTALL( sig, wait4child );
894 #endif /* LDAP_SIGCHLD */
900 * Convert a string to an integer by means of a dispatcher table
901 * if the string is not in the table return the default
905 cnvt_str2int( char *stringVal, STRDISP_P dispatcher, int defaultVal )
907 int retVal = defaultVal;
910 for (disp = dispatcher; disp->stringVal; disp++) {
912 if (!strncasecmp (stringVal, disp->stringVal, disp->abbr)) {
914 retVal = disp->intVal;
923 #endif /* LOG_LOCAL4 */