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