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