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