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