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