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 = "";
269 if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
276 (void) ldap_pvt_thread_initialize();
278 serverName = lutil_progname( "slapd", argc, argv );
280 if ( strcmp( serverName, "slapd" ) ) {
281 for (i=0; tools[i].name; i++) {
282 if ( !strcmp( serverName, tools[i].name ) ) {
283 rc = tools[i].func(argc, argv);
289 #ifdef HAVE_NT_SERVICE_MANAGER
295 char *regService = NULL;
297 if ( is_NT_Service ) {
298 lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
299 if ( strcmp(serverName, SERVICE_NAME) )
300 regService = serverName;
303 i = (int*)lutil_getRegParam( regService, "DebugLevel" );
306 Debug( LDAP_DEBUG_ANY,
307 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
310 newUrls = (char *) lutil_getRegParam(regService, "Urls");
315 urls = ch_strdup(newUrls);
316 Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
320 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
321 if ( newConfigFile != NULL ) {
322 configfile = newConfigFile;
323 Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
326 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
327 if ( newConfigDir != NULL ) {
328 configdir = newConfigDir;
329 Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
334 while ( (i = getopt( argc, argv,
335 "c:d:f:F:h:n:o:s:tT:V"
345 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
352 slap_inet4or6 = AF_INET;
355 slap_inet4or6 = AF_INET6;
359 case 'h': /* listen URLs */
360 if ( urls != NULL ) free( urls );
361 urls = ch_strdup( optarg );
364 case 'c': /* provide sync cookie, override if exist in replica */
365 scp = (struct sync_cookie *) ch_calloc( 1,
366 sizeof( struct sync_cookie ));
367 ber_str2bv( optarg, 0, 1, &scp->octet_str );
369 /* This only parses out the rid at this point */
370 slap_parse_sync_cookie( scp, NULL );
372 if ( scp->rid == -1 ) {
373 Debug( LDAP_DEBUG_ANY,
374 "main: invalid cookie \"%s\"\n",
376 slap_sync_cookie_free( scp, 1 );
380 LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
381 if ( scp->rid == scp_entry->rid ) {
382 Debug( LDAP_DEBUG_ANY,
383 "main: duplicated replica id in cookies\n",
385 slap_sync_cookie_free( scp, 1 );
389 LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
392 case 'd': /* set debug level and 'do not detach' flag */
395 if ( optarg != NULL && optarg[ 0 ] != '-' && !isdigit( optarg[ 0 ] ) )
399 if ( str2loglevel( optarg, &level ) ) {
401 "unrecognized log level "
402 "\"%s\"\n", optarg );
410 if ( lutil_atoix( &level, optarg, 0 ) != 0 ) {
412 "unrecognized log level "
413 "\"%s\"\n", optarg );
419 if ( lutil_atoi( &level, optarg ) != 0 || level != 0 )
420 fputs( "must compile with LDAP_DEBUG for debugging\n",
425 case 'f': /* read config file */
426 configfile = ch_strdup( optarg );
429 case 'F': /* use config dir */
430 configdir = ch_strdup( optarg );
434 char *val = strchr( optarg, '=' );
441 opt.bv_len = ( val - optarg );
445 opt.bv_len = strlen( optarg );
448 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
449 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
450 assert( option_helpers[i].oh_fnc != NULL );
451 if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
452 /* we assume the option parsing helper
453 * issues appropriate and self-explanatory
454 * error messages... */
461 if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
462 goto unhandled_option;
467 case 's': /* set syslog level */
468 if ( lutil_atoi( &ldap_syslog, optarg ) != 0 ) {
469 fprintf( stderr, "unable to parse syslog level \"%s\"", optarg );
475 case 'l': /* set syslog local user */
476 syslogUser = cnvt_str2int( optarg,
477 syslog_types, DEFAULT_SYSLOG_USER );
483 if( sandbox ) free(sandbox);
484 sandbox = ch_strdup( optarg );
488 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
489 case 'u': /* user name */
490 if( username ) free(username);
491 username = ch_strdup( optarg );
494 case 'g': /* group name */
495 if( groupname ) free(groupname);
496 groupname = ch_strdup( optarg );
498 #endif /* SETUID && GETUID */
500 case 'n': /* NT service name */
501 serverName = ch_strdup( optarg );
505 /* deprecated; use slaptest instead */
506 fprintf( stderr, "option -t deprecated; "
507 "use slaptest command instead\n" );
508 check |= CHECK_CONFIG;
516 /* try full option string first */
517 for ( i = 0; tools[i].name; i++ ) {
518 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
519 rc = tools[i].func( argc, argv );
524 /* try bits of option string (backward compatibility for single char) */
525 l = strlen( optarg );
526 for ( i = 0; tools[i].name; i++ ) {
527 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
528 rc = tools[i].func( argc, argv );
535 serverNamePrefix = "slap";
536 fprintf( stderr, "program name \"%s%s\" unrecognized; "
537 "aborting...\n", serverNamePrefix, serverName );
543 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
548 ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
549 ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
550 ldif_debug = slap_debug;
553 fprintf( stderr, "%s\n", Versionstr );
554 if ( version > 1 ) goto stop;
560 logName = ch_strdup( serverName );
563 logName = serverName;
567 openlog( logName, OPENLOG_OPTIONS, syslogUser );
569 openlog( logName, OPENLOG_OPTIONS );
576 Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
578 if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
580 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
584 #if defined(HAVE_CHROOT)
586 if ( chdir( sandbox ) ) {
591 if ( chroot( sandbox ) ) {
599 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
600 if ( username != NULL || groupname != NULL ) {
601 slap_init_user( username, groupname );
609 rc = slap_init( serverMode, serverName );
611 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
615 if ( read_config( configfile, configdir ) != 0 ) {
617 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
619 if ( check & CHECK_CONFIG ) {
620 fprintf( stderr, "config check failed\n" );
626 if ( check & CHECK_CONFIG ) {
627 fprintf( stderr, "config check succeeded\n" );
629 check &= ~CHECK_CONFIG;
630 if ( check == CHECK_NONE ) {
636 if ( glue_sub_attach( ) != 0 ) {
637 Debug( LDAP_DEBUG_ANY,
638 "subordinate config error\n",
644 if ( slap_schema_check( ) != 0 ) {
645 Debug( LDAP_DEBUG_ANY,
646 "schema prep error\n",
653 rc = ldap_pvt_tls_init();
655 Debug( LDAP_DEBUG_ANY,
656 "main: TLS init failed: %d\n",
659 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
664 void *def_ctx = NULL;
666 /* Save existing default ctx, if any */
667 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &def_ctx );
669 /* Force new ctx to be created */
670 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, NULL );
672 rc = ldap_pvt_tls_init_def_ctx( 1 );
674 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
675 /* Restore previous ctx */
676 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, def_ctx );
677 load_extop( &slap_EXOP_START_TLS, 0, starttls_extop );
678 } else if ( rc != LDAP_NOT_SUPPORTED ) {
679 Debug( LDAP_DEBUG_ANY,
680 "main: TLS init def ctx failed: %d\n",
683 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
689 (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
690 (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
693 (void) SIGNAL( SIGPIPE, SIG_IGN );
696 (void) SIGNAL( SIGHUP, slap_sig_shutdown );
698 (void) SIGNAL( SIGINT, slap_sig_shutdown );
699 (void) SIGNAL( SIGTERM, slap_sig_shutdown );
701 (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
704 (void) SIGNAL( LDAP_SIGCHLD, wait4child );
707 /* SIGBREAK is generated when Ctrl-Break is pressed. */
708 (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
712 lutil_detach( no_detach, 0 );
713 #endif /* HAVE_WINSOCK */
720 * FIXME: moved here from slapd_daemon_task()
721 * because back-monitor db_open() needs it
725 if ( slap_startup( NULL ) != 0 ) {
727 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
731 Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
733 if ( slapd_pid_file != NULL ) {
734 FILE *fp = fopen( slapd_pid_file, "w" );
737 int save_errno = errno;
739 Debug( LDAP_DEBUG_ANY, "unable to open pid file "
742 save_errno, strerror( save_errno ) );
744 free( slapd_pid_file );
745 slapd_pid_file = NULL;
751 fprintf( fp, "%d\n", (int) getpid() );
755 if ( slapd_args_file != NULL ) {
756 FILE *fp = fopen( slapd_args_file, "w" );
759 int save_errno = errno;
761 Debug( LDAP_DEBUG_ANY, "unable to open args file "
764 save_errno, strerror( save_errno ) );
766 free( slapd_args_file );
767 slapd_args_file = NULL;
773 for ( i = 0; i < g_argc; i++ ) {
774 fprintf( fp, "%s ", g_argv[i] );
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 );
816 supported_feature_destroy();
819 #ifdef HAVE_NT_EVENT_LOG
821 lutil_LogStoppedEvent( serverName );
824 Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
827 #ifdef HAVE_NT_SERVICE_MANAGER
828 lutil_ReportShutdownComplete();
834 slapd_daemon_destroy();
840 lutil_passwd_destroy();
843 ldap_pvt_tls_destroy();
846 if ( slapd_pid_file != NULL ) {
847 unlink( slapd_pid_file );
849 if ( slapd_args_file != NULL ) {
850 unlink( slapd_args_file );
856 ch_free( configfile );
858 ch_free( configdir );
863 mal_dumpleaktrace( leakfile );
873 * Catch and discard terminated child processes, to avoid zombies.
877 wait4child( int sig )
879 int save_errno = errno;
884 while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
887 while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
893 (void) SIGNAL_REINSTALL( sig, wait4child );
897 #endif /* LDAP_SIGCHLD */
903 * Convert a string to an integer by means of a dispatcher table
904 * if the string is not in the table return the default
908 cnvt_str2int( char *stringVal, STRDISP_P dispatcher, int defaultVal )
910 int retVal = defaultVal;
913 for (disp = dispatcher; disp->stringVal; disp++) {
915 if (!strncasecmp (stringVal, disp->stringVal, disp->abbr)) {
917 retVal = disp->intVal;
926 #endif /* LOG_LOCAL4 */