]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldif/ldif.c
ITS#5408 part 11 - notice Abandon.
[openldap] / servers / slapd / back-ldif / ldif.c
1 /* ldif.c - the ldif backend */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2005-2008 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* ACKNOWLEDGEMENTS:
17  * This work was originally developed by Eric Stokes for inclusion
18  * in OpenLDAP Software.
19  */
20
21 #include "portable.h"
22 #include <stdio.h>
23 #include <ac/string.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <ac/dirent.h>
27 #include <fcntl.h>
28 #include <ac/errno.h>
29 #include <ac/unistd.h>
30 #include "slap.h"
31 #include "lutil.h"
32 #include "config.h"
33
34 struct ldif_tool {
35         Entry   **entries;                      /* collected by bi_tool_entry_first() */
36         ID              elen;                           /* length of entries[] array */
37         ID              ecount;                         /* number of entries */
38         ID              ecurrent;                       /* bi_tool_entry_next() position */
39 #       define  ENTRY_BUFF_INCREMENT 500 /* initial entries[] length */
40 };
41
42 /* Per-database data */
43 struct ldif_info {
44         struct berval li_base_path;                     /* database directory */
45         struct ldif_tool li_tool;                       /* for slap tools */
46         ldap_pvt_thread_rdwr_t  li_rdwr;        /* no other I/O when writing */
47 };
48
49 #ifdef _WIN32
50 #define mkdir(a,b)      mkdir(a)
51 #define move_file(from, to) (!MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING))
52 #else
53 #define move_file(from, to) rename(from, to)
54 #endif
55 #define move_dir(from, to) rename(from, to)
56
57
58 #define LDIF    ".ldif"
59 #define LDIF_FILETYPE_SEP       '.'                     /* LDIF[0] */
60
61 /*
62  * Unsafe/translated characters in the filesystem.
63  *
64  * LDIF_UNSAFE_CHAR(c) returns true if the character c is not to be used
65  * in relative filenames, except it should accept '\\', '{' and '}' even
66  * if unsafe.  The value should be a constant expression.
67  *
68  * If '\\' is unsafe, #define LDIF_ESCAPE_CHAR as a safe character.
69  * If '{' and '}' are unsafe, #define IX_FSL/IX_FSR as safe characters.
70  * (Not digits, '-' or '+'.  IX_FSL == IX_FSR is allowed.)
71  *
72  * Characters are escaped as LDIF_ESCAPE_CHAR followed by two hex digits,
73  * except '\\' is replaced with LDIF_ESCAPE_CHAR and {} with IX_FS[LR].
74  * Also some LDIF special chars are hex-escaped.
75  *
76  * Thus an LDIF filename is a valid normalized RDN (or suffix DN)
77  * followed by ".ldif", except with '\\' replaced with LDIF_ESCAPE_CHAR.
78  */
79
80 #ifndef _WIN32
81
82 /*
83  * Unix/MacOSX version.  ':' vs '/' can cause confusion on MacOSX so we
84  * escape both.  We escape them on Unix so both OS variants get the same
85  * filenames.
86  */
87 #define LDIF_ESCAPE_CHAR        '\\'
88 #define LDIF_UNSAFE_CHAR(c)     ((c) == '/' || (c) == ':')
89
90 #else /* _WIN32 */
91
92 /* Windows version - Microsoft's list of unsafe characters, except '\\' */
93 #define LDIF_ESCAPE_CHAR        '^'                     /* Not '\\' (unsafe on Windows) */
94 #define LDIF_UNSAFE_CHAR(c)     \
95         ((c) == '/' || (c) == ':' || \
96          (c) == '<' || (c) == '>' || (c) == '"' || \
97          (c) == '|' || (c) == '?' || (c) == '*')
98
99 #endif /* !_WIN32 */
100
101 /*
102  * Left and Right "{num}" prefix to ordered RDNs ("olcDatabase={1}bdb").
103  * IX_DN* are for LDAP RDNs, IX_FS* for their .ldif filenames.
104  */
105 #define IX_DNL  '{'
106 #define IX_DNR  '}'
107 #ifndef IX_FSL
108 #define IX_FSL  IX_DNL
109 #define IX_FSR  IX_DNR
110 #endif
111
112 /*
113  * Test for unsafe chars, as well as chars handled specially by back-ldif:
114  * - If the escape char is not '\\', it must itself be escaped.  Otherwise
115  *   '\\' and the escape char would map to the same character.
116  * - Escape the '.' in ".ldif", so the directory for an RDN that actually
117  *   ends with ".ldif" can not conflict with a file of the same name.  And
118  *   since some OSes/programs choke on multiple '.'s, escape all of them.
119  * - If '{' and '}' are translated to some other characters, those
120  *   characters must in turn be escaped when they occur in an RDN.
121  */
122 #ifndef LDIF_NEED_ESCAPE
123 #define LDIF_NEED_ESCAPE(c) \
124         ((LDIF_UNSAFE_CHAR(c)) || \
125          LDIF_MAYBE_UNSAFE(c, LDIF_ESCAPE_CHAR) || \
126          LDIF_MAYBE_UNSAFE(c, LDIF_FILETYPE_SEP) || \
127          LDIF_MAYBE_UNSAFE(c, IX_FSL) || \
128          (IX_FSR != IX_FSL && LDIF_MAYBE_UNSAFE(c, IX_FSR)))
129 #endif
130 /*
131  * Helper macro for LDIF_NEED_ESCAPE(): Treat character x as unsafe if
132  * back-ldif does not already treat is specially.
133  */
134 #define LDIF_MAYBE_UNSAFE(c, x) \
135         (!(LDIF_UNSAFE_CHAR(x) || (x) == '\\' || (x) == IX_DNL || (x) == IX_DNR) \
136          && (c) == (x))
137
138 /* Collect other "safe char" tests here, until someone needs a fix. */
139 enum {
140         eq_unsafe = LDIF_UNSAFE_CHAR('='),
141         safe_filenames = STRLENOF("" LDAP_DIRSEP "") == 1 && !(
142                 LDIF_UNSAFE_CHAR('-') || /* for "{-1}frontend" in bconfig.c */
143                 LDIF_UNSAFE_CHAR(LDIF_ESCAPE_CHAR) ||
144                 LDIF_UNSAFE_CHAR(IX_FSL) || LDIF_UNSAFE_CHAR(IX_FSR))
145 };
146 /* Sanity check: Try to force a compilation error if !safe_filenames */
147 typedef struct {
148         int assert_safe_filenames : safe_filenames ? 2 : -2;
149 } assert_safe_filenames[safe_filenames ? 2 : -2];
150
151
152 static ConfigTable ldifcfg[] = {
153         { "directory", "dir", 2, 2, 0, ARG_BERVAL|ARG_OFFSET,
154                 (void *)offsetof(struct ldif_info, li_base_path),
155                 "( OLcfgDbAt:0.1 NAME 'olcDbDirectory' "
156                         "DESC 'Directory for database content' "
157                         "EQUALITY caseIgnoreMatch "
158                         "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
159         { NULL, NULL, 0, 0, 0, ARG_IGNORED,
160                 NULL, NULL, NULL, NULL }
161 };
162
163 static ConfigOCs ldifocs[] = {
164         { "( OLcfgDbOc:2.1 "
165                 "NAME 'olcLdifConfig' "
166                 "DESC 'LDIF backend configuration' "
167                 "SUP olcDatabaseConfig "
168                 "MUST ( olcDbDirectory ) )", Cft_Database, ldifcfg },
169         { NULL, 0, NULL }
170 };
171
172
173 /*
174  * Handle file/directory names.
175  */
176
177 /* Set *res = LDIF filename path for the normalized DN */
178 static void
179 dn2path( BackendDB *be, struct berval *dn, struct berval *res )
180 {
181         struct ldif_info *li = (struct ldif_info *) be->be_private;
182         struct berval *suffixdn = &be->be_nsuffix[0];
183         const char *start, *end, *next, *p;
184         char ch, *ptr;
185         ber_len_t len;
186         static const char hex[] = "0123456789ABCDEF";
187
188         assert( dn != NULL );
189         assert( !BER_BVISNULL( dn ) );
190         assert( suffixdn != NULL );
191         assert( !BER_BVISNULL( suffixdn ) );
192         assert( dnIsSuffix( dn, suffixdn ) );
193
194         start = dn->bv_val;
195         end = start + dn->bv_len;
196
197         /* Room for dir, dirsep, dn, LDIF, "\hexpair"-escaping of unsafe chars */
198         len = li->li_base_path.bv_len + dn->bv_len + (1 + STRLENOF( LDIF ));
199         for ( p = start; p < end; ) {
200                 ch = *p++;
201                 if ( LDIF_NEED_ESCAPE( ch ) )
202                         len += 2;
203         }
204         res->bv_val = ch_malloc( len + 1 );
205
206         ptr = lutil_strcopy( res->bv_val, li->li_base_path.bv_val );
207         for ( next = end - suffixdn->bv_len; end > start; end = next ) {
208                 /* Set p = start of DN component, next = &',' or start of DN */
209                 while ( (p = next) > start ) {
210                         --next;
211                         if ( DN_SEPARATOR( *next ) )
212                                 break;
213                 }
214                 /* Append <dirsep> <p..end-1: RDN or database-suffix> */
215                 for ( *ptr++ = LDAP_DIRSEP[0]; p < end; *ptr++ = ch ) {
216                         ch = *p++;
217                         if ( LDIF_ESCAPE_CHAR != '\\' && ch == '\\' ) {
218                                 ch = LDIF_ESCAPE_CHAR;
219                         } else if ( IX_FSL != IX_DNL && ch == IX_DNL ) {
220                                 ch = IX_FSL;
221                         } else if ( IX_FSR != IX_DNR && ch == IX_DNR ) {
222                                 ch = IX_FSR;
223                         } else if ( LDIF_NEED_ESCAPE( ch ) ) {
224                                 *ptr++ = LDIF_ESCAPE_CHAR;
225                                 *ptr++ = hex[(ch & 0xFFU) >> 4];
226                                 ch = hex[ch & 0x0FU];
227                         }
228                 }
229         }
230         ptr = lutil_strcopy( ptr, LDIF );
231         res->bv_len = ptr - res->bv_val;
232
233         assert( res->bv_len <= len );
234 }
235
236 /*
237  * *dest = dupbv(<dir + LDAP_DIRSEP>), plus room for <more>-sized filename.
238  * Return pointer past the dirname.
239  */
240 static char *
241 fullpath_alloc( struct berval *dest, const struct berval *dir, ber_len_t more )
242 {
243         char *s = SLAP_MALLOC( dir->bv_len + more + 2 );
244
245         dest->bv_val = s;
246         if ( s == NULL ) {
247                 dest->bv_len = 0;
248                 Debug( LDAP_DEBUG_ANY, "back-ldif: out of memory\n", 0, 0, 0 );
249         } else {
250                 s = lutil_strcopy( dest->bv_val, dir->bv_val );
251                 *s++ = LDAP_DIRSEP[0];
252                 *s = '\0';
253                 dest->bv_len = s - dest->bv_val;
254         }
255         return s;
256 }
257
258 /*
259  * Append filename to fullpath_alloc() dirname or replace previous filename.
260  * dir_end = fullpath_alloc() return value.
261  */
262 #define FILL_PATH(fpath, dir_end, filename) \
263         ((fpath)->bv_len = lutil_strcopy(dir_end, filename) - (fpath)->bv_val)
264
265
266 /* .ldif entry filename length <-> subtree dirname length. */
267 #define ldif2dir_len(bv)  ((bv).bv_len -= STRLENOF(LDIF))
268 #define dir2ldif_len(bv)  ((bv).bv_len += STRLENOF(LDIF))
269 /* .ldif entry filename <-> subtree dirname, both with dirname length. */
270 #define ldif2dir_name(bv) ((bv).bv_val[(bv).bv_len] = '\0')
271 #define dir2ldif_name(bv) ((bv).bv_val[(bv).bv_len] = LDIF_FILETYPE_SEP)
272
273 /* Get the parent directory path, plus the LDIF suffix overwritten by a \0. */
274 static int
275 get_parent_path( struct berval *dnpath, struct berval *res )
276 {
277         ber_len_t i = dnpath->bv_len;
278
279         while ( i > 0 && dnpath->bv_val[ --i ] != LDAP_DIRSEP[0] ) ;
280         if ( res == NULL ) {
281                 res = dnpath;
282         } else {
283                 res->bv_val = SLAP_MALLOC( i + 1 + STRLENOF(LDIF) );
284                 if ( res->bv_val == NULL )
285                         return LDAP_OTHER;
286                 AC_MEMCPY( res->bv_val, dnpath->bv_val, i );
287         }
288         res->bv_len = i;
289         strcpy( res->bv_val + i, LDIF );
290         res->bv_val[i] = '\0';
291         return LDAP_SUCCESS;
292 }
293
294 /* Make temporary filename pattern for mkstemp() based on dnpath. */
295 static char *
296 ldif_tempname( const struct berval *dnpath )
297 {
298         static const char suffix[] = ".XXXXXX";
299         ber_len_t len = dnpath->bv_len - STRLENOF( LDIF );
300         char *name = SLAP_MALLOC( len + sizeof( suffix ) );
301
302         if ( name != NULL ) {
303                 AC_MEMCPY( name, dnpath->bv_val, len );
304                 strcpy( name + len, suffix );
305         }
306         return name;
307 }
308
309 /*
310  * Read a file, or stat() it if datap == NULL.  Allocate and fill *datap.
311  * Return LDAP_SUCCESS, LDAP_NO_SUCH_OBJECT (no such file), or another error.
312  */
313 static int
314 ldif_read_file( const char *path, char **datap )
315 {
316         int rc, fd, len;
317         int res = -1;   /* 0:success, <0:error, >0:file too big/growing. */
318         struct stat st;
319         char *data = NULL, *ptr;
320
321         if ( datap == NULL ) {
322                 res = stat( path, &st );
323                 goto done;
324         }
325         fd = open( path, O_RDONLY );
326         if ( fd >= 0 ) {
327                 if ( fstat( fd, &st ) == 0 ) {
328                         if ( st.st_size > INT_MAX - 2 ) {
329                                 res = 1;
330                         } else {
331                                 len = st.st_size + 1; /* +1 detects file size > st.st_size */
332                                 *datap = data = ptr = SLAP_MALLOC( len + 1 );
333                                 if ( ptr != NULL ) {
334                                         while ( len && (res = read( fd, ptr, len )) ) {
335                                                 if ( res > 0 ) {
336                                                         len -= res;
337                                                         ptr += res;
338                                                 } else if ( errno != EINTR ) {
339                                                         break;
340                                                 }
341                                         }
342                                         *ptr = '\0';
343                                 }
344                         }
345                 }
346                 if ( close( fd ) < 0 )
347                         res = -1;
348         }
349
350  done:
351         if ( res == 0 ) {
352                 Debug( LDAP_DEBUG_TRACE, "ldif_read_file: %s: \"%s\"\n",
353                         datap ? "read entry file" : "entry file exists", path, 0 );
354                 rc = LDAP_SUCCESS;
355         } else {
356                 if ( res < 0 && errno == ENOENT ) {
357                         Debug( LDAP_DEBUG_TRACE, "ldif_read_file: "
358                                 "no entry file \"%s\"\n", path, 0, 0 );
359                         rc = LDAP_NO_SUCH_OBJECT;
360                 } else {
361                         const char *msg = res < 0 ? STRERROR( errno ) : "bad stat() size";
362                         Debug( LDAP_DEBUG_ANY, "ldif_read_file: %s for \"%s\"\n",
363                                 msg, path, 0 );
364                         rc = LDAP_OTHER;
365                 }
366                 if ( data != NULL )
367                         SLAP_FREE( data );
368         }
369         return rc;
370 }
371
372 /*
373  * return nonnegative for success or -1 for error
374  * do not return numbers less than -1
375  */
376 static int
377 spew_file( int fd, const char *spew, int len, int *save_errno )
378 {
379         int writeres = 0;
380
381         while(len > 0) {
382                 writeres = write(fd, spew, len);
383                 if(writeres == -1) {
384                         *save_errno = errno;
385                         if (*save_errno != EINTR)
386                                 break;
387                 }
388                 else {
389                         spew += writeres;
390                         len -= writeres;
391                 }
392         }
393         return writeres;
394 }
395
396 /* Write an entry LDIF file.  Create parentdir first if non-NULL. */
397 static int
398 ldif_write_entry(
399         Operation *op,
400         Entry *e,
401         const struct berval *path,
402         const char *parentdir,
403         const char **text )
404 {
405         int rc = LDAP_OTHER, res, save_errno = 0;
406         int fd, entry_length;
407         char *entry_as_string, *tmpfname;
408
409         if ( op->o_abandon )
410                 return SLAPD_ABANDON;
411
412         if ( parentdir != NULL && mkdir( parentdir, 0750 ) < 0 ) {
413                 save_errno = errno;
414                 Debug( LDAP_DEBUG_ANY, "ldif_write_entry: %s \"%s\": %s\n",
415                         "cannot create parent directory",
416                         parentdir, STRERROR( save_errno ) );
417                 *text = "internal error (cannot create parent directory)";
418                 return rc;
419         }
420
421         tmpfname = ldif_tempname( path );
422         fd = tmpfname == NULL ? -1 : mkstemp( tmpfname );
423         if ( fd < 0 ) {
424                 save_errno = errno;
425                 Debug( LDAP_DEBUG_ANY, "ldif_write_entry: %s for \"%s\": %s\n",
426                         "cannot create file", e->e_dn, STRERROR( save_errno ) );
427                 *text = "internal error (cannot create file)";
428
429         } else {
430                 ber_len_t dn_len = e->e_name.bv_len;
431                 struct berval rdn;
432
433                 /* Only save the RDN onto disk */
434                 dnRdn( &e->e_name, &rdn );
435                 if ( rdn.bv_len != dn_len ) {
436                         e->e_name.bv_val[rdn.bv_len] = '\0';
437                         e->e_name.bv_len = rdn.bv_len;
438                 }
439
440                 res = -2;
441                 ldap_pvt_thread_mutex_lock( &entry2str_mutex );
442                 entry_as_string = entry2str( e, &entry_length );
443                 if ( entry_as_string != NULL )
444                         res = spew_file( fd, entry_as_string, entry_length, &save_errno );
445                 ldap_pvt_thread_mutex_unlock( &entry2str_mutex );
446
447                 /* Restore full DN */
448                 if ( rdn.bv_len != dn_len ) {
449                         e->e_name.bv_val[rdn.bv_len] = ',';
450                         e->e_name.bv_len = dn_len;
451                 }
452
453                 if ( close( fd ) < 0 && res >= 0 ) {
454                         res = -1;
455                         save_errno = errno;
456                 }
457
458                 if ( res >= 0 ) {
459                         if ( move_file( tmpfname, path->bv_val ) == 0 ) {
460                                 Debug( LDAP_DEBUG_TRACE, "ldif_write_entry: "
461                                         "wrote entry \"%s\"\n", e->e_name.bv_val, 0, 0 );
462                                 rc = LDAP_SUCCESS;
463                         } else {
464                                 save_errno = errno;
465                                 Debug( LDAP_DEBUG_ANY, "ldif_write_entry: "
466                                         "could not put entry file for \"%s\" in place: %s\n",
467                                         e->e_name.bv_val, STRERROR( save_errno ), 0 );
468                                 *text = "internal error (could not put entry file in place)";
469                         }
470                 } else if ( res == -1 ) {
471                         Debug( LDAP_DEBUG_ANY, "ldif_write_entry: %s \"%s\": %s\n",
472                                 "write error to", tmpfname, STRERROR( save_errno ) );
473                         *text = "internal error (write error to entry file)";
474                 }
475
476                 if ( rc != LDAP_SUCCESS ) {
477                         unlink( tmpfname );
478                 }
479         }
480
481         if ( tmpfname )
482                 SLAP_FREE( tmpfname );
483         return rc;
484 }
485
486 /*
487  * Read the entry at path, or if entryp==NULL just see if it exists.
488  * pdn and pndn are the parent's DN and normalized DN, or both NULL.
489  * Return an LDAP result code.
490  */
491 static int
492 ldif_read_entry(
493         Operation *op,
494         const char *path,
495         struct berval *pdn,
496         struct berval *pndn,
497         Entry **entryp,
498         const char **text )
499 {
500         int rc;
501         Entry *entry;
502         char *entry_as_string;
503         struct berval rdn;
504
505         /* TODO: Does slapd prevent Abandon of Bind as per rfc4511?
506          * If so we need not check for LDAP_REQ_BIND here.
507          */
508         if ( op->o_abandon && op->o_tag != LDAP_REQ_BIND )
509                 return SLAPD_ABANDON;
510
511         rc = ldif_read_file( path, entryp ? &entry_as_string : NULL );
512
513         switch ( rc ) {
514         case LDAP_SUCCESS:
515                 if ( entryp == NULL )
516                         break;
517                 *entryp = entry = str2entry( entry_as_string );
518                 SLAP_FREE( entry_as_string );
519                 if ( entry == NULL ) {
520                         rc = LDAP_OTHER;
521                         if ( text != NULL )
522                                 *text = "internal error (cannot parse some entry file)";
523                         break;
524                 }
525                 if ( pdn == NULL || BER_BVISEMPTY( pdn ) )
526                         break;
527                 /* Append parent DN to DN from LDIF file */
528                 rdn = entry->e_name;
529                 build_new_dn( &entry->e_name, pdn, &rdn, NULL );
530                 SLAP_FREE( rdn.bv_val );
531                 rdn = entry->e_nname;
532                 build_new_dn( &entry->e_nname, pndn, &rdn, NULL );
533                 SLAP_FREE( rdn.bv_val );
534                 break;
535
536         case LDAP_OTHER:
537                 if ( text != NULL )
538                         *text = entryp
539                                 ? "internal error (cannot read some entry file)"
540                                 : "internal error (cannot stat some entry file)";
541                 break;
542         }
543
544         return rc;
545 }
546
547 /*
548  * Read the operation's entry, or if entryp==NULL just see if it exists.
549  * Return an LDAP result code.  May set *text to a message on failure.
550  * If pathp is non-NULL, set it to the entry filename on success.
551  */
552 static int
553 get_entry(
554         Operation *op,
555         Entry **entryp,
556         struct berval *pathp,
557         const char **text )
558 {
559         int rc;
560         struct berval path, pdn, pndn;
561
562         dnParent(&op->o_req_dn, &pdn);
563         dnParent(&op->o_req_ndn, &pndn);
564         dn2path( op->o_bd, &op->o_req_ndn, &path );
565         rc = ldif_read_entry( op, path.bv_val, &pdn, &pndn, entryp, text );
566
567         if ( rc == LDAP_SUCCESS && pathp != NULL ) {
568                 *pathp = path;
569         } else {
570                 SLAP_FREE(path.bv_val);
571         }
572         return rc;
573 }
574
575
576 /*
577  * RDN-named directory entry, with special handling of "attr={num}val" RDNs.
578  * For sorting, filename "attr=val.ldif" is truncated to "attr="val\0ldif",
579  * and filename "attr={num}val.ldif" to "attr={\0um}val.ldif".
580  * Does not sort escaped chars correctly, would need to un-escape them.
581  */
582 typedef struct bvlist {
583         struct bvlist *next;
584         char *trunc;    /* filename was truncated here */
585         int  inum;              /* num from "attr={num}" in filename, or INT_MIN */
586         char savech;    /* original char at *trunc */
587         char fname;             /* variable length array BVL_NAME(bvl) = &fname */
588 #       define BVL_NAME(bvl) ((char *) (bvl) + offsetof(bvlist, fname))
589 #       define BVL_SIZE(namelen) (sizeof(bvlist) + (namelen))
590 } bvlist;
591
592 static int
593 ldif_send_entry( Operation *op, SlapReply *rs, Entry *e, int scope )
594 {
595         int rc = LDAP_SUCCESS;
596
597         if ( scope == LDAP_SCOPE_BASE || scope == LDAP_SCOPE_SUBTREE ) {
598                 if ( rs == NULL ) {
599                         /* Save the entry for tool mode */
600                         struct ldif_tool *tl =
601                                 &((struct ldif_info *) op->o_bd->be_private)->li_tool;
602
603                         if ( tl->ecount >= tl->elen ) {
604                                 /* Allocate/grow entries */
605                                 ID elen = tl->elen ? tl->elen * 2 : ENTRY_BUFF_INCREMENT;
606                                 Entry **entries = (Entry **) SLAP_REALLOC( tl->entries,
607                                         sizeof(Entry *) * elen );
608                                 if ( entries == NULL ) {
609                                         Debug( LDAP_DEBUG_ANY,
610                                                 "ldif_send_entry: out of memory\n", 0, 0, 0 );
611                                         rc = LDAP_OTHER;
612                                         goto done;
613                                 }
614                                 tl->elen = elen;
615                                 tl->entries = entries;
616                         }
617                         tl->entries[tl->ecount++] = e;
618                         return rc;
619                 }
620
621                 else if ( !get_manageDSAit( op ) && is_entry_referral( e ) ) {
622                         /* Send a continuation reference.
623                          * (ldif_back_referrals() handles baseobject referrals.)
624                          * Don't check the filter since it's only a candidate.
625                          */
626                         BerVarray refs = get_entry_referrals( op, e );
627                         rs->sr_ref = referral_rewrite( refs, &e->e_name, NULL, scope );
628                         rs->sr_entry = e;
629                         rc = send_search_reference( op, rs );
630                         ber_bvarray_free( rs->sr_ref );
631                         ber_bvarray_free( refs );
632                         rs->sr_ref = NULL;
633                         rs->sr_entry = NULL;
634                 }
635
636                 else if ( test_filter( op, e, op->ors_filter ) == LDAP_COMPARE_TRUE ) {
637                         rs->sr_entry = e;
638                         rs->sr_attrs = op->ors_attrs;
639                         rs->sr_flags = REP_ENTRY_MODIFIABLE;
640                         rc = send_search_entry( op, rs );
641                         rs->sr_entry = NULL;
642                 }
643         }
644
645  done:
646         entry_free( e );
647         return rc;
648 }
649
650 /* Read LDIF directory <path> into <listp>.  Set *fname_maxlenp. */
651 static int
652 ldif_readdir(
653         Operation *op,
654         SlapReply *rs,
655         const struct berval *path,
656         bvlist **listp,
657         ber_len_t *fname_maxlenp )
658 {
659         int rc = LDAP_SUCCESS;
660         DIR *dir_of_path;
661
662         *listp = NULL;
663         *fname_maxlenp = 0;
664
665         dir_of_path = opendir( path->bv_val );
666         if ( dir_of_path == NULL ) {
667                 int save_errno = errno;
668                 struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
669                 int is_rootDSE = (path->bv_len == li->li_base_path.bv_len);
670
671                 /* Absent directory is OK (leaf entry), except the database dir */
672                 if ( is_rootDSE || save_errno != ENOENT ) {
673                         Debug( LDAP_DEBUG_ANY,
674                                 "=> ldif_search_entry: failed to opendir \"%s\": %s\n",
675                                 path->bv_val, STRERROR( save_errno ), 0 );
676                         rc = LDAP_OTHER;
677                         if ( rs != NULL )
678                                 rs->sr_text =
679                                         save_errno != ENOENT ? "internal error (bad directory)"
680                                         : !is_rootDSE ? "internal error (missing directory)"
681                                         : "internal error (database directory does not exist)";
682                 }
683
684         } else {
685                 bvlist *ptr;
686                 struct dirent *dir;
687                 int save_errno = 0;
688
689                 while ( (dir = readdir( dir_of_path )) != NULL ) {
690                         size_t fname_len;
691                         bvlist *bvl, **prev;
692                         char *trunc, *idxp, *endp, *endp2;
693
694                         fname_len = strlen( dir->d_name );
695                         if ( fname_len < STRLENOF( "x=" LDIF )) /* min filename size */
696                                 continue;
697                         if ( strcmp( dir->d_name + fname_len - STRLENOF(LDIF), LDIF ))
698                                 continue;
699
700                         if ( *fname_maxlenp < fname_len )
701                                 *fname_maxlenp = fname_len;
702
703                         bvl = SLAP_MALLOC( BVL_SIZE( fname_len ) );
704                         if ( bvl == NULL ) {
705                                 rc = LDAP_OTHER;
706                                 save_errno = errno;
707                                 break;
708                         }
709                         strcpy( BVL_NAME( bvl ), dir->d_name );
710
711                         /* Make it sortable by ("attr=val" or <preceding {num}, num>) */
712                         trunc = BVL_NAME( bvl ) + fname_len - STRLENOF( LDIF );
713                         if ( (idxp = strchr( BVL_NAME( bvl ) + 2, IX_FSL )) != NULL &&
714                                  (endp = strchr( ++idxp, IX_FSR )) != NULL && endp > idxp &&
715                                  (eq_unsafe || idxp[-2] == '=' || endp + 1 == trunc) )
716                         {
717                                 /* attr={n}val or bconfig.c's "pseudo-indexed" attr=val{n} */
718                                 bvl->inum = strtol( idxp, &endp2, 10 );
719                                 if ( endp2 == endp ) {
720                                         trunc = idxp;
721                                         goto truncate;
722                                 }
723                         }
724                         bvl->inum = INT_MIN;
725                 truncate:
726                         bvl->trunc = trunc;
727                         bvl->savech = *trunc;
728                         *trunc = '\0';
729
730                         for ( prev = listp; (ptr = *prev) != NULL; prev = &ptr->next ) {
731                                 int cmp = strcmp( BVL_NAME( bvl ), BVL_NAME( ptr ));
732                                 if ( cmp < 0 || (cmp == 0 && bvl->inum < ptr->inum) )
733                                         break;
734                         }
735                         *prev = bvl;
736                         bvl->next = ptr;
737                 }
738
739                 if ( closedir( dir_of_path ) < 0 ) {
740                         save_errno = errno;
741                         rc = LDAP_OTHER;
742                         if ( rs != NULL )
743                                 rs->sr_text = "internal error (bad directory)";
744                 }
745                 if ( rc != LDAP_SUCCESS ) {
746                         Debug( LDAP_DEBUG_ANY, "ldif_search_entry: %s \"%s\": %s\n",
747                                 "error reading directory", path->bv_val,
748                                 STRERROR( save_errno ) );
749                 }
750         }
751
752         return rc;
753 }
754
755 /*
756  * Send an entry, recursively search its children, and free or save it.
757  * Return an LDAP result code.  Parameters:
758  *  op, rs  operation and reply.  rs == NULL for slap tools.
759  *  e       entry to search, or NULL for rootDSE.
760  *  scope   scope for the part of the search from this entry.
761  *  path    LDIF filename -- bv_len and non-directory part are overwritten.
762  */
763 static int
764 ldif_search_entry(
765         Operation *op,
766         SlapReply *rs,
767         Entry *e,
768         int scope,
769         struct berval *path )
770 {
771         int rc = LDAP_SUCCESS;
772         struct berval dn = BER_BVC( "" ), ndn = BER_BVC( "" );
773
774         if ( scope != LDAP_SCOPE_BASE && e != NULL ) {
775                 /* Copy DN/NDN since we send the entry with REP_ENTRY_MODIFIABLE,
776                  * which bconfig.c seems to need.  (TODO: see config_rename_one.)
777                  */
778                 if ( ber_dupbv( &dn,  &e->e_name  ) == NULL ||
779                          ber_dupbv( &ndn, &e->e_nname ) == NULL )
780                 {
781                         Debug( LDAP_DEBUG_ANY,
782                                 "ldif_search_entry: out of memory\n", 0, 0, 0 );
783                         rc = LDAP_OTHER;
784                         goto done;
785                 }
786         }
787
788         /* Send the entry if appropriate, and free or save it */
789         if ( e != NULL )
790                 rc = ldif_send_entry( op, rs, e, scope );
791
792         /* Search the children */
793         if ( scope != LDAP_SCOPE_BASE && rc == LDAP_SUCCESS ) {
794                 bvlist *list, *ptr;
795                 struct berval fpath;    /* becomes child pathname */
796                 char *dir_end;  /* will point past dirname in fpath */
797
798                 ldif2dir_len( *path );
799                 ldif2dir_name( *path );
800                 rc = ldif_readdir( op, rs, path, &list, &fpath.bv_len );
801
802                 if ( list != NULL ) {
803                         const char **text = rs == NULL ? NULL : &rs->sr_text;
804
805                         if ( scope == LDAP_SCOPE_ONELEVEL )
806                                 scope = LDAP_SCOPE_BASE;
807                         else if ( scope == LDAP_SCOPE_SUBORDINATE )
808                                 scope = LDAP_SCOPE_SUBTREE;
809
810                         /* Allocate fpath and fill in directory part */
811                         dir_end = fullpath_alloc( &fpath, path, fpath.bv_len );
812                         if ( dir_end == NULL )
813                                 rc = LDAP_OTHER;
814
815                         do {
816                                 ptr = list;
817
818                                 if ( rc == LDAP_SUCCESS ) {
819                                         *ptr->trunc = ptr->savech;
820                                         FILL_PATH( &fpath, dir_end, BVL_NAME( ptr ));
821
822                                         rc = ldif_read_entry( op, fpath.bv_val, &dn, &ndn,
823                                                 &e, text );
824                                         switch ( rc ) {
825                                         case LDAP_SUCCESS:
826                                                 rc = ldif_search_entry( op, rs, e, scope, &fpath );
827                                                 break;
828                                         case LDAP_NO_SUCH_OBJECT:
829                                                 /* Only the search baseDN may produce noSuchObject. */
830                                                 rc = LDAP_OTHER;
831                                                 if ( rs != NULL )
832                                                         rs->sr_text = "internal error "
833                                                                 "(did someone just remove an entry file?)";
834                                                 Debug( LDAP_DEBUG_ANY, "ldif_search_entry: "
835                                                         "file listed in parent directory does not exist: "
836                                                         "\"%s\"\n", fpath.bv_val, 0, 0 );
837                                                 break;
838                                         }
839                                 }
840
841                                 list = ptr->next;
842                                 SLAP_FREE( ptr );
843                         } while ( list != NULL );
844
845                         if ( !BER_BVISNULL( &fpath ) )
846                                 SLAP_FREE( fpath.bv_val );
847                 }
848         }
849
850  done:
851         if ( !BER_BVISEMPTY( &dn ) )
852                 ber_memfree( dn.bv_val );
853         if ( !BER_BVISEMPTY( &ndn ) )
854                 ber_memfree( ndn.bv_val );
855         return rc;
856 }
857
858 static int
859 search_tree( Operation *op, SlapReply *rs )
860 {
861         int rc = LDAP_SUCCESS;
862         Entry *e = NULL;
863         struct berval path;
864         struct berval pdn, pndn;
865
866         dn2path( op->o_bd, &op->o_req_ndn, &path );
867         if ( !BER_BVISEMPTY( &op->o_req_ndn ) ) {
868                 /* Read baseObject */
869                 dnParent( &op->o_req_dn, &pdn );
870                 dnParent( &op->o_req_ndn, &pndn );
871                 rc = ldif_read_entry( op, path.bv_val, &pdn, &pndn, &e,
872                         rs == NULL ? NULL : &rs->sr_text );
873         }
874         if ( rc == LDAP_SUCCESS )
875                 rc = ldif_search_entry( op, rs, e, op->ors_scope, &path );
876
877         ch_free( path.bv_val );
878         return rc;
879 }
880
881
882 /*
883  * Prepare to create or rename an entry:
884  * Check that the entry does not already exist.
885  * Check that the parent entry exists and can have subordinates,
886  * unless need_dir is NULL or adding the suffix entry.
887  *
888  * Return an LDAP result code.  May set *text to a message on failure.
889  * If success, set *dnpath to LDIF entry path and *need_dir to
890  * (directory must be created ? dirname : NULL).
891  */
892 static int
893 ldif_prepare_create(
894         Operation *op,
895         Entry *e,
896         struct berval *dnpath,
897         char **need_dir,
898         const char **text )
899 {
900         BackendDB *be = op->o_bd;
901         struct ldif_info *li = (struct ldif_info *) be->be_private;
902         struct berval *ndn = &e->e_nname;
903         struct berval ppath = BER_BVNULL;
904         struct stat st;
905         Entry *parent = NULL;
906         int rc = LDAP_SUCCESS;
907
908         if ( op->o_abandon )
909                 return SLAPD_ABANDON;
910
911         dn2path( be, ndn, dnpath );
912
913         if ( stat( dnpath->bv_val, &st ) == 0 ) { /* entry .ldif file */
914                 rc = LDAP_ALREADY_EXISTS;
915
916         } else if ( errno != ENOENT ) {
917                 Debug( LDAP_DEBUG_ANY,
918                         "ldif_prepare_create: cannot stat \"%s\": %s\n",
919                         dnpath->bv_val, STRERROR( errno ), 0 );
920                 rc = LDAP_OTHER;
921                 *text = "internal error (cannot check entry file)";
922
923         } else if ( need_dir != NULL ) {
924                 *need_dir = NULL;
925                 rc = get_parent_path( dnpath, &ppath );
926                 /* If parent dir exists, so does parent .ldif:
927                  * The directory gets created after and removed before the .ldif.
928                  * Except with the database directory, which has no matching entry.
929                  */
930                 if ( rc == LDAP_SUCCESS && stat( ppath.bv_val, &st ) < 0 ) {
931                         rc = errno == ENOENT && ppath.bv_len > li->li_base_path.bv_len
932                                 ? LDAP_NO_SUCH_OBJECT : LDAP_OTHER;
933                 }
934                 switch ( rc ) {
935                 case LDAP_NO_SUCH_OBJECT:
936                         /* No parent dir, check parent .ldif */
937                         dir2ldif_name( ppath );
938                         rc = ldif_read_entry( op, ppath.bv_val, NULL, NULL,
939                                 (op->o_tag != LDAP_REQ_ADD || get_manageDSAit( op )
940                                  ? &parent : NULL),
941                                 text );
942                         switch ( rc ) {
943                         case LDAP_SUCCESS:
944                                 /* Check that parent is not a referral, unless
945                                  * ldif_back_referrals() already checked.
946                                  */
947                                 if ( parent != NULL ) {
948                                         int is_ref = is_entry_referral( parent );
949                                         entry_free( parent );
950                                         if ( is_ref ) {
951                                                 rc = LDAP_AFFECTS_MULTIPLE_DSAS;
952                                                 *text = op->o_tag == LDAP_REQ_MODDN
953                                                         ? "newSuperior is a referral object"
954                                                         : "parent is a referral object";
955                                                 break;
956                                         }
957                                 }
958                                 /* Must create parent directory. */
959                                 ldif2dir_name( ppath );
960                                 *need_dir = ppath.bv_val;
961                                 break;
962                         case LDAP_NO_SUCH_OBJECT:
963                                 *text = op->o_tag == LDAP_REQ_MODDN
964                                         ? "newSuperior object does not exist"
965                                         : "parent does not exist";
966                                 break;
967                         }
968                         break;
969                 case LDAP_OTHER:
970                         Debug( LDAP_DEBUG_ANY,
971                                 "ldif_prepare_create: cannot stat \"%s\" parent dir: %s\n",
972                                 ndn->bv_val, STRERROR( errno ), 0 );
973                         *text = "internal error (cannot stat parent dir)";
974                         break;
975                 }
976                 if ( *need_dir == NULL && ppath.bv_val != NULL )
977                         SLAP_FREE( ppath.bv_val );
978         }
979
980         if ( rc != LDAP_SUCCESS ) {
981                 SLAP_FREE( dnpath->bv_val );
982                 BER_BVZERO( dnpath );
983         }
984         return rc;
985 }
986
987 static int apply_modify_to_entry(Entry * entry,
988                                 Modifications * modlist,
989                                 Operation * op,
990                                 SlapReply * rs)
991 {
992         char textbuf[SLAP_TEXT_BUFLEN];
993         int rc = modlist ? LDAP_UNWILLING_TO_PERFORM : LDAP_SUCCESS;
994         int is_oc = 0;
995         Modification *mods;
996
997         if (!acl_check_modlist(op, entry, modlist)) {
998                 return LDAP_INSUFFICIENT_ACCESS;
999         }
1000
1001         for (; modlist != NULL; modlist = modlist->sml_next) {
1002                 mods = &modlist->sml_mod;
1003
1004                 if ( mods->sm_desc == slap_schema.si_ad_objectClass ) {
1005                         is_oc = 1;
1006                 }
1007                 switch (mods->sm_op) {
1008                 case LDAP_MOD_ADD:
1009                         rc = modify_add_values(entry, mods,
1010                                    get_permissiveModify(op),
1011                                    &rs->sr_text, textbuf,
1012                                    sizeof( textbuf ) );
1013                         break;
1014                                 
1015                 case LDAP_MOD_DELETE:
1016                         rc = modify_delete_values(entry, mods,
1017                                 get_permissiveModify(op),
1018                                 &rs->sr_text, textbuf,
1019                                 sizeof( textbuf ) );
1020                         break;
1021                                 
1022                 case LDAP_MOD_REPLACE:
1023                         rc = modify_replace_values(entry, mods,
1024                                  get_permissiveModify(op),
1025                                  &rs->sr_text, textbuf,
1026                                  sizeof( textbuf ) );
1027                         break;
1028
1029                 case LDAP_MOD_INCREMENT:
1030                         rc = modify_increment_values( entry,
1031                                 mods, get_permissiveModify(op),
1032                                 &rs->sr_text, textbuf,
1033                                 sizeof( textbuf ) );
1034                         break;
1035
1036                 case SLAP_MOD_SOFTADD:
1037                         mods->sm_op = LDAP_MOD_ADD;
1038                         rc = modify_add_values(entry, mods,
1039                                    get_permissiveModify(op),
1040                                    &rs->sr_text, textbuf,
1041                                    sizeof( textbuf ) );
1042                         mods->sm_op = SLAP_MOD_SOFTADD;
1043                         if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
1044                                 rc = LDAP_SUCCESS;
1045                         }
1046                         break;
1047                 }
1048                 if(rc != LDAP_SUCCESS) break;
1049         }
1050
1051         if ( rc == LDAP_SUCCESS ) {
1052                 rs->sr_text = NULL; /* Needed at least with SLAP_MOD_SOFTADD */
1053                 if ( is_oc ) {
1054                         entry->e_ocflags = 0;
1055                 }
1056                 /* check that the entry still obeys the schema */
1057                 rc = entry_schema_check( op, entry, NULL, 0, 0,
1058                           &rs->sr_text, textbuf, sizeof( textbuf ) );
1059         }
1060
1061         return rc;
1062 }
1063
1064
1065 static int
1066 ldif_back_referrals( Operation *op, SlapReply *rs )
1067 {
1068         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1069         struct berval path, dn = op->o_req_dn, ndn = op->o_req_ndn;
1070         ber_len_t min_dnlen;
1071         Entry *entry = NULL, **entryp;
1072         BerVarray ref;
1073         int rc;
1074
1075         min_dnlen = op->o_bd->be_nsuffix[0].bv_len;
1076         if ( min_dnlen == 0 ) {
1077                 /* Catch root DSE (empty DN), it is not a referral */
1078                 min_dnlen = 1;
1079                 if ( BER_BVISEMPTY( &ndn ) )
1080                         return LDAP_SUCCESS;
1081         }
1082
1083         entryp = get_manageDSAit( op ) ? NULL : &entry;
1084         dn2path( op->o_bd, &ndn, &path );
1085         ldap_pvt_thread_rdwr_rlock( &li->li_rdwr );
1086
1087         for (;;) {
1088                 dnParent( &dn, &dn );
1089                 dnParent( &ndn, &ndn );
1090                 rc = ldif_read_entry( op, path.bv_val, &dn, &ndn,
1091                         entryp, &rs->sr_text );
1092                 if ( rc != LDAP_NO_SUCH_OBJECT )
1093                         break;
1094
1095                 rc = LDAP_SUCCESS;
1096                 if ( ndn.bv_len < min_dnlen )
1097                         break;
1098                 (void) get_parent_path( &path, NULL );
1099                 dir2ldif_name( path );
1100                 entryp = &entry;
1101         }
1102
1103         ldap_pvt_thread_rdwr_runlock( &li->li_rdwr );
1104         SLAP_FREE( path.bv_val );
1105
1106         if ( entry != NULL ) {
1107                 if ( is_entry_referral( entry ) ) {
1108                         Debug( LDAP_DEBUG_TRACE,
1109                                 "ldif_back_referrals: tag=%lu target=\"%s\" matched=\"%s\"\n",
1110                                 (unsigned long) op->o_tag, op->o_req_dn.bv_val, entry->e_dn );
1111
1112                         ref = get_entry_referrals( op, entry );
1113                         rs->sr_ref = referral_rewrite( ref, &entry->e_name, &op->o_req_dn,
1114                                 op->o_tag == LDAP_REQ_SEARCH ?
1115                                 op->ors_scope : LDAP_SCOPE_DEFAULT );
1116                         ber_bvarray_free( ref );
1117
1118                         if ( rs->sr_ref != NULL ) {
1119                                 /* send referral */
1120                                 rc = rs->sr_err = LDAP_REFERRAL;
1121                                 rs->sr_matched = entry->e_dn;
1122                                 send_ldap_result( op, rs );
1123                                 ber_bvarray_free( rs->sr_ref );
1124                                 rs->sr_ref = NULL;
1125                         } else {
1126                                 rc = LDAP_OTHER;
1127                                 rs->sr_text = "bad referral object";
1128                         }
1129                         rs->sr_matched = NULL;
1130                 }
1131
1132                 entry_free( entry );
1133         }
1134
1135         return rc;
1136 }
1137
1138
1139 /* LDAP operations */
1140
1141 static int
1142 ldif_back_bind( Operation *op, SlapReply *rs )
1143 {
1144         struct ldif_info *li;
1145         Attribute *a;
1146         AttributeDescription *password = slap_schema.si_ad_userPassword;
1147         int return_val;
1148         Entry *entry = NULL;
1149
1150         switch ( be_rootdn_bind( op, rs ) ) {
1151         case SLAP_CB_CONTINUE:
1152                 break;
1153
1154         default:
1155                 /* in case of success, front end will send result;
1156                  * otherwise, be_rootdn_bind() did */
1157                 return rs->sr_err;
1158         }
1159
1160         li = (struct ldif_info *) op->o_bd->be_private;
1161         ldap_pvt_thread_rdwr_rlock(&li->li_rdwr);
1162         return_val = get_entry(op, &entry, NULL, NULL);
1163
1164         /* no object is found for them */
1165         if(return_val != LDAP_SUCCESS) {
1166                 rs->sr_err = return_val = LDAP_INVALID_CREDENTIALS;
1167                 goto return_result;
1168         }
1169
1170         /* they don't have userpassword */
1171         if((a = attr_find(entry->e_attrs, password)) == NULL) {
1172                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1173                 return_val = 1;
1174                 goto return_result;
1175         }
1176
1177         /* authentication actually failed */
1178         if(slap_passwd_check(op, entry, a, &op->oq_bind.rb_cred,
1179                              &rs->sr_text) != 0) {
1180                 rs->sr_err = LDAP_INVALID_CREDENTIALS;
1181                 return_val = 1;
1182                 goto return_result;
1183         }
1184
1185         /* let the front-end send success */
1186         return_val = 0;
1187         goto return_result;
1188
1189  return_result:
1190         ldap_pvt_thread_rdwr_runlock(&li->li_rdwr);
1191         if(return_val != 0)
1192                 send_ldap_result( op, rs );
1193         if(entry != NULL)
1194                 entry_free(entry);
1195         return return_val;
1196 }
1197
1198 static int ldif_back_search(Operation *op, SlapReply *rs)
1199 {
1200         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1201
1202         ldap_pvt_thread_rdwr_rlock(&li->li_rdwr);
1203         rs->sr_err = search_tree( op, rs );
1204         ldap_pvt_thread_rdwr_runlock(&li->li_rdwr);
1205         send_ldap_result(op, rs);
1206
1207         return rs->sr_err;
1208 }
1209
1210 static int ldif_back_add(Operation *op, SlapReply *rs) {
1211         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1212         Entry * e = op->ora_e;
1213         struct berval path;
1214         char *parentdir;
1215         char textbuf[SLAP_TEXT_BUFLEN];
1216         int rc;
1217
1218         Debug( LDAP_DEBUG_TRACE, "ldif_back_add: \"%s\"\n", e->e_dn, 0, 0 );
1219
1220         rc = entry_schema_check( op, e, NULL, 0, 1,
1221                 &rs->sr_text, textbuf, sizeof( textbuf ) );
1222         if ( rc != LDAP_SUCCESS )
1223                 goto send_res;
1224
1225         rc = slap_add_opattrs( op, &rs->sr_text, textbuf, sizeof( textbuf ), 1 );
1226         if ( rc != LDAP_SUCCESS )
1227                 goto send_res;
1228
1229         ldap_pvt_thread_rdwr_wlock(&li->li_rdwr);
1230
1231         rc = ldif_prepare_create( op, e, &path, &parentdir, &rs->sr_text );
1232         if ( rc == LDAP_SUCCESS ) {
1233                 rc = ldif_write_entry( op, e, &path, parentdir, &rs->sr_text );
1234                 SLAP_FREE( path.bv_val );
1235                 if ( parentdir != NULL )
1236                         SLAP_FREE( parentdir );
1237         }
1238
1239         ldap_pvt_thread_rdwr_wunlock(&li->li_rdwr);
1240
1241  send_res:
1242         rs->sr_err = rc;
1243         Debug( LDAP_DEBUG_TRACE, "ldif_back_add: err: %d text: %s\n",
1244                 rc, rs->sr_text ? rs->sr_text : "", 0 );
1245         send_ldap_result(op, rs);
1246         slap_graduate_commit_csn( op );
1247         return rs->sr_err;
1248 }
1249
1250 static int ldif_back_modify(Operation *op, SlapReply *rs) {
1251         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1252         Modifications * modlst = op->orm_modlist;
1253         struct berval path;
1254         Entry *entry;
1255         int rc;
1256
1257         slap_mods_opattrs( op, &op->orm_modlist, 1 );
1258
1259         ldap_pvt_thread_rdwr_wlock(&li->li_rdwr);
1260
1261         rc = get_entry( op, &entry, &path, &rs->sr_text );
1262         if ( rc == LDAP_SUCCESS ) {
1263                 rc = apply_modify_to_entry( entry, modlst, op, rs );
1264                 if ( rc == LDAP_SUCCESS ) {
1265                         rc = ldif_write_entry( op, entry, &path, NULL, &rs->sr_text );
1266                 }
1267
1268                 entry_free( entry );
1269                 SLAP_FREE( path.bv_val );
1270         }
1271
1272         ldap_pvt_thread_rdwr_wunlock(&li->li_rdwr);
1273
1274         rs->sr_err = rc;
1275         send_ldap_result( op, rs );
1276         slap_graduate_commit_csn( op );
1277         return rs->sr_err;
1278 }
1279
1280 static int
1281 ldif_back_delete( Operation *op, SlapReply *rs )
1282 {
1283         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1284         struct berval path;
1285         int rc = LDAP_SUCCESS;
1286
1287         if ( BER_BVISEMPTY( &op->o_csn )) {
1288                 struct berval csn;
1289                 char csnbuf[LDAP_LUTIL_CSNSTR_BUFSIZE];
1290
1291                 csn.bv_val = csnbuf;
1292                 csn.bv_len = sizeof( csnbuf );
1293                 slap_get_csn( op, &csn, 1 );
1294         }
1295
1296         ldap_pvt_thread_rdwr_wlock(&li->li_rdwr);
1297         if ( op->o_abandon ) {
1298                 rc = SLAPD_ABANDON;
1299                 goto done;
1300         }
1301
1302         dn2path( op->o_bd, &op->o_req_ndn, &path );
1303         ldif2dir_len( path );
1304         ldif2dir_name( path );
1305         if ( rmdir( path.bv_val ) < 0 ) {
1306                 switch ( errno ) {
1307                 case ENOTEMPTY:
1308                         rc = LDAP_NOT_ALLOWED_ON_NONLEAF;
1309                         break;
1310                 case ENOENT:
1311                         /* is leaf, go on */
1312                         break;
1313                 default:
1314                         rc = LDAP_OTHER;
1315                         rs->sr_text = "internal error (cannot delete subtree directory)";
1316                         break;
1317                 }
1318         }
1319
1320         if ( rc == LDAP_SUCCESS ) {
1321                 dir2ldif_name( path );
1322                 if ( unlink( path.bv_val ) < 0 ) {
1323                         rc = LDAP_NO_SUCH_OBJECT;
1324                         if ( errno != ENOENT ) {
1325                                 rc = LDAP_OTHER;
1326                                 rs->sr_text = "internal error (cannot delete entry file)";
1327                         }
1328                 }
1329         }
1330
1331         if ( rc == LDAP_OTHER ) {
1332                 Debug( LDAP_DEBUG_ANY, "ldif_back_delete: %s \"%s\": %s\n",
1333                         "cannot delete", path.bv_val, STRERROR( errno ) );
1334         }
1335
1336         SLAP_FREE(path.bv_val);
1337  done:
1338         ldap_pvt_thread_rdwr_wunlock(&li->li_rdwr);
1339         rs->sr_err = rc;
1340         send_ldap_result( op, rs );
1341         slap_graduate_commit_csn( op );
1342         return rs->sr_err;
1343 }
1344
1345
1346 static int
1347 ldif_move_entry(
1348         Operation *op,
1349         Entry *entry,
1350         struct berval *oldpath,
1351         const char **text )
1352 {
1353         struct berval newpath;
1354         char *parentdir = NULL, *trash;
1355         int rc, rename_res;
1356
1357         rc = ldif_prepare_create( op, entry, &newpath,
1358                         op->orr_newSup ? &parentdir : NULL, text );
1359
1360         if ( rc == LDAP_SUCCESS ) {
1361                 rc = ldif_write_entry( op, entry, &newpath, parentdir, text );
1362                 if ( rc == LDAP_SUCCESS ) {
1363                         trash = oldpath->bv_val; /* will be .ldif file to delete */
1364                         ldif2dir_len( newpath );
1365                         ldif2dir_len( *oldpath );
1366                         /* Move subdir before deleting old entry,
1367                          * so .ldif always exists if subdir does.
1368                          */
1369                         ldif2dir_name( newpath );
1370                         ldif2dir_name( *oldpath );
1371                         rename_res = move_dir( oldpath->bv_val, newpath.bv_val );
1372                         if ( rename_res != 0 && errno != ENOENT ) {
1373                                 rc = LDAP_OTHER;
1374                                 *text = "internal error (cannot move this subtree)";
1375                                 trash = newpath.bv_val;
1376                         }
1377
1378                         /* Delete old entry, or if error undo change */
1379                         for (;;) {
1380                                 dir2ldif_name( newpath );
1381                                 dir2ldif_name( *oldpath );
1382                                 if ( unlink( trash ) == 0 )
1383                                         break;
1384                                 if ( rc == LDAP_SUCCESS ) {
1385                                         /* Prepare to undo change and return failure */
1386                                         rc = LDAP_OTHER;
1387                                         *text = "internal error (cannot move this entry)";
1388                                         trash = newpath.bv_val;
1389                                         if ( rename_res != 0 )
1390                                                 continue;
1391                                         /* First move subdirectory back */
1392                                         ldif2dir_name( newpath );
1393                                         ldif2dir_name( *oldpath );
1394                                         if ( move_dir( newpath.bv_val, oldpath->bv_val ) == 0 )
1395                                                 continue;
1396                                 }
1397                                 *text = "added new but couldn't delete old entry!";
1398                                 break;
1399                         }
1400
1401                         if ( rc != LDAP_SUCCESS ) {
1402                                 char s[128];
1403                                 snprintf( s, sizeof s, "%s (%s)", *text, STRERROR( errno ));
1404                                 Debug( LDAP_DEBUG_ANY,
1405                                         "ldif_move_entry: %s: \"%s\" -> \"%s\"\n",
1406                                         s, op->o_req_dn.bv_val, entry->e_dn );
1407                         }
1408                 }
1409
1410                 SLAP_FREE( newpath.bv_val );
1411                 if ( parentdir != NULL )
1412                         SLAP_FREE( parentdir );
1413         }
1414
1415         return rc;
1416 }
1417
1418 static int
1419 ldif_back_modrdn(Operation *op, SlapReply *rs)
1420 {
1421         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1422         struct berval new_dn = BER_BVNULL, new_ndn = BER_BVNULL;
1423         struct berval p_dn, old_path;
1424         Entry *entry;
1425         int rc;
1426
1427         slap_mods_opattrs( op, &op->orr_modlist, 1 );
1428
1429         ldap_pvt_thread_rdwr_wlock( &li->li_rdwr );
1430
1431         rc = get_entry( op, &entry, &old_path, &rs->sr_text );
1432         if ( rc == LDAP_SUCCESS ) {
1433                 /* build new dn, and new ndn for the entry */
1434                 if ( op->oq_modrdn.rs_newSup != NULL ) {
1435                         p_dn = *op->oq_modrdn.rs_newSup;
1436                 } else {
1437                         dnParent( &entry->e_name, &p_dn );
1438                 }
1439                 build_new_dn( &new_dn, &p_dn, &op->oq_modrdn.rs_newrdn, NULL ); 
1440                 dnNormalize( 0, NULL, NULL, &new_dn, &new_ndn, NULL );
1441                 ber_memfree_x( entry->e_name.bv_val, NULL );
1442                 ber_memfree_x( entry->e_nname.bv_val, NULL );
1443                 entry->e_name = new_dn;
1444                 entry->e_nname = new_ndn;
1445
1446                 /* perform the modifications */
1447                 rc = apply_modify_to_entry( entry, op->orr_modlist, op, rs );
1448                 if ( rc == LDAP_SUCCESS )
1449                         rc = ldif_move_entry( op, entry, &old_path, &rs->sr_text );
1450
1451                 entry_free( entry );
1452                 SLAP_FREE( old_path.bv_val );
1453         }
1454
1455         ldap_pvt_thread_rdwr_wunlock( &li->li_rdwr );
1456         rs->sr_err = rc;
1457         send_ldap_result( op, rs );
1458         slap_graduate_commit_csn( op );
1459         return rs->sr_err;
1460 }
1461
1462
1463 /* Return LDAP_SUCCESS IFF we retrieve the specified entry. */
1464 static int
1465 ldif_back_entry_get(
1466         Operation *op,
1467         struct berval *ndn,
1468         ObjectClass *oc,
1469         AttributeDescription *at,
1470         int rw,
1471         Entry **e )
1472 {
1473         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1474         struct berval op_dn = op->o_req_dn, op_ndn = op->o_req_ndn;
1475         int rc;
1476
1477         assert( ndn != NULL );
1478         assert( !BER_BVISNULL( ndn ) );
1479
1480         ldap_pvt_thread_rdwr_rlock( &li->li_rdwr );
1481         op->o_req_dn = *ndn;
1482         op->o_req_ndn = *ndn;
1483         rc = get_entry( op, e, NULL, NULL );
1484         op->o_req_dn = op_dn;
1485         op->o_req_ndn = op_ndn;
1486         ldap_pvt_thread_rdwr_runlock( &li->li_rdwr );
1487
1488         if ( rc == LDAP_SUCCESS && oc && !is_entry_objectclass_or_sub( *e, oc ) ) {
1489                 rc = LDAP_NO_SUCH_ATTRIBUTE;
1490                 entry_free( *e );
1491                 *e = NULL;
1492         }
1493
1494         return rc;
1495 }
1496
1497
1498 /* Slap tools */
1499
1500 static int ldif_tool_entry_open(BackendDB *be, int mode) {
1501         struct ldif_tool *tl = &((struct ldif_info *) be->be_private)->li_tool;
1502
1503         tl->ecurrent = 0;
1504         return 0;
1505 }                                       
1506
1507 static int ldif_tool_entry_close(BackendDB * be) {
1508         struct ldif_tool *tl = &((struct ldif_info *) be->be_private)->li_tool;
1509         Entry **entries = tl->entries;
1510         ID i;
1511
1512         for ( i = tl->ecount; i--; )
1513                 if ( entries[i] )
1514                         entry_free( entries[i] );
1515         SLAP_FREE( entries );
1516         tl->entries = NULL;
1517         tl->ecount = tl->elen = 0;
1518         return 0;
1519 }
1520
1521 static ID ldif_tool_entry_next(BackendDB *be)
1522 {
1523         struct ldif_tool *tl = &((struct ldif_info *) be->be_private)->li_tool;
1524
1525         if ( tl->ecurrent >= tl->ecount )
1526                 return NOID;
1527         else
1528                 return ++tl->ecurrent;
1529 }
1530
1531 static ID
1532 ldif_tool_entry_first(BackendDB *be)
1533 {
1534         struct ldif_tool *tl = &((struct ldif_info *) be->be_private)->li_tool;
1535
1536         if ( tl->entries == NULL ) {
1537                 Operation op = {0};
1538
1539                 op.o_bd = be;
1540                 op.o_req_dn = *be->be_suffix;
1541                 op.o_req_ndn = *be->be_nsuffix;
1542                 op.ors_scope = LDAP_SCOPE_SUBTREE;
1543                 if ( search_tree( &op, NULL ) != LDAP_SUCCESS ) {
1544                         tl->ecurrent = tl->ecount; /* fail ldif_tool_entry_next() */
1545                         return 0; /* fail ldif_tool_entry_get() */
1546                 }
1547         }
1548         return ldif_tool_entry_next( be );
1549 }
1550
1551 static Entry * ldif_tool_entry_get(BackendDB * be, ID id) {
1552         struct ldif_tool *tl = &((struct ldif_info *) be->be_private)->li_tool;
1553         Entry *e = NULL;
1554
1555         --id;
1556         if ( id < tl->ecount ) {
1557                 e = tl->entries[id];
1558                 tl->entries[id] = NULL;
1559         }
1560         return e;
1561 }
1562
1563 static ID
1564 ldif_tool_entry_put( BackendDB *be, Entry *e, struct berval *text )
1565 {
1566         int rc;
1567         const char *errmsg = NULL;
1568         struct berval path;
1569         char *parentdir;
1570         Operation op = {0};
1571
1572         op.o_bd = be;
1573         rc = ldif_prepare_create( &op, e, &path, &parentdir, &errmsg );
1574         if ( rc == LDAP_SUCCESS ) {
1575                 rc = ldif_write_entry( &op, e, &path, parentdir, &errmsg );
1576
1577                 SLAP_FREE( path.bv_val );
1578                 if ( parentdir != NULL )
1579                         SLAP_FREE( parentdir );
1580                 if ( rc == LDAP_SUCCESS )
1581                         return 1;
1582         }
1583
1584         if ( errmsg == NULL && rc != LDAP_OTHER )
1585                 errmsg = ldap_err2string( rc );
1586         if ( errmsg != NULL )
1587                 snprintf( text->bv_val, text->bv_len, "%s", errmsg );
1588         return NOID;
1589 }
1590
1591
1592 /* Setup */
1593
1594 static int
1595 ldif_back_db_init( BackendDB *be, ConfigReply *cr )
1596 {
1597         struct ldif_info *li;
1598
1599         li = ch_calloc( 1, sizeof(struct ldif_info) );
1600         be->be_private = li;
1601         be->be_cf_ocs = ldifocs;
1602         ldap_pvt_thread_rdwr_init(&li->li_rdwr);
1603         SLAP_DBFLAGS( be ) |= SLAP_DBFLAG_ONE_SUFFIX;
1604         return 0;
1605 }
1606
1607 static int
1608 ldif_back_db_destroy( Backend *be, ConfigReply *cr )
1609 {
1610         struct ldif_info *li = be->be_private;
1611
1612         ch_free(li->li_base_path.bv_val);
1613         ldap_pvt_thread_rdwr_destroy(&li->li_rdwr);
1614         free( be->be_private );
1615         return 0;
1616 }
1617
1618 static int
1619 ldif_back_db_open( Backend *be, ConfigReply *cr)
1620 {
1621         struct ldif_info *li = (struct ldif_info *) be->be_private;
1622         if( BER_BVISEMPTY(&li->li_base_path)) {/* missing base path */
1623                 Debug( LDAP_DEBUG_ANY, "missing base path for back-ldif\n", 0, 0, 0);
1624                 return 1;
1625         }
1626         return 0;
1627 }
1628
1629 int
1630 ldif_back_initialize(
1631                            BackendInfo  *bi
1632                            )
1633 {
1634         static char *controls[] = {
1635                 LDAP_CONTROL_MANAGEDSAIT,
1636                 NULL
1637         };
1638         int rc;
1639
1640         bi->bi_flags |=
1641                 SLAP_BFLAG_INCREMENT |
1642                 SLAP_BFLAG_REFERRALS;
1643
1644         bi->bi_controls = controls;
1645
1646         bi->bi_open = 0;
1647         bi->bi_close = 0;
1648         bi->bi_config = 0;
1649         bi->bi_destroy = 0;
1650
1651         bi->bi_db_init = ldif_back_db_init;
1652         bi->bi_db_config = config_generic_wrapper;
1653         bi->bi_db_open = ldif_back_db_open;
1654         bi->bi_db_close = 0;
1655         bi->bi_db_destroy = ldif_back_db_destroy;
1656
1657         bi->bi_op_bind = ldif_back_bind;
1658         bi->bi_op_unbind = 0;
1659         bi->bi_op_search = ldif_back_search;
1660         bi->bi_op_compare = 0;
1661         bi->bi_op_modify = ldif_back_modify;
1662         bi->bi_op_modrdn = ldif_back_modrdn;
1663         bi->bi_op_add = ldif_back_add;
1664         bi->bi_op_delete = ldif_back_delete;
1665         bi->bi_op_abandon = 0;
1666
1667         bi->bi_extended = 0;
1668
1669         bi->bi_chk_referrals = ldif_back_referrals;
1670
1671         bi->bi_connection_init = 0;
1672         bi->bi_connection_destroy = 0;
1673
1674         bi->bi_entry_get_rw = ldif_back_entry_get;
1675
1676 #if 0   /* NOTE: uncomment to completely disable access control */
1677         bi->bi_access_allowed = slap_access_always_allowed;
1678 #endif
1679
1680         bi->bi_tool_entry_open = ldif_tool_entry_open;
1681         bi->bi_tool_entry_close = ldif_tool_entry_close;
1682         bi->bi_tool_entry_first = ldif_tool_entry_first;
1683         bi->bi_tool_entry_next = ldif_tool_entry_next;
1684         bi->bi_tool_entry_get = ldif_tool_entry_get;
1685         bi->bi_tool_entry_put = ldif_tool_entry_put;
1686         bi->bi_tool_entry_reindex = 0;
1687         bi->bi_tool_sync = 0;
1688         
1689         bi->bi_tool_dn2id_get = 0;
1690         bi->bi_tool_entry_modify = 0;
1691
1692         bi->bi_cf_ocs = ldifocs;
1693
1694         rc = config_register_schema( ldifcfg, ldifocs );
1695         if ( rc ) return rc;
1696         return 0;
1697 }