]> git.sur5r.net Git - openldap/blob - servers/slapd/main.c
Merge from HEAD
[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 }
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         serverName = lutil_progname( "slapd", argc, argv );
275
276         if ( strcmp( serverName, "slapd" ) ) {
277                 for (i=0; tools[i].name; i++) {
278                         if ( !strcmp( serverName, tools[i].name ) ) {
279                                 rc = tools[i].func(argc, argv);
280                                 MAIN_RETURN(rc);
281                         }
282                 }
283         }
284
285 #ifdef HAVE_NT_SERVICE_MANAGER
286         {
287                 int *i;
288                 char *newConfigFile;
289                 char *newConfigDir;
290                 char *newUrls;
291                 char *regService = NULL;
292
293                 if ( is_NT_Service ) {
294                         lutil_CommenceStartupProcessing( serverName, slap_sig_shutdown );
295                         if ( strcmp(serverName, SERVICE_NAME) )
296                             regService = serverName;
297                 }
298
299                 i = (int*)lutil_getRegParam( regService, "DebugLevel" );
300                 if ( i != NULL ) {
301                         slap_debug = *i;
302                         Debug( LDAP_DEBUG_ANY,
303                                 "new debug level from registry is: %d\n", slap_debug, 0, 0 );
304                 }
305
306                 newUrls = (char *) lutil_getRegParam(regService, "Urls");
307                 if (newUrls) {
308                     if (urls)
309                         ch_free(urls);
310
311                     urls = ch_strdup(newUrls);
312                     Debug(LDAP_DEBUG_ANY, "new urls from registry: %s\n",
313                                 urls, 0, 0);
314                 }
315
316                 newConfigFile = (char*)lutil_getRegParam( regService, "ConfigFile" );
317                 if ( newConfigFile != NULL ) {
318                         configfile = newConfigFile;
319                         Debug ( LDAP_DEBUG_ANY, "new config file from registry is: %s\n", configfile, 0, 0 );
320                 }
321
322                 newConfigDir = (char*)lutil_getRegParam( regService, "ConfigDir" );
323                 if ( newConfigDir != NULL ) {
324                         configdir = newConfigDir;
325                         Debug ( LDAP_DEBUG_ANY, "new config dir from registry is: %s\n", configdir, 0, 0 );
326                 }
327         }
328 #endif
329
330         while ( (i = getopt( argc, argv,
331                              "c:d:f:F:h:n:o:s:StT:V"
332 #if LDAP_PF_INET6
333                                 "46"
334 #endif
335 #ifdef HAVE_CHROOT
336                                 "r:"
337 #endif
338 #ifdef LOG_LOCAL4
339                              "l:"
340 #endif
341 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
342                              "u:g:"
343 #endif
344                              )) != EOF ) {
345                 switch ( i ) {
346 #ifdef LDAP_PF_INET6
347                 case '4':
348                         slap_inet4or6 = AF_INET;
349                         break;
350                 case '6':
351                         slap_inet4or6 = AF_INET6;
352                         break;
353 #endif
354
355                 case 'h':       /* listen URLs */
356                         if ( urls != NULL ) free( urls );
357                         urls = ch_strdup( optarg );
358                         break;
359
360                 case 'c':       /* provide sync cookie, override if exist in replica */
361                         scp = (struct sync_cookie *) ch_calloc( 1,
362                                                                                 sizeof( struct sync_cookie ));
363                         ber_str2bv( optarg, 0, 1, &scp->octet_str );
364                         slap_parse_sync_cookie( scp );
365
366                         LDAP_STAILQ_FOREACH( scp_entry, &slap_sync_cookie, sc_next ) {
367                                 if ( scp->rid == scp_entry->rid ) {
368                                         Debug( LDAP_DEBUG_ANY,
369                                                     "main: duplicated replica id in cookies\n",
370                                                         0, 0, 0 );
371                                         slap_sync_cookie_free( scp, 1 );
372                                         goto destroy;
373                                 }
374                         }
375                         LDAP_STAILQ_INSERT_TAIL( &slap_sync_cookie, scp, sc_next );
376                         break;
377
378                 case 'd':       /* set debug level and 'do not detach' flag */
379                         no_detach = 1;
380 #ifdef LDAP_DEBUG
381                         slap_debug |= atoi( optarg );
382 #else
383                         if ( atoi( optarg ) != 0 )
384                                 fputs( "must compile with LDAP_DEBUG for debugging\n",
385                                        stderr );
386 #endif
387                         break;
388
389                 case 'f':       /* read config file */
390                         configfile = ch_strdup( optarg );
391                         break;
392
393                 case 'F':       /* use config dir */
394                         configdir = ch_strdup( optarg );
395                         break;
396
397                 case 'o': {
398                         char            *val = strchr( optarg, '=' );
399                         struct berval   opt;
400                         int             i;
401
402                         opt.bv_val = optarg;
403                         
404                         if ( val ) {
405                                 opt.bv_len = ( val - optarg );
406                                 val++;
407                         
408                         } else {
409                                 opt.bv_len = strlen( optarg );
410                         }
411
412                         for ( i = 0; !BER_BVISNULL( &option_helpers[i].oh_name ); i++ ) {
413                                 if ( ber_bvstrcasecmp( &option_helpers[i].oh_name, &opt ) == 0 ) {
414                                         assert( option_helpers[i].oh_fnc != NULL );
415                                         if ( (*option_helpers[i].oh_fnc)( val, option_helpers[i].oh_arg ) == -1 ) {
416                                                 /* we assume the option parsing helper
417                                                  * issues appropriate and self-explanatory
418                                                  * error messages... */
419                                                 goto stop;
420                                         }
421                                         break;
422                                 }
423                         }
424
425                         if ( BER_BVISNULL( &option_helpers[i].oh_name ) ) {
426                                 goto unhandled_option;
427                         }
428                         break;
429                 }
430
431                 case 's':       /* set syslog level */
432                         ldap_syslog = atoi( optarg );
433                         break;
434
435 #ifdef LOG_LOCAL4
436                 case 'l':       /* set syslog local user */
437                         syslogUser = cnvt_str2int( optarg,
438                                 syslog_types, DEFAULT_SYSLOG_USER );
439                         break;
440 #endif
441
442 #ifdef HAVE_CHROOT
443                 case 'r':
444                         if( sandbox ) free(sandbox);
445                         sandbox = ch_strdup( optarg );
446                         break;
447 #endif
448
449 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
450                 case 'u':       /* user name */
451                         if( username ) free(username);
452                         username = ch_strdup( optarg );
453                         break;
454
455                 case 'g':       /* group name */
456                         if( groupname ) free(groupname);
457                         groupname = ch_strdup( optarg );
458                         break;
459 #endif /* SETUID && GETUID */
460
461                 case 'n':  /* NT service name */
462                         serverName = ch_strdup( optarg );
463                         break;
464
465                 case 't':
466                         /* deprecated; use slaptest instead */
467                         fprintf( stderr, "option -t deprecated; "
468                                 "use slaptest command instead\n" );
469                         check |= CHECK_CONFIG;
470                         break;
471
472                 case 'V':
473                         version++;
474                         break;
475
476                 case 'T':
477                         /* try full option string first */
478                         for ( i = 0; tools[i].name; i++ ) {
479                                 if ( strcmp( optarg, &tools[i].name[4] ) == 0 ) {
480                                         rc = tools[i].func( argc, argv );
481                                         MAIN_RETURN( rc );
482                                 }
483                         }
484
485                         /* try bits of option string (backward compatibility for single char) */
486                         l = strlen( optarg );
487                         for ( i = 0; tools[i].name; i++ ) {
488                                 if ( strncmp( optarg, &tools[i].name[4], l ) == 0 ) {
489                                         rc = tools[i].func( argc, argv );
490                                         MAIN_RETURN( rc );
491                                 }
492                         }
493                         
494                         /* issue error */
495                         serverName = optarg;
496                         serverNamePrefix = "slap";
497                         fprintf( stderr, "program name \"%s%s\" unrecognized; "
498                                         "aborting...\n", serverNamePrefix, serverName );
499                         /* FALLTHRU */
500                 default:
501 unhandled_option:;
502                         usage( argv[0] );
503                         rc = 1;
504                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 15 );
505                         goto stop;
506                 }
507         }
508
509         (void) ldap_pvt_thread_initialize();
510
511         ber_set_option(NULL, LBER_OPT_DEBUG_LEVEL, &slap_debug);
512         ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &slap_debug);
513         ldif_debug = slap_debug;
514
515         if ( version ) {
516                 fprintf( stderr, "%s\n", Versionstr );
517                 if ( version > 1 ) goto stop;
518         }
519
520         {
521                 char *logName;
522 #ifdef HAVE_EBCDIC
523                 logName = ch_strdup( serverName );
524                 __atoe( logName );
525 #else
526                 logName = serverName;
527 #endif
528
529 #ifdef LOG_LOCAL4
530                 openlog( logName, OPENLOG_OPTIONS, syslogUser );
531 #elif LOG_DEBUG
532                 openlog( logName, OPENLOG_OPTIONS );
533 #endif
534 #ifdef HAVE_EBCDIC
535                 free( logName );
536 #endif
537         }
538
539         Debug( LDAP_DEBUG_ANY, "%s", Versionstr, 0, 0 );
540
541         if( check == CHECK_NONE && slapd_daemon_init( urls ) != 0 ) {
542                 rc = 1;
543                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 16 );
544                 goto stop;
545         }
546
547 #if defined(HAVE_CHROOT)
548         if ( sandbox ) {
549                 if ( chdir( sandbox ) ) {
550                         perror("chdir");
551                         rc = 1;
552                         goto stop;
553                 }
554                 if ( chroot( sandbox ) ) {
555                         perror("chroot");
556                         rc = 1;
557                         goto stop;
558                 }
559         }
560 #endif
561
562 #if defined(HAVE_SETUID) && defined(HAVE_SETGID)
563         if ( username != NULL || groupname != NULL ) {
564                 slap_init_user( username, groupname );
565         }
566 #endif
567
568         extops_init();
569         lutil_passwd_init();
570         slap_op_init();
571
572 #ifdef SLAPD_MODULES
573         if ( module_init() != 0 ) {
574                 rc = 1;
575                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 17 );
576                 goto destroy;
577         }
578 #endif
579
580         if ( slap_schema_init( ) != 0 ) {
581                 Debug( LDAP_DEBUG_ANY,
582                     "schema initialization error\n",
583                     0, 0, 0 );
584
585                 goto destroy;
586         }
587
588         if ( slap_init( serverMode, serverName ) != 0 ) {
589                 rc = 1;
590                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 18 );
591                 goto destroy;
592         }
593
594         if ( slap_controls_init( ) != 0 ) {
595                 Debug( LDAP_DEBUG_ANY,
596                     "controls initialization error\n",
597                     0, 0, 0 );
598
599                 goto destroy;
600         }
601
602 #ifdef HAVE_TLS
603         /* Library defaults to full certificate checking. This is correct when
604          * a client is verifying a server because all servers should have a
605          * valid cert. But few clients have valid certs, so we want our default
606          * to be no checking. The config file can override this as usual.
607          */
608         rc = 0;
609         (void) ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &rc );
610 #endif
611
612 #ifdef LDAP_SLAPI
613         if ( slapi_int_initialize() != 0 ) {
614                 Debug( LDAP_DEBUG_ANY,
615                     "slapi initialization error\n",
616                     0, 0, 0 );
617
618                 goto destroy;
619         }
620 #endif /* LDAP_SLAPI */
621
622         if ( frontend_init() ) {
623                 goto destroy;
624         }
625
626         if ( overlay_init() ) {
627                 goto destroy;
628         }
629
630 #ifdef SLAP_DYNACL
631         if ( acl_init() ) {
632                 goto destroy;
633         }
634 #endif /* SLAP_DYNACL */
635
636         if ( read_config( configfile, configdir ) != 0 ) {
637                 rc = 1;
638                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 19 );
639
640                 if ( check & CHECK_CONFIG ) {
641                         fprintf( stderr, "config check failed\n" );
642                 }
643
644                 goto destroy;
645         }
646
647         if ( check & CHECK_CONFIG ) {
648                 fprintf( stderr, "config check succeeded\n" );
649
650                 check &= ~CHECK_CONFIG;
651                 if ( check == CHECK_NONE ) {
652                         rc = 0;
653                         goto destroy;
654                 }
655         }
656
657         if ( slap_schema_check( ) != 0 ) {
658                 Debug( LDAP_DEBUG_ANY,
659                     "schema prep error\n",
660                     0, 0, 0 );
661
662                 goto destroy;
663         }
664
665 #ifdef HAVE_TLS
666         rc = ldap_pvt_tls_init();
667         if( rc != 0) {
668                 Debug( LDAP_DEBUG_ANY,
669                     "main: TLS init failed: %d\n",
670                     0, 0, 0 );
671                 rc = 1;
672                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
673                 goto destroy;
674         }
675
676         {
677                 void *def_ctx = NULL;
678
679                 /* Save existing default ctx, if any */
680                 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &def_ctx );
681
682                 /* Force new ctx to be created */
683                 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, NULL );
684
685                 rc = ldap_pvt_tls_init_def_ctx();
686                 if( rc != 0) {
687                         Debug( LDAP_DEBUG_ANY,
688                             "main: TLS init def ctx failed: %d\n",
689                             rc, 0, 0 );
690                         rc = 1;
691                         SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 20 );
692                         goto destroy;
693                 }
694                 /* Retrieve slapd's own ctx */
695                 ldap_pvt_tls_get_option( NULL, LDAP_OPT_X_TLS_CTX, &slap_tls_ctx );
696                 /* Restore previous ctx */
697                 ldap_pvt_tls_set_option( NULL, LDAP_OPT_X_TLS_CTX, def_ctx );
698         }
699 #endif
700
701         (void) SIGNAL( LDAP_SIGUSR1, slap_sig_wake );
702         (void) SIGNAL( LDAP_SIGUSR2, slap_sig_shutdown );
703
704 #ifdef SIGPIPE
705         (void) SIGNAL( SIGPIPE, SIG_IGN );
706 #endif
707 #ifdef SIGHUP
708         (void) SIGNAL( SIGHUP, slap_sig_shutdown );
709 #endif
710         (void) SIGNAL( SIGINT, slap_sig_shutdown );
711         (void) SIGNAL( SIGTERM, slap_sig_shutdown );
712 #ifdef SIGTRAP
713         (void) SIGNAL( SIGTRAP, slap_sig_shutdown );
714 #endif
715 #ifdef LDAP_SIGCHLD
716         (void) SIGNAL( LDAP_SIGCHLD, wait4child );
717 #endif
718 #ifdef SIGBREAK
719         /* SIGBREAK is generated when Ctrl-Break is pressed. */
720         (void) SIGNAL( SIGBREAK, slap_sig_shutdown );
721 #endif
722
723 #ifndef HAVE_WINSOCK
724         lutil_detach( no_detach, 0 );
725 #endif /* HAVE_WINSOCK */
726
727 #ifdef CSRIMALLOC
728         mal_leaktrace(1);
729 #endif
730
731         /*
732          * FIXME: moved here from slapd_daemon_task()
733          * because back-monitor db_open() needs it
734          */
735         time( &starttime );
736
737         if ( slap_startup( NULL )  != 0 ) {
738                 rc = 1;
739                 SERVICE_EXIT( ERROR_SERVICE_SPECIFIC_ERROR, 21 );
740                 goto shutdown;
741         }
742
743         Debug( LDAP_DEBUG_ANY, "slapd starting\n", 0, 0, 0 );
744
745
746         if ( slapd_pid_file != NULL ) {
747                 FILE *fp = fopen( slapd_pid_file, "w" );
748
749                 if( fp != NULL ) {
750                         fprintf( fp, "%d\n", (int) getpid() );
751                         fclose( fp );
752
753                 } else {
754                         free(slapd_pid_file);
755                         slapd_pid_file = NULL;
756                 }
757         }
758
759         if ( slapd_args_file != NULL ) {
760                 FILE *fp = fopen( slapd_args_file, "w" );
761
762                 if( fp != NULL ) {
763                         for ( i = 0; i < g_argc; i++ ) {
764                                 fprintf( fp, "%s ", g_argv[i] );
765                         }
766                         fprintf( fp, "\n" );
767                         fclose( fp );
768                 } else {
769                         free(slapd_args_file);
770                         slapd_args_file = NULL;
771                 }
772         }
773
774 #ifdef HAVE_NT_EVENT_LOG
775         if (is_NT_Service)
776         lutil_LogStartedEvent( serverName, slap_debug, configfile ?
777                 configfile : SLAPD_DEFAULT_CONFIGFILE , urls );
778 #endif
779
780         rc = slapd_daemon();
781
782 #ifdef HAVE_NT_SERVICE_MANAGER
783         /* Throw away the event that we used during the startup process. */
784         if ( is_NT_Service )
785                 ldap_pvt_thread_cond_destroy( &started_event );
786 #endif
787
788 shutdown:
789         /* remember an error during shutdown */
790         rc |= slap_shutdown( NULL );
791
792 destroy:
793         /* remember an error during destroy */
794         rc |= slap_destroy();
795
796         while ( !LDAP_STAILQ_EMPTY( &slap_sync_cookie )) {
797                 scp = LDAP_STAILQ_FIRST( &slap_sync_cookie );
798                 LDAP_STAILQ_REMOVE_HEAD( &slap_sync_cookie, sc_next );
799                 ch_free( scp );
800         }
801
802 #ifdef SLAPD_MODULES
803         module_kill();
804 #endif
805
806         slap_op_destroy();
807
808         extops_kill();
809
810 stop:
811 #ifdef HAVE_NT_EVENT_LOG
812         if (is_NT_Service)
813         lutil_LogStoppedEvent( serverName );
814 #endif
815
816         Debug( LDAP_DEBUG_ANY, "slapd stopped.\n", 0, 0, 0 );
817
818
819 #ifdef HAVE_NT_SERVICE_MANAGER
820         lutil_ReportShutdownComplete();
821 #endif
822
823 #ifdef LOG_DEBUG
824     closelog();
825 #endif
826         slapd_daemon_destroy();
827
828         controls_destroy();
829
830         schema_destroy();
831
832         lutil_passwd_destroy();
833
834 #ifdef HAVE_TLS
835         ldap_pvt_tls_destroy();
836 #endif
837
838         if ( slapd_pid_file != NULL ) {
839                 unlink( slapd_pid_file );
840         }
841         if ( slapd_args_file != NULL ) {
842                 unlink( slapd_args_file );
843         }
844
845         config_destroy();
846
847 #ifdef CSRIMALLOC
848         mal_dumpleaktrace( leakfile );
849 #endif
850
851         MAIN_RETURN(rc);
852 }
853
854
855 #ifdef LDAP_SIGCHLD
856
857 /*
858  *  Catch and discard terminated child processes, to avoid zombies.
859  */
860
861 static RETSIGTYPE
862 wait4child( int sig )
863 {
864     int save_errno = errno;
865
866 #ifdef WNOHANG
867     errno = 0;
868 #ifdef HAVE_WAITPID
869     while ( waitpid( (pid_t)-1, NULL, WNOHANG ) > 0 || errno == EINTR )
870         ;       /* NULL */
871 #else
872     while ( wait3( NULL, WNOHANG, NULL ) > 0 || errno == EINTR )
873         ;       /* NULL */
874 #endif
875 #else
876     (void) wait( NULL );
877 #endif
878     (void) SIGNAL_REINSTALL( sig, wait4child );
879     errno = save_errno;
880 }
881
882 #endif /* LDAP_SIGCHLD */
883
884
885 #ifdef LOG_LOCAL4
886
887 /*
888  *  Convert a string to an integer by means of a dispatcher table
889  *  if the string is not in the table return the default
890  */
891
892 static int
893 cnvt_str2int( char *stringVal, STRDISP_P dispatcher, int defaultVal )
894 {
895     int        retVal = defaultVal;
896     STRDISP_P  disp;
897
898     for (disp = dispatcher; disp->stringVal; disp++) {
899
900         if (!strncasecmp (stringVal, disp->stringVal, disp->abbr)) {
901
902             retVal = disp->intVal;
903             break;
904
905         }
906     }
907
908     return (retVal);
909 }
910
911 #endif  /* LOG_LOCAL4 */