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