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