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