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