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