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