]> git.sur5r.net Git - openldap/blob - servers/slapd/main.c
ITS#6324
[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                 int rc;
274
275                 if ( arg[0] == '-' ) {
276                         rc = lutil_atoix( &level, arg, 0 );
277                 } else {
278                         unsigned ulevel;
279
280                         rc = lutil_atoux( &ulevel, arg, 0 );
281                         level = (int)ulevel;
282                 }
283
284                 if ( rc ) {
285                         fprintf( stderr,
286                                 "unrecognized log level "
287                                 "\"%s\"\n", arg );
288                         return 1;
289                 }
290
291                 if ( level == 0 ) {
292                         *levelp = 0;
293
294                 } else {
295                         *levelp |= level;
296                 }
297         }
298
299         return 0;
300 }
301
302 static void
303 usage( char *name )
304 {
305         fprintf( stderr,
306                 "usage: %s options\n", name );
307         fprintf( stderr,
308                 "\t-4\t\tIPv4 only\n"
309                 "\t-6\t\tIPv6 only\n"
310                 "\t-T {acl|add|auth|cat|dn|index|passwd|test}\n"
311                 "\t\t\tRun in Tool mode\n"
312                 "\t-c cookie\tSync cookie of consumer\n"
313                 "\t-d level\tDebug level" "\n"
314                 "\t-f filename\tConfiguration file\n"
315                 "\t-F dir\tConfiguration directory\n"
316 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
317                 "\t-g group\tGroup (id or name) to run as\n"
318 #endif
319                 "\t-h URLs\t\tList of URLs to serve\n"
320 #ifdef SLAP_DEFAULT_SYSLOG_USER
321                 "\t-l facility\tSyslog facility (default: LOCAL4)\n"
322 #endif
323                 "\t-n serverName\tService name\n"
324                 "\t-o <opt>[=val] generic means to specify options" );
325         if ( !BER_BVISNULL( &option_helpers[0].oh_name ) ) {
326                 int     i;
327
328                 fprintf( stderr, "; supported options:\n" );
329                 for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++) {
330                         fprintf( stderr, "\t\t%s\n", option_helpers[i].oh_usage );
331                 }
332         } else {
333                 fprintf( stderr, "\n" );
334         }
335         fprintf( stderr,        
336 #ifdef HAVE_CHROOT
337                 "\t-r directory\tSandbox directory to chroot to\n"
338 #endif
339                 "\t-s level\tSyslog level\n"
340 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
341                 "\t-u user\t\tUser (id or name) to run as\n"
342 #endif
343                 "\t-V\t\tprint version info (-VV only)\n"
344     );
345 }
346
347 #ifdef HAVE_NT_SERVICE_MANAGER
348 void WINAPI ServiceMain( DWORD argc, LPTSTR *argv )
349 #else
350 int main( int argc, char **argv )
351 #endif
352 {
353         int             i, no_detach = 0;
354         int             rc = 1;
355         char *urls = NULL;
356 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
357         char *username = NULL;
358         char *groupname = NULL;
359 #endif
360 #if defined(HAVE_CHROOT)
361         char *sandbox = NULL;
362 #endif
363 #ifdef SLAP_DEFAULT_SYSLOG_USER
364         int syslogUser = SLAP_DEFAULT_SYSLOG_USER;
365 #endif
366         
367         int g_argc = argc;
368         char **g_argv = argv;
369
370         char *configfile = NULL;
371         char *configdir = NULL;
372         char *serverName;
373         int serverMode = SLAP_SERVER_MODE;
374
375         struct sync_cookie *scp = NULL;
376         struct sync_cookie *scp_entry = NULL;
377
378         char **debug_unknowns = NULL;
379         char **syslog_unknowns = NULL;
380
381         char *serverNamePrefix = "";
382         size_t  l;
383
384         int slapd_pid_file_unlink = 0, slapd_args_file_unlink = 0;
385         int firstopt = 1;
386
387 #ifdef CSRIMALLOC
388         FILE *leakfile;
389         if( ( leakfile = fopen( "slapd.leak", "w" )) == NULL ) {
390                 leakfile = stderr;
391         }
392 #endif
393
394         slap_sl_mem_init();
395
396         (void) ldap_pvt_thread_initialize();
397
398         serverName = lutil_progname( "slapd", argc, argv );
399
400         if ( strcmp( serverName, "slapd" ) ) {
401                 for (i=0; tools[i].name; i++) {
402                         if ( !strcmp( serverName, tools[i].name ) ) {
403                                 rc = tools[i].func(argc, argv);
404                                 MAIN_RETURN(rc);
405                         }
406                 }
407         }
408
409 #ifdef HAVE_NT_SERVICE_MANAGER
410         {
411                 int *ip;
412                 char *newConfigFile;
413                 char *newConfigDir;
414                 char *newUrls;
415                 char *regService = NULL;
416
417                 if ( is_NT_Service ) {
418                         lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
419                         if ( strcmp(serverName, SERVICE_NAME) )
420                             regService = serverName;
421                 }
422
423                 ip = (int*)lutil_getRegParam( regService, "DebugLevel" );
424                 if ( ip != NULL ) {
425                         slap_debug = *ip;
426                         Debug( LDAP_DEBUG_ANY,
427                                 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
428                 }
429
430                 newUrls = (char *) lutil_getRegParam(regService, "Urls");
431                 if (newUrls) {
432                     if (urls)
433                         ch_free(urls);
434
435                     urls = ch_strdup(newUrls);
436                     Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
437                                 urls, 0, 0);
438                 }
439
440                 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
441                 if ( newConfigFile != NULL ) {
442                         configfile = newConfigFile;
443                         Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
444                 }
445
446                 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
447                 if ( newConfigDir != NULL ) {
448                         configdir = newConfigDir;
449                         Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
450                 }
451         }
452 #endif
453
454         while ( (i = getopt( argc, argv,
455                              "c:d:f:F:h:n:o:s:tT:V"
456 #ifdef LDAP_PF_INET6
457                                 "46"
458 #endif
459 #ifdef HAVE_CHROOT
460                                 "r:"
461 #endif
462 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
463                                 "S:"
464 #ifdef LOG_LOCAL4
465                                 "l:"
466 #endif
467 #endif
468 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
469                                 "u:g:"
470 #endif
471                              )) != EOF ) {
472                 switch ( i ) {
473 #ifdef LDAP_PF_INET6
474                 case '4':
475                         slap_inet4or6 = AF_INET;
476                         break;
477                 case '6':
478                         slap_inet4or6 = AF_INET6;
479                         break;
480 #endif
481
482                 case 'h':       /* listen URLs */
483                         if ( urls != NULL ) free( urls );
484                         urls = ch_strdup( optarg );
485                         break;
486
487                 case 'c':       /* provide sync cookie, override if exist in replica */
488                         scp = (struct sync_cookie *) ch_calloc( 1,
489                                                                                 sizeof( struct sync_cookie ));
490                         ber_str2bv( optarg, 0, 1, &scp->octet_str );
491                         
492                         /* This only parses out the rid at this point */
493                         slap_parse_sync_cookie( scp, NULL );
494
495                         if ( scp->rid == -1 ) {
496                                 Debug( LDAP_DEBUG_ANY,
497                                                 "main: invalid cookie \"%s\"\n",
498                                                 optarg, 0, 0 );
499                                 slap_sync_cookie_free( scp, 1 );
500                                 goto destroy;
501                         }
502
503                         LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
504                                 if ( scp->rid == scp_entry->rid ) {
505                                         Debug( LDAP_DEBUG_ANY,
506                                                     "main: duplicated replica id in cookies\n",
507                                                         0, 0, 0 );
508                                         slap_sync_cookie_free( scp, 1 );
509                                         goto destroy;
510                                 }
511                         }
512                         LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
513                         break;
514
515                 case 'd': {     /* set debug level and 'do not detach' flag */
516                         int     level = 0;
517
518                         if ( strcmp( optarg, "?" ) == 0 ) {
519                                 check |= CHECK_LOGLEVEL;
520                                 break;
521                         }
522
523                         no_detach = 1;
524                         if ( parse_debug_level( optarg, &level, &debug_unknowns ) ) {
525                                 goto destroy;
526                         }
527 #ifdef LDAP_DEBUG
528                         slap_debug |= level;
529 #else
530                         if ( level != 0 )
531                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
532                                        stderr );
533 #endif
534                         } break;
535
536                 case 'f':       /* read config file */
537                         configfile = ch_strdup( optarg );
538                         break;
539
540                 case 'F':       /* use config dir */
541                         configdir = ch_strdup( optarg );
542                         break;
543
544                 case 'o': {
545                         char            *val = strchr( optarg, '=' );
546                         struct berval   opt;
547
548                         opt.bv_val = optarg;
549                         
550                         if ( val ) {
551                                 opt.bv_len = ( val - optarg );
552                                 val++;
553                         
554                         } else {
555                                 opt.bv_len = strlen( optarg );
556                         }
557
558                         for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
559                                 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
560                                         assert( option_helpers[i].oh_fnc != NULL );
561                                         if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
562                                                 /* we assume the option parsing helper
563                                                  * issues appropriate and self-explanatory
564                                                  * error messages... */
565                                                 goto stop;
566                                         }
567                                         break;
568                                 }
569                         }
570
571                         if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
572                                 goto unhandled_option;
573                         }
574                         break;
575                 }
576
577                 case 's':       /* set syslog level */
578                         if ( strcmp( optarg, "?" ) == 0 ) {
579                                 check |= CHECK_LOGLEVEL;
580                                 break;
581                         }
582
583                         if ( parse_debug_level( optarg, &ldap_syslog, &syslog_unknowns ) ) {
584                                 goto destroy;
585                         }
586                         break;
587
588 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
589                 case 'S':
590                         if ( parse_syslog_level( optarg, &ldap_syslog_level ) ) {
591                                 goto destroy;
592                         }
593                         break;
594
595 #ifdef LOG_LOCAL4
596                 case 'l':       /* set syslog local user */
597                         if ( parse_syslog_user( optarg, &syslogUser ) ) {
598                                 goto destroy;
599                         }
600                         break;
601 #endif
602 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
603
604 #ifdef HAVE_CHROOT
605                 case 'r':
606                         if( sandbox ) free(sandbox);
607                         sandbox = ch_strdup( optarg );
608                         break;
609 #endif
610
611 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
612                 case 'u':       /* user name */
613                         if( username ) free(username);
614                         username = ch_strdup( optarg );
615                         break;
616
617                 case 'g':       /* group name */
618                         if( groupname ) free(groupname);
619                         groupname = ch_strdup( optarg );
620                         break;
621 #endif /* SETUID && GETUID */
622
623                 case 'n':  /* NT service name */
624                         serverName = ch_strdup( optarg );
625                         break;
626
627                 case 't':
628                         /* deprecated; use slaptest instead */
629                         fprintf( stderr, "option -t deprecated; "
630                                 "use slaptest command instead\n" );
631                         check |= CHECK_CONFIG;
632                         break;
633
634                 case 'V':
635                         version++;
636                         break;
637
638                 case 'T':
639                         if ( firstopt == 0 ) {
640                                 fprintf( stderr, "warning: \"-T %s\" "
641                                         "should be the first option.\n",
642                                         optarg );
643                         }
644
645                         /* try full option string first */
646                         for ( i = 0; tools[i].name; i++ ) {
647                                 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
648                                         rc = tools[i].func( argc, argv );
649                                         MAIN_RETURN( rc );
650                                 }
651                         }
652
653                         /* try bits of option string (backward compatibility for single char) */
654                         l = strlen( optarg );
655                         for ( i = 0; tools[i].name; i++ ) {
656                                 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
657                                         rc = tools[i].func( argc, argv );
658                                         MAIN_RETURN( rc );
659                                 }
660                         }
661                         
662                         /* issue error */
663                         serverName = optarg;
664                         serverNamePrefix = "slap";
665                         fprintf( stderr, "program name \"%s%s\" unrecognized; "
666                                         "aborting...\n", serverNamePrefix, serverName );
667                         /* FALLTHRU */
668                 default:
669 unhandled_option:;
670                         usage( argv[0] );
671                         rc = 1;
672                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
673                         goto stop;
674                 }
675
676                 if ( firstopt ) {
677                         firstopt = 0;
678                 }
679         }
680
681         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
682         ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
683         ldif_debug = slap_debug;
684
685         if ( version ) {
686                 fprintf( stderr, "%s\n", Versionstr );
687                 if ( version > 1 ) goto stop;
688         }
689
690 #if defined(LDAP_DEBUG) && defined(LDAP_SYSLOG)
691         {
692                 char *logName;
693 #ifdef HAVE_EBCDIC
694                 logName = ch_strdup( serverName );
695                 __atoe( logName );
696 #else
697                 logName = serverName;
698 #endif
699
700 #ifdef LOG_LOCAL4
701                 openlog( logName, OPENLOG_OPTIONS, syslogUser );
702 #elif defined LOG_DEBUG
703                 openlog( logName, OPENLOG_OPTIONS );
704 #endif
705 #ifdef HAVE_EBCDIC
706                 free( logName );
707 #endif
708         }
709 #endif /* LDAP_DEBUG && LDAP_SYSLOG */
710
711         Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
712
713         global_host = ldap_pvt_get_fqdn( NULL );
714         ber_str2bv( global_host, 0, 0, &global_host_bv );
715
716         if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
717                 rc = 1;
718                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
719                 goto stop;
720         }
721
722 #if defined(HAVE_CHROOT)
723         if ( sandbox ) {
724                 if ( chdir( sandbox ) ) {
725                         perror("chdir");
726                         rc = 1;
727                         goto stop;
728                 }
729                 if ( chroot( sandbox ) ) {
730                         perror("chroot");
731                         rc = 1;
732                         goto stop;
733                 }
734         }
735 #endif
736
737 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
738         if ( username != NULL || groupname != NULL ) {
739                 slap_init_user( username, groupname );
740         }
741 #endif
742
743         extops_init();
744         lutil_passwd_init();
745
746 #ifdef HAVE_TLS
747         rc = ldap_create( &slap_tls_ld );
748         if ( rc ) {
749                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
750                 goto destroy;
751         }
752         /* Library defaults to full certificate checking. This is correct when
753          * a client is verifying a server because all servers should have a
754          * valid cert. But few clients have valid certs, so we want our default
755          * to be no checking. The config file can override this as usual.
756          */
757         rc = LDAP_OPT_X_TLS_NEVER;
758         (void) ldap_pvt_tls_set_option( slap_tls_ld, LDAP_OPT_X_TLS_REQUIRE_CERT, &rc );
759 #endif
760
761         rc = slap_init( serverMode, serverName );
762         if ( rc ) {
763                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
764                 goto destroy;
765         }
766
767         if ( read_config( configfile, configdir ) != 0 ) {
768                 rc = 1;
769                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
770
771                 if ( check & CHECK_CONFIG ) {
772                         fprintf( stderr, "config check failed\n" );
773                 }
774
775                 goto destroy;
776         }
777
778         if ( debug_unknowns ) {
779                 rc = parse_debug_unknowns( debug_unknowns, &slap_debug );
780                 ldap_charray_free( debug_unknowns );
781                 debug_unknowns = NULL;
782                 if ( rc )
783                         goto destroy;
784         }
785         if ( syslog_unknowns ) {
786                 rc = parse_debug_unknowns( syslog_unknowns, &ldap_syslog );
787                 ldap_charray_free( syslog_unknowns );
788                 syslog_unknowns = NULL;
789                 if ( rc )
790                         goto destroy;
791         }       
792
793         if ( check & CHECK_LOGLEVEL ) {
794                 rc = 0;
795                 goto destroy;
796         }
797
798         if ( check & CHECK_CONFIG ) {
799                 fprintf( stderr, "config check succeeded\n" );
800
801                 check &= ~CHECK_CONFIG;
802                 if ( check == CHECK_NONE ) {
803                         rc = 0;
804                         goto destroy;
805                 }
806         }
807
808         if ( glue_sub_attach( 0 ) != 0 ) {
809                 Debug( LDAP_DEBUG_ANY,
810                     "subordinate config error\n",
811                     0, 0, 0 );
812
813                 goto destroy;
814         }
815
816         if ( slap_schema_check( ) != 0 ) {
817                 Debug( LDAP_DEBUG_ANY,
818                     "schema prep error\n",
819                     0, 0, 0 );
820
821                 goto destroy;
822         }
823
824 #ifdef HAVE_TLS
825         rc = ldap_pvt_tls_init();
826         if( rc != 0) {
827                 Debug( LDAP_DEBUG_ANY,
828                     "main: TLS init failed: %d\n",
829                     0, 0, 0 );
830                 rc = 1;
831                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
832                 goto destroy;
833         }
834
835         {
836                 int opt = 1;
837
838                 /* Force new ctx to be created */
839                 rc = ldap_pvt_tls_set_option( slap_tls_ld, LDAP_OPT_X_TLS_NEWCTX, &opt );
840                 if( rc == 0 ) {
841                         /* The ctx's refcount is bumped up here */
842                         ldap_pvt_tls_get_option( slap_tls_ld, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
843                         load_extop( &slap_EXOP_START_TLS, 0, starttls_extop );
844                 } else if ( rc != LDAP_NOT_SUPPORTED ) {
845                         Debug( LDAP_DEBUG_ANY,
846                             "main: TLS init def ctx failed: %d\n",
847                             rc, 0, 0 );
848                         rc = 1;
849                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
850                         goto destroy;
851                 }
852         }
853 #endif
854
855 #ifdef HAVE_CYRUS_SASL
856         if( sasl_host == NULL ) {
857                 sasl_host = ch_strdup( global_host );
858         }
859 #endif
860
861         (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
862         (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
863
864 #ifdef SIGPIPE
865         (void) SIGNAL( SIGPIPE, SIG_IGN );
866 #endif
867 #ifdef SIGHUP
868         (void) SIGNAL( SIGHUP, slap_sig_shutdown );
869 #endif
870         (void) SIGNAL( SIGINT, slap_sig_shutdown );
871         (void) SIGNAL( SIGTERM, slap_sig_shutdown );
872 #ifdef SIGTRAP
873         (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
874 #endif
875 #ifdef LDAP_SIGCHLD
876         (void) SIGNAL( LDAP_SIGCHLD, wait4child );
877 #endif
878 #ifdef SIGBREAK
879         /* SIGBREAK is generated when Ctrl-Break is pressed. */
880         (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
881 #endif
882
883 #ifndef HAVE_WINSOCK
884         lutil_detach( no_detach, 0 );
885 #endif /* HAVE_WINSOCK */
886
887 #ifdef CSRIMALLOC
888         mal_leaktrace(1);
889 #endif
890
891         if ( slapd_pid_file != NULL ) {
892                 FILE *fp = fopen( slapd_pid_file, "w" );
893
894                 if ( fp == NULL ) {
895                         int save_errno = errno;
896
897                         Debug( LDAP_DEBUG_ANY, "unable to open pid file "
898                                 "\"%s\": %d (%s)\n",
899                                 slapd_pid_file,
900                                 save_errno, strerror( save_errno ) );
901
902                         free( slapd_pid_file );
903                         slapd_pid_file = NULL;
904
905                         rc = 1;
906                         goto destroy;
907                 }
908                 fprintf( fp, "%d\n", (int) getpid() );
909                 fclose( fp );
910                 slapd_pid_file_unlink = 1;
911         }
912
913         if ( slapd_args_file != NULL ) {
914                 FILE *fp = fopen( slapd_args_file, "w" );
915
916                 if ( fp == NULL ) {
917                         int save_errno = errno;
918
919                         Debug( LDAP_DEBUG_ANY, "unable to open args file "
920                                 "\"%s\": %d (%s)\n",
921                                 slapd_args_file,
922                                 save_errno, strerror( save_errno ) );
923
924                         free( slapd_args_file );
925                         slapd_args_file = NULL;
926
927                         rc = 1;
928                         goto destroy;
929                 }
930
931                 for ( i = 0; i < g_argc; i++ ) {
932                         fprintf( fp, "%s ", g_argv[i] );
933                 }
934                 fprintf( fp, "\n" );
935                 fclose( fp );
936                 slapd_args_file_unlink = 1;
937         }
938
939         /*
940          * FIXME: moved here from slapd_daemon_task()
941          * because back-monitor db_open() needs it
942          */
943         time( &starttime );
944
945         connections_init();
946
947         if ( slap_startup( NULL ) != 0 ) {
948                 rc = 1;
949                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
950                 goto shutdown;
951         }
952
953         Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
954
955 #ifdef HAVE_NT_EVENT_LOG
956         if (is_NT_Service)
957         lutil_LogStartedEvent( serverName, slap_debug, configfile ?
958                 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
959 #endif
960
961         rc = slapd_daemon();
962
963 #ifdef HAVE_NT_SERVICE_MANAGER
964         /* Throw away the event that we used during the startup process. */
965         if ( is_NT_Service )
966                 ldap_pvt_thread_cond_destroy( &started_event );
967 #endif
968
969 shutdown:
970         /* remember an error during shutdown */
971         rc |= slap_shutdown( NULL );
972
973 destroy:
974         if ( check & CHECK_LOGLEVEL ) {
975                 (void)loglevel_print( stdout );
976         }
977         /* remember an error during destroy */
978         rc |= slap_destroy();
979
980         while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
981                 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
982                 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
983                 ch_free( scp );
984         }
985
986 #ifdef SLAPD_MODULES
987         module_kill();
988 #endif
989
990         extops_kill();
991
992         supported_feature_destroy();
993         entry_info_destroy();
994
995 stop:
996 #ifdef HAVE_NT_EVENT_LOG
997         if (is_NT_Service)
998         lutil_LogStoppedEvent( serverName );
999 #endif
1000
1001         Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
1002
1003
1004 #ifdef HAVE_NT_SERVICE_MANAGER
1005         lutil_ReportShutdownComplete();
1006 #endif
1007
1008 #ifdef LOG_DEBUG
1009     closelog();
1010 #endif
1011         slapd_daemon_destroy();
1012
1013         controls_destroy();
1014
1015         filter_destroy();
1016
1017         schema_destroy();
1018
1019         lutil_passwd_destroy();
1020
1021 #ifdef HAVE_TLS
1022         if ( slap_tls_ld ) {
1023                 ldap_pvt_tls_ctx_free( slap_tls_ctx );
1024                 ldap_unbind_ext( slap_tls_ld, NULL, NULL );
1025         }
1026         ldap_pvt_tls_destroy();
1027 #endif
1028
1029         slap_sasl_regexp_destroy();
1030
1031         if ( slapd_pid_file_unlink ) {
1032                 unlink( slapd_pid_file );
1033         }
1034         if ( slapd_args_file_unlink ) {
1035                 unlink( slapd_args_file );
1036         }
1037
1038         config_destroy();
1039
1040         if ( configfile )
1041                 ch_free( configfile );
1042         if ( configdir )
1043                 ch_free( configdir );
1044         if ( urls )
1045                 ch_free( urls );
1046         if ( global_host )
1047                 ch_free( global_host );
1048
1049         /* kludge, get symbols referenced */
1050         tavl_free( NULL, NULL );
1051
1052 #ifdef CSRIMALLOC
1053         mal_dumpleaktrace( leakfile );
1054 #endif
1055
1056         MAIN_RETURN(rc);
1057 }
1058
1059
1060 #ifdef LDAP_SIGCHLD
1061
1062 /*
1063  *  Catch and discard terminated child processes, to avoid zombies.
1064  */
1065
1066 static RETSIGTYPE
1067 wait4child( int sig )
1068 {
1069     int save_errno = errno;
1070
1071 #ifdef WNOHANG
1072     do
1073         errno = 0;
1074 #ifdef HAVE_WAITPID
1075     while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR );
1076 #else
1077     while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR );
1078 #endif
1079 #else
1080     (void) wait( NULL );
1081 #endif
1082     (void) SIGNAL_REINSTALL( sig, wait4child );
1083     errno = save_errno;
1084 }
1085
1086 #endif /* LDAP_SIGCHLD */