]> git.sur5r.net Git - openldap/blob - servers/slapd/main.c
ITS#6152 add olcProxyCacheOffline for manually toggling cache expiration,
[openldap] / servers / slapd / main.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2009 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
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>.
14  */
15 /* Portions Copyright (c) 1995 Regents of the University of Michigan.
16  * All rights reserved.
17  *
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.
24  */
25
26 #include "portable.h"
27
28 #include <stdio.h>
29
30 #include <ac/ctype.h>
31 #include <ac/socket.h>
32 #include <ac/string.h>
33 #include <ac/time.h>
34 #include <ac/unistd.h>
35 #include <ac/wait.h>
36 #include <ac/errno.h>
37
38 #include "slap.h"
39 #include "lutil.h"
40 #include "ldif.h"
41
42 #ifdef LDAP_SLAPI
43 #include "slapi/slapi.h"
44 #endif
45
46 #ifdef LDAP_SIGCHLD
47 static RETSIGTYPE wait4child( int sig );
48 #endif
49
50 #ifdef HAVE_NT_SERVICE_MANAGER
51 #define MAIN_RETURN(x) return
52 static struct sockaddr_in       bind_addr;
53
54 #define SERVICE_EXIT( e, n )    do { \
55         if ( is_NT_Service ) { \
56                 lutil_ServiceStatus.dwWin32ExitCode                             = (e); \
57                 lutil_ServiceStatus.dwServiceSpecificExitCode   = (n); \
58         } \
59 } while ( 0 )
60
61 #else
62 #define SERVICE_EXIT( e, n )
63 #define MAIN_RETURN(x) return(x)
64 #endif
65
66 typedef int (MainFunc) LDAP_P(( int argc, char *argv[] ));
67 extern MainFunc slapadd, slapcat, slapdn, slapindex, slappasswd,
68         slaptest, slapauth, slapacl, slapschema;
69
70 static struct {
71         char *name;
72         MainFunc *func;
73 } tools[] = {
74         {"slapadd", slapadd},
75         {"slapcat", slapcat},
76         {"slapdn", slapdn},
77         {"slapindex", slapindex},
78         {"slappasswd", slappasswd},
79         {"slapschema", slapschema},
80         {"slaptest", slaptest},
81         {"slapauth", slapauth},
82         {"slapacl", slapacl},
83         /* NOTE: new tools must be added in chronological order,
84          * not in alphabetical order, because for backwards
85          * compatibility name[4] is used to identify the
86          * tools; so name[4]=='a' must refer to "slapadd" and
87          * not to "slapauth".  Alphabetical order can be used
88          * for tools whose name[4] is not used yet */
89         {NULL, NULL}
90 };
91
92 /*
93  * when more than one slapd is running on one machine, each one might have
94  * it's own LOCAL for syslogging and must have its own pid/args files
95  */
96
97 #ifndef HAVE_MKVERSION
98 const char Versionstr[] =
99         OPENLDAP_PACKAGE " " OPENLDAP_VERSION " Standalone LDAP Server (slapd)";
100 #endif
101
102 #define CHECK_NONE      0x00
103 #define CHECK_CONFIG    0x01
104 #define CHECK_LOGLEVEL  0x02
105 static int check = CHECK_NONE;
106 static int version = 0;
107
108 void *slap_tls_ctx;
109 LDAP *slap_tls_ld;
110
111 static int
112 slapd_opt_slp( const char *val, void *arg )
113 {
114 #ifdef HAVE_SLP
115         /* NULL is default */
116         if ( val == NULL || *val == '(' || strcasecmp( val, "on" ) == 0 ) {
117                 slapd_register_slp = 1;
118                 slapd_slp_attrs = (val != NULL && *val == '(') ? val : NULL;
119
120         } else if ( strcasecmp( val, "off" ) == 0 ) {
121                 slapd_register_slp = 0;
122
123         /* NOTE: add support for URL specification? */
124
125         } else {
126                 fprintf(stderr, "unrecognized value \"%s\" for SLP option\n", val );
127                 return -1;
128         }
129
130         return 0;
131                 
132 #else
133         fputs( "slapd: SLP support is not available\n", stderr );
134         return 0;
135 #endif
136 }
137
138 /*
139  * Option helper structure:
140  * 
141  * oh_nam       is left-hand part of <option>[=<value>]
142  * oh_fnc       is handler function
143  * oh_arg       is an optional arg to oh_fnc
144  * oh_usage     is the one-line usage string related to the option,
145  *              which is assumed to start with <option>[=<value>]
146  *
147  * please leave valid options in the structure, and optionally #ifdef
148  * their processing inside the helper, so that reasonable and helpful
149  * error messages can be generated if a disabled option is requested.
150  */
151 struct option_helper {
152         struct berval   oh_name;
153         int             (*oh_fnc)(const char *val, void *arg);
154         void            *oh_arg;
155         const char      *oh_usage;
156 } option_helpers[] = {
157         { BER_BVC("slp"),       slapd_opt_slp,  NULL, "slp[={on|off|(attrs)}] enable/disable SLP using (attrs)" },
158         { BER_BVNULL, 0, NULL, NULL }
159 };
160
161 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
162 #ifdef LOG_LOCAL4
163 int
164 parse_syslog_user( const char *arg, int *syslogUser )
165 {
166         static slap_verbmasks syslogUsers[] = {
167                 { BER_BVC( "LOCAL0" ), LOG_LOCAL0 },
168                 { BER_BVC( "LOCAL1" ), LOG_LOCAL1 },
169                 { BER_BVC( "LOCAL2" ), LOG_LOCAL2 },
170                 { BER_BVC( "LOCAL3" ), LOG_LOCAL3 },
171                 { BER_BVC( "LOCAL4" ), LOG_LOCAL4 },
172                 { BER_BVC( "LOCAL5" ), LOG_LOCAL5 },
173                 { BER_BVC( "LOCAL6" ), LOG_LOCAL6 },
174                 { BER_BVC( "LOCAL7" ), LOG_LOCAL7 },
175 #ifdef LOG_USER
176                 { BER_BVC( "USER" ), LOG_USER },
177 #endif /* LOG_USER */
178 #ifdef LOG_DAEMON
179                 { BER_BVC( "DAEMON" ), LOG_DAEMON },
180 #endif /* LOG_DAEMON */
181                 { BER_BVNULL, 0 }
182         };
183         int i = verb_to_mask( arg, syslogUsers );
184
185         if ( BER_BVISNULL( &syslogUsers[ i ].word ) ) {
186                 Debug( LDAP_DEBUG_ANY,
187                         "unrecognized syslog user \"%s\".\n",
188                         arg, 0, 0 );
189                 return 1;
190         }
191
192         *syslogUser = syslogUsers[ i ].mask;
193
194         return 0;
195 }
196 #endif /* LOG_LOCAL4 */
197
198 int
199 parse_syslog_level( const char *arg, int *levelp )
200 {
201         static slap_verbmasks   str2syslog_level[] = {
202                 { BER_BVC( "EMERG" ),   LOG_EMERG },
203                 { BER_BVC( "ALERT" ),   LOG_ALERT },
204                 { BER_BVC( "CRIT" ),    LOG_CRIT },
205                 { BER_BVC( "ERR" ),     LOG_ERR },
206                 { BER_BVC( "WARNING" ), LOG_WARNING },
207                 { BER_BVC( "NOTICE" ),  LOG_NOTICE },
208                 { BER_BVC( "INFO" ),    LOG_INFO },
209                 { BER_BVC( "DEBUG" ),   LOG_DEBUG },
210                 { BER_BVNULL, 0 }
211         };
212         int i = verb_to_mask( arg, str2syslog_level );
213         if ( BER_BVISNULL( &str2syslog_level[ i ].word ) ) {
214                 Debug( LDAP_DEBUG_ANY,
215                         "unknown syslog level \"%s\".\n",
216                         arg, 0, 0 );
217                 return 1;
218         }
219         
220         *levelp = str2syslog_level[ i ].mask;
221
222         return 0;
223 }
224 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
225
226 int
227 parse_debug_unknowns( char **unknowns, int *levelp )
228 {
229         int i, level, rc = 0;
230
231         for ( i = 0; unknowns[ i ] != NULL; i++ ) {
232                 level = 0;
233                 if ( str2loglevel( unknowns[ i ], &level )) {
234                         fprintf( stderr,
235                                 "unrecognized log level \"%s\"\n", unknowns[ i ] );
236                         rc = 1;
237                 } else {
238                         *levelp |= level;
239                 }
240         }
241         return rc;
242 }
243
244 int
245 parse_debug_level( const char *arg, int *levelp, char ***unknowns )
246 {
247         int     level;
248
249         if ( arg && arg[ 0 ] != '-' && !isdigit( (unsigned char) arg[ 0 ] ) )
250         {
251                 int     i;
252                 char    **levels;
253
254                 levels = ldap_str2charray( arg, "," );
255
256                 for ( i = 0; levels[ i ] != NULL; i++ ) {
257                         level = 0;
258
259                         if ( str2loglevel( levels[ i ], &level ) ) {
260                                 /* remember this for later */
261                                 ldap_charray_add( unknowns, levels[ i ] );
262                                 fprintf( stderr,
263                                         "unrecognized log level \"%s\" (deferred)\n",
264                                         levels[ i ] );
265                         } else {
266                                 *levelp |= level;
267                         }
268                 }
269
270                 ldap_charray_free( levels );
271
272         } else {
273                 if ( lutil_atoix( &level, arg, 0 ) != 0 ) {
274                         fprintf( stderr,
275                                 "unrecognized log level "
276                                 "\"%s\"\n", arg );
277                         return 1;
278                 }
279
280                 if ( level == 0 ) {
281                         *levelp = 0;
282
283                 } else {
284                         *levelp |= level;
285                 }
286         }
287
288         return 0;
289 }
290
291 static void
292 usage( char *name )
293 {
294         fprintf( stderr,
295                 "usage: %s options\n", name );
296         fprintf( stderr,
297                 "\t-4\t\tIPv4 only\n"
298                 "\t-6\t\tIPv6 only\n"
299                 "\t-T {acl|add|auth|cat|dn|index|passwd|test}\n"
300                 "\t\t\tRun in Tool mode\n"
301                 "\t-c cookie\tSync cookie of consumer\n"
302                 "\t-d level\tDebug level" "\n"
303                 "\t-f filename\tConfiguration file\n"
304                 "\t-F dir\tConfiguration directory\n"
305 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
306                 "\t-g group\tGroup (id or name) to run as\n"
307 #endif
308                 "\t-h URLs\t\tList of URLs to serve\n"
309 #ifdef SLAP_DEFAULT_SYSLOG_USER
310                 "\t-l facility\tSyslog facility (default: LOCAL4)\n"
311 #endif
312                 "\t-n serverName\tService name\n"
313                 "\t-o <opt>[=val] generic means to specify options" );
314         if ( !BER_BVISNULL( &option_helpers[0].oh_name ) ) {
315                 int     i;
316
317                 fprintf( stderr, "; supported options:\n" );
318                 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++) {
319                         fprintf( stderr, "\t\t%s\n", option_helpers[i].oh_usage );
320                 }
321         } else {
322                 fprintf( stderr, "\n" );
323         }
324         fprintf( stderr,        
325 #ifdef HAVE_CHROOT
326                 "\t-r directory\tSandbox directory to chroot to\n"
327 #endif
328                 "\t-s level\tSyslog level\n"
329 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
330                 "\t-u user\t\tUser (id or name) to run as\n"
331 #endif
332                 "\t-V\t\tprint version info (-VV only)\n"
333     );
334 }
335
336 #ifdef HAVE_NT_SERVICE_MANAGER
337 void WINAPI ServiceMain( DWORD argc, LPTSTR *argv )
338 #else
339 int main( int argc, char **argv )
340 #endif
341 {
342         int             i, no_detach = 0;
343         int             rc = 1;
344         char *urls = NULL;
345 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
346         char *username = NULL;
347         char *groupname = NULL;
348 #endif
349 #if defined(HAVE_CHROOT)
350         char *sandbox = NULL;
351 #endif
352 #ifdef SLAP_DEFAULT_SYSLOG_USER
353         int syslogUser = SLAP_DEFAULT_SYSLOG_USER;
354 #endif
355         
356         int g_argc = argc;
357         char **g_argv = argv;
358
359         char *configfile = NULL;
360         char *configdir = NULL;
361         char *serverName;
362         int serverMode = SLAP_SERVER_MODE;
363
364         struct sync_cookie *scp = NULL;
365         struct sync_cookie *scp_entry = NULL;
366
367         char **debug_unknowns = NULL;
368         char **syslog_unknowns = NULL;
369
370         char *serverNamePrefix = "";
371         size_t  l;
372
373         int slapd_pid_file_unlink = 0, slapd_args_file_unlink = 0;
374         int firstopt = 1;
375
376 #ifdef CSRIMALLOC
377         FILE *leakfile;
378         if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
379                 leakfile = stderr;
380         }
381 #endif
382
383         slap_sl_mem_init();
384
385         (void) ldap_pvt_thread_initialize();
386
387         serverName = lutil_progname( "slapd", argc, argv );
388
389         if ( strcmp( serverName, "slapd" ) ) {
390                 for (i=0; tools[i].name; i++) {
391                         if ( !strcmp( serverName, tools[i].name ) ) {
392                                 rc = tools[i].func(argc, argv);
393                                 MAIN_RETURN(rc);
394                         }
395                 }
396         }
397
398 #ifdef HAVE_NT_SERVICE_MANAGER
399         {
400                 int *ip;
401                 char *newConfigFile;
402                 char *newConfigDir;
403                 char *newUrls;
404                 char *regService = NULL;
405
406                 if ( is_NT_Service ) {
407                         lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
408                         if ( strcmp(serverName, SERVICE_NAME) )
409                             regService = serverName;
410                 }
411
412                 ip = (int*)lutil_getRegParam( regService, "DebugLevel" );
413                 if ( ip != NULL ) {
414                         slap_debug = *ip;
415                         Debug( LDAP_DEBUG_ANY,
416                                 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
417                 }
418
419                 newUrls = (char *) lutil_getRegParam(regService, "Urls");
420                 if (newUrls) {
421                     if (urls)
422                         ch_free(urls);
423
424                     urls = ch_strdup(newUrls);
425                     Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
426                                 urls, 0, 0);
427                 }
428
429                 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
430                 if ( newConfigFile != NULL ) {
431                         configfile = newConfigFile;
432                         Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
433                 }
434
435                 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
436                 if ( newConfigDir != NULL ) {
437                         configdir = newConfigDir;
438                         Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
439                 }
440         }
441 #endif
442
443         while ( (i = getopt( argc, argv,
444                              "c:d:f:F:h:n:o:s:tT:V"
445 #ifdef LDAP_PF_INET6
446                                 "46"
447 #endif
448 #ifdef HAVE_CHROOT
449                                 "r:"
450 #endif
451 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
452                                 "S:"
453 #ifdef LOG_LOCAL4
454                                 "l:"
455 #endif
456 #endif
457 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
458                                 "u:g:"
459 #endif
460                              )) != EOF ) {
461                 switch ( i ) {
462 #ifdef LDAP_PF_INET6
463                 case '4':
464                         slap_inet4or6 = AF_INET;
465                         break;
466                 case '6':
467                         slap_inet4or6 = AF_INET6;
468                         break;
469 #endif
470
471                 case 'h':       /* listen URLs */
472                         if ( urls != NULL ) free( urls );
473                         urls = ch_strdup( optarg );
474                         break;
475
476                 case 'c':       /* provide sync cookie, override if exist in replica */
477                         scp = (struct sync_cookie *) ch_calloc( 1,
478                                                                                 sizeof( struct sync_cookie ));
479                         ber_str2bv( optarg, 0, 1, &scp->octet_str );
480                         
481                         /* This only parses out the rid at this point */
482                         slap_parse_sync_cookie( scp, NULL );
483
484                         if ( scp->rid == -1 ) {
485                                 Debug( LDAP_DEBUG_ANY,
486                                                 "main: invalid cookie \"%s\"\n",
487                                                 optarg, 0, 0 );
488                                 slap_sync_cookie_free( scp, 1 );
489                                 goto destroy;
490                         }
491
492                         LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
493                                 if ( scp->rid == scp_entry->rid ) {
494                                         Debug( LDAP_DEBUG_ANY,
495                                                     "main: duplicated replica id in cookies\n",
496                                                         0, 0, 0 );
497                                         slap_sync_cookie_free( scp, 1 );
498                                         goto destroy;
499                                 }
500                         }
501                         LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
502                         break;
503
504                 case 'd': {     /* set debug level and 'do not detach' flag */
505                         int     level = 0;
506
507                         if ( strcmp( optarg, "?" ) == 0 ) {
508                                 check |= CHECK_LOGLEVEL;
509                                 break;
510                         }
511
512                         no_detach = 1;
513                         if ( parse_debug_level( optarg, &level, &debug_unknowns ) ) {
514                                 goto destroy;
515                         }
516 #ifdef LDAP_DEBUG
517                         slap_debug |= level;
518 #else
519                         if ( level != 0 )
520                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
521                                        stderr );
522 #endif
523                         } break;
524
525                 case 'f':       /* read config file */
526                         configfile = ch_strdup( optarg );
527                         break;
528
529                 case 'F':       /* use config dir */
530                         configdir = ch_strdup( optarg );
531                         break;
532
533                 case 'o': {
534                         char            *val = strchr( optarg, '=' );
535                         struct berval   opt;
536
537                         opt.bv_val = optarg;
538                         
539                         if ( val ) {
540                                 opt.bv_len = ( val - optarg );
541                                 val++;
542                         
543                         } else {
544                                 opt.bv_len = strlen( optarg );
545                         }
546
547                         for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
548                                 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
549                                         assert( option_helpers[i].oh_fnc != NULL );
550                                         if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
551                                                 /* we assume the option parsing helper
552                                                  * issues appropriate and self-explanatory
553                                                  * error messages... */
554                                                 goto stop;
555                                         }
556                                         break;
557                                 }
558                         }
559
560                         if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
561                                 goto unhandled_option;
562                         }
563                         break;
564                 }
565
566                 case 's':       /* set syslog level */
567                         if ( strcmp( optarg, "?" ) == 0 ) {
568                                 check |= CHECK_LOGLEVEL;
569                                 break;
570                         }
571
572                         if ( parse_debug_level( optarg, &ldap_syslog, &syslog_unknowns ) ) {
573                                 goto destroy;
574                         }
575                         break;
576
577 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
578                 case 'S':
579                         if ( parse_syslog_level( optarg, &ldap_syslog_level ) ) {
580                                 goto destroy;
581                         }
582                         break;
583
584 #ifdef LOG_LOCAL4
585                 case 'l':       /* set syslog local user */
586                         if ( parse_syslog_user( optarg, &syslogUser ) ) {
587                                 goto destroy;
588                         }
589                         break;
590 #endif
591 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
592
593 #ifdef HAVE_CHROOT
594                 case 'r':
595                         if( sandbox ) free(sandbox);
596                         sandbox = ch_strdup( optarg );
597                         break;
598 #endif
599
600 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
601                 case 'u':       /* user name */
602                         if( username ) free(username);
603                         username = ch_strdup( optarg );
604                         break;
605
606                 case 'g':       /* group name */
607                         if( groupname ) free(groupname);
608                         groupname = ch_strdup( optarg );
609                         break;
610 #endif /* SETUID && GETUID */
611
612                 case 'n':  /* NT service name */
613                         serverName = ch_strdup( optarg );
614                         break;
615
616                 case 't':
617                         /* deprecated; use slaptest instead */
618                         fprintf( stderr, "option -t deprecated; "
619                                 "use slaptest command instead\n" );
620                         check |= CHECK_CONFIG;
621                         break;
622
623                 case 'V':
624                         version++;
625                         break;
626
627                 case 'T':
628                         if ( firstopt == 0 ) {
629                                 fprintf( stderr, "warning: \"-T %s\" "
630                                         "should be the first option.\n",
631                                         optarg );
632                         }
633
634                         /* try full option string first */
635                         for ( i = 0; tools[i].name; i++ ) {
636                                 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
637                                         rc = tools[i].func( argc, argv );
638                                         MAIN_RETURN( rc );
639                                 }
640                         }
641
642                         /* try bits of option string (backward compatibility for single char) */
643                         l = strlen( optarg );
644                         for ( i = 0; tools[i].name; i++ ) {
645                                 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
646                                         rc = tools[i].func( argc, argv );
647                                         MAIN_RETURN( rc );
648                                 }
649                         }
650                         
651                         /* issue error */
652                         serverName = optarg;
653                         serverNamePrefix = "slap";
654                         fprintf( stderr, "program name \"%s%s\" unrecognized; "
655                                         "aborting...\n", serverNamePrefix, serverName );
656                         /* FALLTHRU */
657                 default:
658 unhandled_option:;
659                         usage( argv[0] );
660                         rc = 1;
661                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
662                         goto stop;
663                 }
664
665                 if ( firstopt ) {
666                         firstopt = 0;
667                 }
668         }
669
670         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
671         ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
672         ldif_debug = slap_debug;
673
674         if ( version ) {
675                 fprintf( stderr, "%s\n", Versionstr );
676                 if ( version > 1 ) goto stop;
677         }
678
679 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
680         {
681                 char *logName;
682 #ifdef HAVE_EBCDIC
683                 logName = ch_strdup( serverName );
684                 __atoe( logName );
685 #else
686                 logName = serverName;
687 #endif
688
689 #ifdef LOG_LOCAL4
690                 openlog( logName, OPENLOG_OPTIONS, syslogUser );
691 #elif defined LOG_DEBUG
692                 openlog( logName, OPENLOG_OPTIONS );
693 #endif
694 #ifdef HAVE_EBCDIC
695                 free( logName );
696 #endif
697         }
698 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
699
700         Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
701
702         global_host = ldap_pvt_get_fqdn( NULL );
703         ber_str2bv( global_host, 0, 0, &global_host_bv );
704
705         if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
706                 rc = 1;
707                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
708                 goto stop;
709         }
710
711 #if defined(HAVE_CHROOT)
712         if ( sandbox ) {
713                 if ( chdir( sandbox ) ) {
714                         perror("chdir");
715                         rc = 1;
716                         goto stop;
717                 }
718                 if ( chroot( sandbox ) ) {
719                         perror("chroot");
720                         rc = 1;
721                         goto stop;
722                 }
723         }
724 #endif
725
726 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
727         if ( username != NULL || groupname != NULL ) {
728                 slap_init_user( username, groupname );
729         }
730 #endif
731
732         extops_init();
733         lutil_passwd_init();
734
735 #ifdef HAVE_TLS
736         rc = ldap_create( &slap_tls_ld );
737         if ( rc ) {
738                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
739                 goto destroy;
740         }
741         /* Library defaults to full certificate checking. This is correct when
742          * a client is verifying a server because all servers should have a
743          * valid cert. But few clients have valid certs, so we want our default
744          * to be no checking. The config file can override this as usual.
745          */
746         rc = LDAP_OPT_X_TLS_NEVER;
747         (void) ldap_pvt_tls_set_option( slap_tls_ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &rc );
748 #endif
749
750         rc = slap_init( serverMode, serverName );
751         if ( rc ) {
752                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
753                 goto destroy;
754         }
755
756         if ( read_config( configfile, configdir ) != 0 ) {
757                 rc = 1;
758                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
759
760                 if ( check & CHECK_CONFIG ) {
761                         fprintf( stderr, "config check failed\n" );
762                 }
763
764                 goto destroy;
765         }
766
767         if ( debug_unknowns ) {
768                 rc = parse_debug_unknowns( debug_unknowns, &slap_debug );
769                 ldap_charray_free( debug_unknowns );
770                 debug_unknowns = NULL;
771                 if ( rc )
772                         goto destroy;
773         }
774         if ( syslog_unknowns ) {
775                 rc = parse_debug_unknowns( syslog_unknowns, &ldap_syslog );
776                 ldap_charray_free( syslog_unknowns );
777                 syslog_unknowns = NULL;
778                 if ( rc )
779                         goto destroy;
780         }       
781
782         if ( check & CHECK_LOGLEVEL ) {
783                 rc = 0;
784                 goto destroy;
785         }
786
787         if ( check & CHECK_CONFIG ) {
788                 fprintf( stderr, "config check succeeded\n" );
789
790                 check &= ~CHECK_CONFIG;
791                 if ( check == CHECK_NONE ) {
792                         rc = 0;
793                         goto destroy;
794                 }
795         }
796
797         if ( glue_sub_attach( 0 ) != 0 ) {
798                 Debug( LDAP_DEBUG_ANY,
799                     "subordinate config error\n",
800                     0, 0, 0 );
801
802                 goto destroy;
803         }
804
805         if ( slap_schema_check( ) != 0 ) {
806                 Debug( LDAP_DEBUG_ANY,
807                     "schema prep error\n",
808                     0, 0, 0 );
809
810                 goto destroy;
811         }
812
813 #ifdef HAVE_TLS
814         rc = ldap_pvt_tls_init();
815         if( rc != 0) {
816                 Debug( LDAP_DEBUG_ANY,
817                     "main: TLS init failed: %d\n",
818                     0, 0, 0 );
819                 rc = 1;
820                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
821                 goto destroy;
822         }
823
824         {
825                 int opt = 1;
826
827                 /* Force new ctx to be created */
828                 rc = ldap_pvt_tls_set_option( slap_tls_ld, LDAP_OPT_X_TLS_NEWCTX, &opt );
829                 if( rc == 0 ) {
830                         /* The ctx's refcount is bumped up here */
831                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
832                         load_extop( &slap_EXOP_START_TLS, 0, starttls_extop );
833                 } else if ( rc != LDAP_NOT_SUPPORTED ) {
834                         Debug( LDAP_DEBUG_ANY,
835                             "main: TLS init def ctx failed: %d\n",
836                             rc, 0, 0 );
837                         rc = 1;
838                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
839                         goto destroy;
840                 }
841         }
842 #endif
843
844 #ifdef HAVE_CYRUS_SASL
845         if( sasl_host == NULL ) {
846                 sasl_host = ch_strdup( global_host );
847         }
848 #endif
849
850         (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
851         (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
852
853 #ifdef SIGPIPE
854         (void) SIGNAL( SIGPIPE, SIG_IGN );
855 #endif
856 #ifdef SIGHUP
857         (void) SIGNAL( SIGHUP, slap_sig_shutdown );
858 #endif
859         (void) SIGNAL( SIGINT, slap_sig_shutdown );
860         (void) SIGNAL( SIGTERM, slap_sig_shutdown );
861 #ifdef SIGTRAP
862         (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
863 #endif
864 #ifdef LDAP_SIGCHLD
865         (void) SIGNAL( LDAP_SIGCHLD, wait4child );
866 #endif
867 #ifdef SIGBREAK
868         /* SIGBREAK is generated when Ctrl-Break is pressed. */
869         (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
870 #endif
871
872 #ifndef HAVE_WINSOCK
873         lutil_detach( no_detach, 0 );
874 #endif /* HAVE_WINSOCK */
875
876 #ifdef CSRIMALLOC
877         mal_leaktrace(1);
878 #endif
879
880         if ( slapd_pid_file != NULL ) {
881                 FILE *fp = fopen( slapd_pid_file, "w" );
882
883                 if ( fp == NULL ) {
884                         int save_errno = errno;
885
886                         Debug( LDAP_DEBUG_ANY, "unable to open pid file "
887                                 "\"%s\": %d (%s)\n",
888                                 slapd_pid_file,
889                                 save_errno, strerror( save_errno ) );
890
891                         free( slapd_pid_file );
892                         slapd_pid_file = NULL;
893
894                         rc = 1;
895                         goto destroy;
896                 }
897                 fprintf( fp, "%d\n", (int) getpid() );
898                 fclose( fp );
899                 slapd_pid_file_unlink = 1;
900         }
901
902         if ( slapd_args_file != NULL ) {
903                 FILE *fp = fopen( slapd_args_file, "w" );
904
905                 if ( fp == NULL ) {
906                         int save_errno = errno;
907
908                         Debug( LDAP_DEBUG_ANY, "unable to open args file "
909                                 "\"%s\": %d (%s)\n",
910                                 slapd_args_file,
911                                 save_errno, strerror( save_errno ) );
912
913                         free( slapd_args_file );
914                         slapd_args_file = NULL;
915
916                         rc = 1;
917                         goto destroy;
918                 }
919
920                 for ( i = 0; i < g_argc; i++ ) {
921                         fprintf( fp, "%s ", g_argv[i] );
922                 }
923                 fprintf( fp, "\n" );
924                 fclose( fp );
925                 slapd_args_file_unlink = 1;
926         }
927
928         /*
929          * FIXME: moved here from slapd_daemon_task()
930          * because back-monitor db_open() needs it
931          */
932         time( &starttime );
933
934         connections_init();
935
936         if ( slap_startup( NULL ) != 0 ) {
937                 rc = 1;
938                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
939                 goto shutdown;
940         }
941
942         Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
943
944 #ifdef HAVE_NT_EVENT_LOG
945         if (is_NT_Service)
946         lutil_LogStartedEvent( serverName, slap_debug, configfile ?
947                 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
948 #endif
949
950         rc = slapd_daemon();
951
952 #ifdef HAVE_NT_SERVICE_MANAGER
953         /* Throw away the event that we used during the startup process. */
954         if ( is_NT_Service )
955                 ldap_pvt_thread_cond_destroy( &started_event );
956 #endif
957
958 shutdown:
959         /* remember an error during shutdown */
960         rc |= slap_shutdown( NULL );
961
962 destroy:
963         if ( check & CHECK_LOGLEVEL ) {
964                 (void)loglevel_print( stdout );
965         }
966         /* remember an error during destroy */
967         rc |= slap_destroy();
968
969         while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
970                 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
971                 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
972                 ch_free( scp );
973         }
974
975 #ifdef SLAPD_MODULES
976         module_kill();
977 #endif
978
979         extops_kill();
980
981         supported_feature_destroy();
982         entry_info_destroy();
983
984 stop:
985 #ifdef HAVE_NT_EVENT_LOG
986         if (is_NT_Service)
987         lutil_LogStoppedEvent( serverName );
988 #endif
989
990         Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
991
992
993 #ifdef HAVE_NT_SERVICE_MANAGER
994         lutil_ReportShutdownComplete();
995 #endif
996
997 #ifdef LOG_DEBUG
998     closelog();
999 #endif
1000         slapd_daemon_destroy();
1001
1002         controls_destroy();
1003
1004         filter_destroy();
1005
1006         schema_destroy();
1007
1008         lutil_passwd_destroy();
1009
1010 #ifdef HAVE_TLS
1011         if ( slap_tls_ld ) {
1012                 ldap_pvt_tls_ctx_free( slap_tls_ctx );
1013                 ldap_unbind_ext( slap_tls_ld, NULL, NULL );
1014         }
1015         ldap_pvt_tls_destroy();
1016 #endif
1017
1018         slap_sasl_regexp_destroy();
1019
1020         if ( slapd_pid_file_unlink ) {
1021                 unlink( slapd_pid_file );
1022         }
1023         if ( slapd_args_file_unlink ) {
1024                 unlink( slapd_args_file );
1025         }
1026
1027         config_destroy();
1028
1029         if ( configfile )
1030                 ch_free( configfile );
1031         if ( configdir )
1032                 ch_free( configdir );
1033         if ( urls )
1034                 ch_free( urls );
1035         if ( global_host )
1036                 ch_free( global_host );
1037
1038         /* kludge, get symbols referenced */
1039         tavl_free( NULL, NULL );
1040
1041 #ifdef CSRIMALLOC
1042         mal_dumpleaktrace( leakfile );
1043 #endif
1044
1045         MAIN_RETURN(rc);
1046 }
1047
1048
1049 #ifdef LDAP_SIGCHLD
1050
1051 /*
1052  *  Catch and discard terminated child processes, to avoid zombies.
1053  */
1054
1055 static RETSIGTYPE
1056 wait4child( int sig )
1057 {
1058     int save_errno = errno;
1059
1060 #ifdef WNOHANG
1061     do
1062         errno = 0;
1063 #ifdef HAVE_WAITPID
1064     while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR );
1065 #else
1066     while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR );
1067 #endif
1068 #else
1069     (void) wait( NULL );
1070 #endif
1071     (void) SIGNAL_REINSTALL( sig, wait4child );
1072     errno = save_errno;
1073 }
1074
1075 #endif /* LDAP_SIGCHLD */