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