]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldif/ldif.c
78d35629980a7698625f1510812b5c87af62863f
[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 = 0;
399
400         while(len > 0) {
401                 writeres = write(fd, spew, len);
402                 if(writeres == -1) {
403                         *save_errno = errno;
404                         if (*save_errno != EINTR)
405                                 break;
406                 }
407                 else {
408                         spew += writeres;
409                         len -= writeres;
410                 }
411         }
412         return writeres;
413 }
414
415 /* Write an entry LDIF file.  Create parentdir first if non-NULL. */
416 static int
417 ldif_write_entry(
418         Operation *op,
419         Entry *e,
420         const struct berval *path,
421         const char *parentdir,
422         const char **text )
423 {
424         int rc = LDAP_OTHER, res, save_errno = 0;
425         int fd, entry_length;
426         char *entry_as_string, *tmpfname;
427
428         if ( op->o_abandon )
429                 return SLAPD_ABANDON;
430
431         if ( parentdir != NULL && mkdir( parentdir, 0750 ) < 0 ) {
432                 save_errno = errno;
433                 Debug( LDAP_DEBUG_ANY, "ldif_write_entry: %s \"%s\": %s\n",
434                         "cannot create parent directory",
435                         parentdir, STRERROR( save_errno ) );
436                 *text = "internal error (cannot create parent directory)";
437                 return rc;
438         }
439
440         tmpfname = ldif_tempname( path );
441         fd = tmpfname == NULL ? -1 : mkstemp( tmpfname );
442         if ( fd < 0 ) {
443                 save_errno = errno;
444                 Debug( LDAP_DEBUG_ANY, "ldif_write_entry: %s for \"%s\": %s\n",
445                         "cannot create file", e->e_dn, STRERROR( save_errno ) );
446                 *text = "internal error (cannot create file)";
447
448         } else {
449                 ber_len_t dn_len = e->e_name.bv_len;
450                 struct berval rdn;
451
452                 /* Only save the RDN onto disk */
453                 dnRdn( &e->e_name, &rdn );
454                 if ( rdn.bv_len != dn_len ) {
455                         e->e_name.bv_val[rdn.bv_len] = '\0';
456                         e->e_name.bv_len = rdn.bv_len;
457                 }
458
459                 res = -2;
460                 ldap_pvt_thread_mutex_lock( &entry2str_mutex );
461                 entry_as_string = entry2str( e, &entry_length );
462                 if ( entry_as_string != NULL )
463                         res = spew_file( fd, entry_as_string, entry_length, &save_errno );
464                 ldap_pvt_thread_mutex_unlock( &entry2str_mutex );
465
466                 /* Restore full DN */
467                 if ( rdn.bv_len != dn_len ) {
468                         e->e_name.bv_val[rdn.bv_len] = ',';
469                         e->e_name.bv_len = dn_len;
470                 }
471
472                 if ( close( fd ) < 0 && res >= 0 ) {
473                         res = -1;
474                         save_errno = errno;
475                 }
476
477                 if ( res >= 0 ) {
478                         if ( move_file( tmpfname, path->bv_val ) == 0 ) {
479                                 Debug( LDAP_DEBUG_TRACE, "ldif_write_entry: "
480                                         "wrote entry \"%s\"\n", e->e_name.bv_val, 0, 0 );
481                                 rc = LDAP_SUCCESS;
482                         } else {
483                                 save_errno = errno;
484                                 Debug( LDAP_DEBUG_ANY, "ldif_write_entry: "
485                                         "could not put entry file for \"%s\" in place: %s\n",
486                                         e->e_name.bv_val, STRERROR( save_errno ), 0 );
487                                 *text = "internal error (could not put entry file in place)";
488                         }
489                 } else if ( res == -1 ) {
490                         Debug( LDAP_DEBUG_ANY, "ldif_write_entry: %s \"%s\": %s\n",
491                                 "write error to", tmpfname, STRERROR( save_errno ) );
492                         *text = "internal error (write error to entry file)";
493                 }
494
495                 if ( rc != LDAP_SUCCESS ) {
496                         unlink( tmpfname );
497                 }
498         }
499
500         if ( tmpfname )
501                 SLAP_FREE( tmpfname );
502         return rc;
503 }
504
505 /*
506  * Read the entry at path, or if entryp==NULL just see if it exists.
507  * pdn and pndn are the parent's DN and normalized DN, or both NULL.
508  * Return an LDAP result code.
509  */
510 static int
511 ldif_read_entry(
512         Operation *op,
513         const char *path,
514         struct berval *pdn,
515         struct berval *pndn,
516         Entry **entryp,
517         const char **text )
518 {
519         int rc;
520         Entry *entry;
521         char *entry_as_string;
522         struct berval rdn;
523
524         /* TODO: Does slapd prevent Abandon of Bind as per rfc4511?
525          * If so we need not check for LDAP_REQ_BIND here.
526          */
527         if ( op->o_abandon && op->o_tag != LDAP_REQ_BIND )
528                 return SLAPD_ABANDON;
529
530         rc = ldif_read_file( path, entryp ? &entry_as_string : NULL );
531
532         switch ( rc ) {
533         case LDAP_SUCCESS:
534                 if ( entryp == NULL )
535                         break;
536                 *entryp = entry = str2entry( entry_as_string );
537                 SLAP_FREE( entry_as_string );
538                 if ( entry == NULL ) {
539                         rc = LDAP_OTHER;
540                         if ( text != NULL )
541                                 *text = "internal error (cannot parse some entry file)";
542                         break;
543                 }
544                 if ( pdn == NULL || BER_BVISEMPTY( pdn ) )
545                         break;
546                 /* Append parent DN to DN from LDIF file */
547                 rdn = entry->e_name;
548                 build_new_dn( &entry->e_name, pdn, &rdn, NULL );
549                 SLAP_FREE( rdn.bv_val );
550                 rdn = entry->e_nname;
551                 build_new_dn( &entry->e_nname, pndn, &rdn, NULL );
552                 SLAP_FREE( rdn.bv_val );
553                 break;
554
555         case LDAP_OTHER:
556                 if ( text != NULL )
557                         *text = entryp
558                                 ? "internal error (cannot read some entry file)"
559                                 : "internal error (cannot stat some entry file)";
560                 break;
561         }
562
563         return rc;
564 }
565
566 /*
567  * Read the operation's entry, or if entryp==NULL just see if it exists.
568  * Return an LDAP result code.  May set *text to a message on failure.
569  * If pathp is non-NULL, set it to the entry filename on success.
570  */
571 static int
572 get_entry(
573         Operation *op,
574         Entry **entryp,
575         struct berval *pathp,
576         const char **text )
577 {
578         int rc;
579         struct berval path, pdn, pndn;
580
581         dnParent( &op->o_req_dn, &pdn );
582         dnParent( &op->o_req_ndn, &pndn );
583         rc = ndn2path( op, &op->o_req_ndn, &path, 0 );
584         if ( rc != LDAP_SUCCESS ) {
585                 goto done;
586         }
587
588         rc = ldif_read_entry( op, path.bv_val, &pdn, &pndn, entryp, text );
589
590         if ( rc == LDAP_SUCCESS && pathp != NULL ) {
591                 *pathp = path;
592         } else {
593                 SLAP_FREE( path.bv_val );
594         }
595  done:
596         return rc;
597 }
598
599
600 /*
601  * RDN-named directory entry, with special handling of "attr={num}val" RDNs.
602  * For sorting, filename "attr=val.ldif" is truncated to "attr="val\0ldif",
603  * and filename "attr={num}val.ldif" to "attr={\0um}val.ldif".
604  * Does not sort escaped chars correctly, would need to un-escape them.
605  */
606 typedef struct bvlist {
607         struct bvlist *next;
608         char *trunc;    /* filename was truncated here */
609         int  inum;              /* num from "attr={num}" in filename, or INT_MIN */
610         char savech;    /* original char at *trunc */
611         /* BVL_NAME(&bvlist) is the filename, allocated after the struct: */
612 #       define BVL_NAME(bvl)     ((char *) ((bvl) + 1))
613 #       define BVL_SIZE(namelen) (sizeof(bvlist) + (namelen) + 1)
614 } bvlist;
615
616 static int
617 ldif_send_entry( Operation *op, SlapReply *rs, Entry *e, int scope )
618 {
619         int rc = LDAP_SUCCESS;
620
621         if ( scope == LDAP_SCOPE_BASE || scope == LDAP_SCOPE_SUBTREE ) {
622                 if ( rs == NULL ) {
623                         /* Save the entry for tool mode */
624                         struct ldif_tool *tl =
625                                 &((struct ldif_info *) op->o_bd->be_private)->li_tool;
626
627                         if ( tl->ecount >= tl->elen ) {
628                                 /* Allocate/grow entries */
629                                 ID elen = tl->elen ? tl->elen * 2 : ENTRY_BUFF_INCREMENT;
630                                 Entry **entries = (Entry **) SLAP_REALLOC( tl->entries,
631                                         sizeof(Entry *) * elen );
632                                 if ( entries == NULL ) {
633                                         Debug( LDAP_DEBUG_ANY,
634                                                 "ldif_send_entry: out of memory\n", 0, 0, 0 );
635                                         rc = LDAP_OTHER;
636                                         goto done;
637                                 }
638                                 tl->elen = elen;
639                                 tl->entries = entries;
640                         }
641                         tl->entries[tl->ecount++] = e;
642                         return rc;
643                 }
644
645                 else if ( !get_manageDSAit( op ) && is_entry_referral( e ) ) {
646                         /* Send a continuation reference.
647                          * (ldif_back_referrals() handles baseobject referrals.)
648                          * Don't check the filter since it's only a candidate.
649                          */
650                         BerVarray refs = get_entry_referrals( op, e );
651                         rs->sr_ref = referral_rewrite( refs, &e->e_name, NULL, scope );
652                         rs->sr_entry = e;
653                         rc = send_search_reference( op, rs );
654                         ber_bvarray_free( rs->sr_ref );
655                         ber_bvarray_free( refs );
656                         rs->sr_ref = NULL;
657                         rs->sr_entry = NULL;
658                 }
659
660                 else if ( test_filter( op, e, op->ors_filter ) == LDAP_COMPARE_TRUE ) {
661                         rs->sr_entry = e;
662                         rs->sr_attrs = op->ors_attrs;
663                         /* Could set REP_ENTRY_MUSTBEFREED too for efficiency,
664                          * but refraining lets us test unFREEable MODIFIABLE
665                          * entries.  Like entries built on the stack.
666                          */
667                         rs->sr_flags = REP_ENTRY_MODIFIABLE;
668                         rc = send_search_entry( op, rs );
669                         rs->sr_entry = NULL;
670                         rs->sr_attrs = NULL;
671                 }
672         }
673
674  done:
675         entry_free( e );
676         return rc;
677 }
678
679 /* Read LDIF directory <path> into <listp>.  Set *fname_maxlenp. */
680 static int
681 ldif_readdir(
682         Operation *op,
683         SlapReply *rs,
684         const struct berval *path,
685         bvlist **listp,
686         ber_len_t *fname_maxlenp )
687 {
688         int rc = LDAP_SUCCESS;
689         DIR *dir_of_path;
690
691         *listp = NULL;
692         *fname_maxlenp = 0;
693
694         dir_of_path = opendir( path->bv_val );
695         if ( dir_of_path == NULL ) {
696                 int save_errno = errno;
697                 struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
698                 int is_rootDSE = (path->bv_len == li->li_base_path.bv_len);
699
700                 /* Absent directory is OK (leaf entry), except the database dir */
701                 if ( is_rootDSE || save_errno != ENOENT ) {
702                         Debug( LDAP_DEBUG_ANY,
703                                 "=> ldif_search_entry: failed to opendir \"%s\": %s\n",
704                                 path->bv_val, STRERROR( save_errno ), 0 );
705                         rc = LDAP_OTHER;
706                         if ( rs != NULL )
707                                 rs->sr_text =
708                                         save_errno != ENOENT ? "internal error (bad directory)"
709                                         : !is_rootDSE ? "internal error (missing directory)"
710                                         : "internal error (database directory does not exist)";
711                 }
712
713         } else {
714                 bvlist *ptr;
715                 struct dirent *dir;
716                 int save_errno = 0;
717
718                 while ( (dir = readdir( dir_of_path )) != NULL ) {
719                         size_t fname_len;
720                         bvlist *bvl, **prev;
721                         char *trunc, *idxp, *endp, *endp2;
722
723                         fname_len = strlen( dir->d_name );
724                         if ( fname_len < STRLENOF( "x=" LDIF )) /* min filename size */
725                                 continue;
726                         if ( strcmp( dir->d_name + fname_len - STRLENOF(LDIF), LDIF ))
727                                 continue;
728
729                         if ( *fname_maxlenp < fname_len )
730                                 *fname_maxlenp = fname_len;
731
732                         bvl = SLAP_MALLOC( BVL_SIZE( fname_len ) );
733                         if ( bvl == NULL ) {
734                                 rc = LDAP_OTHER;
735                                 save_errno = errno;
736                                 break;
737                         }
738                         strcpy( BVL_NAME( bvl ), dir->d_name );
739
740                         /* Make it sortable by ("attr=val" or <preceding {num}, num>) */
741                         trunc = BVL_NAME( bvl ) + fname_len - STRLENOF( LDIF );
742                         if ( (idxp = strchr( BVL_NAME( bvl ) + 2, IX_FSL )) != NULL &&
743                                  (endp = strchr( ++idxp, IX_FSR )) != NULL && endp > idxp &&
744                                  (eq_unsafe || idxp[-2] == '=' || endp + 1 == trunc) )
745                         {
746                                 /* attr={n}val or bconfig.c's "pseudo-indexed" attr=val{n} */
747                                 bvl->inum = strtol( idxp, &endp2, 10 );
748                                 if ( endp2 == endp ) {
749                                         trunc = idxp;
750                                         goto truncate;
751                                 }
752                         }
753                         bvl->inum = INT_MIN;
754                 truncate:
755                         bvl->trunc = trunc;
756                         bvl->savech = *trunc;
757                         *trunc = '\0';
758
759                         /* Insertion sort */
760                         for ( prev = listp; (ptr = *prev) != NULL; prev = &ptr->next ) {
761                                 int cmp = strcmp( BVL_NAME( bvl ), BVL_NAME( ptr ));
762                                 if ( cmp < 0 || (cmp == 0 && bvl->inum < ptr->inum) )
763                                         break;
764                         }
765                         *prev = bvl;
766                         bvl->next = ptr;
767                 }
768
769                 if ( closedir( dir_of_path ) < 0 ) {
770                         save_errno = errno;
771                         rc = LDAP_OTHER;
772                         if ( rs != NULL )
773                                 rs->sr_text = "internal error (bad directory)";
774                 }
775                 if ( rc != LDAP_SUCCESS ) {
776                         Debug( LDAP_DEBUG_ANY, "ldif_search_entry: %s \"%s\": %s\n",
777                                 "error reading directory", path->bv_val,
778                                 STRERROR( save_errno ) );
779                 }
780         }
781
782         return rc;
783 }
784
785 /*
786  * Send an entry, recursively search its children, and free or save it.
787  * Return an LDAP result code.  Parameters:
788  *  op, rs  operation and reply.  rs == NULL for slap tools.
789  *  e       entry to search, or NULL for rootDSE.
790  *  scope   scope for the part of the search from this entry.
791  *  path    LDIF filename -- bv_len and non-directory part are overwritten.
792  */
793 static int
794 ldif_search_entry(
795         Operation *op,
796         SlapReply *rs,
797         Entry *e,
798         int scope,
799         struct berval *path )
800 {
801         int rc = LDAP_SUCCESS;
802         struct berval dn = BER_BVC( "" ), ndn = BER_BVC( "" );
803
804         if ( scope != LDAP_SCOPE_BASE && e != NULL ) {
805                 /* Copy DN/NDN since we send the entry with REP_ENTRY_MODIFIABLE,
806                  * which bconfig.c seems to need.  (TODO: see config_rename_one.)
807                  */
808                 if ( ber_dupbv( &dn,  &e->e_name  ) == NULL ||
809                          ber_dupbv( &ndn, &e->e_nname ) == NULL )
810                 {
811                         Debug( LDAP_DEBUG_ANY,
812                                 "ldif_search_entry: out of memory\n", 0, 0, 0 );
813                         rc = LDAP_OTHER;
814                         goto done;
815                 }
816         }
817
818         /* Send the entry if appropriate, and free or save it */
819         if ( e != NULL )
820                 rc = ldif_send_entry( op, rs, e, scope );
821
822         /* Search the children */
823         if ( scope != LDAP_SCOPE_BASE && rc == LDAP_SUCCESS ) {
824                 bvlist *list, *ptr;
825                 struct berval fpath;    /* becomes child pathname */
826                 char *dir_end;  /* will point past dirname in fpath */
827
828                 ldif2dir_len( *path );
829                 ldif2dir_name( *path );
830                 rc = ldif_readdir( op, rs, path, &list, &fpath.bv_len );
831
832                 if ( list != NULL ) {
833                         const char **text = rs == NULL ? NULL : &rs->sr_text;
834
835                         if ( scope == LDAP_SCOPE_ONELEVEL )
836                                 scope = LDAP_SCOPE_BASE;
837                         else if ( scope == LDAP_SCOPE_SUBORDINATE )
838                                 scope = LDAP_SCOPE_SUBTREE;
839
840                         /* Allocate fpath and fill in directory part */
841                         dir_end = fullpath_alloc( &fpath, path, fpath.bv_len );
842                         if ( dir_end == NULL )
843                                 rc = LDAP_OTHER;
844
845                         do {
846                                 ptr = list;
847
848                                 if ( rc == LDAP_SUCCESS ) {
849                                         *ptr->trunc = ptr->savech;
850                                         FILL_PATH( &fpath, dir_end, BVL_NAME( ptr ));
851
852                                         rc = ldif_read_entry( op, fpath.bv_val, &dn, &ndn,
853                                                 &e, text );
854                                         switch ( rc ) {
855                                         case LDAP_SUCCESS:
856                                                 rc = ldif_search_entry( op, rs, e, scope, &fpath );
857                                                 break;
858                                         case LDAP_NO_SUCH_OBJECT:
859                                                 /* Only the search baseDN may produce noSuchObject. */
860                                                 rc = LDAP_OTHER;
861                                                 if ( rs != NULL )
862                                                         rs->sr_text = "internal error "
863                                                                 "(did someone just remove an entry file?)";
864                                                 Debug( LDAP_DEBUG_ANY, "ldif_search_entry: "
865                                                         "file listed in parent directory does not exist: "
866                                                         "\"%s\"\n", fpath.bv_val, 0, 0 );
867                                                 break;
868                                         }
869                                 }
870
871                                 list = ptr->next;
872                                 SLAP_FREE( ptr );
873                         } while ( list != NULL );
874
875                         if ( !BER_BVISNULL( &fpath ) )
876                                 SLAP_FREE( fpath.bv_val );
877                 }
878         }
879
880  done:
881         if ( !BER_BVISEMPTY( &dn ) )
882                 ber_memfree( dn.bv_val );
883         if ( !BER_BVISEMPTY( &ndn ) )
884                 ber_memfree( ndn.bv_val );
885         return rc;
886 }
887
888 static int
889 search_tree( Operation *op, SlapReply *rs )
890 {
891         int rc = LDAP_SUCCESS;
892         Entry *e = NULL;
893         struct berval path;
894         struct berval pdn, pndn;
895
896         (void) ndn2path( op, &op->o_req_ndn, &path, 1 );
897         if ( !BER_BVISEMPTY( &op->o_req_ndn ) ) {
898                 /* Read baseObject */
899                 dnParent( &op->o_req_dn, &pdn );
900                 dnParent( &op->o_req_ndn, &pndn );
901                 rc = ldif_read_entry( op, path.bv_val, &pdn, &pndn, &e,
902                         rs == NULL ? NULL : &rs->sr_text );
903         }
904         if ( rc == LDAP_SUCCESS )
905                 rc = ldif_search_entry( op, rs, e, op->ors_scope, &path );
906
907         ch_free( path.bv_val );
908         return rc;
909 }
910
911
912 /*
913  * Prepare to create or rename an entry:
914  * Check that the entry does not already exist.
915  * Check that the parent entry exists and can have subordinates,
916  * unless need_dir is NULL or adding the suffix entry.
917  *
918  * Return an LDAP result code.  May set *text to a message on failure.
919  * If success, set *dnpath to LDIF entry path and *need_dir to
920  * (directory must be created ? dirname : NULL).
921  */
922 static int
923 ldif_prepare_create(
924         Operation *op,
925         Entry *e,
926         struct berval *dnpath,
927         char **need_dir,
928         const char **text )
929 {
930         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
931         struct berval *ndn = &e->e_nname;
932         struct berval ppath = BER_BVNULL;
933         struct stat st;
934         Entry *parent = NULL;
935         int rc;
936
937         if ( op->o_abandon )
938                 return SLAPD_ABANDON;
939
940         rc = ndn2path( op, ndn, dnpath, 0 );
941         if ( rc != LDAP_SUCCESS ) {
942                 return rc;
943         }
944
945         if ( stat( dnpath->bv_val, &st ) == 0 ) { /* entry .ldif file */
946                 rc = LDAP_ALREADY_EXISTS;
947
948         } else if ( errno != ENOENT ) {
949                 Debug( LDAP_DEBUG_ANY,
950                         "ldif_prepare_create: cannot stat \"%s\": %s\n",
951                         dnpath->bv_val, STRERROR( errno ), 0 );
952                 rc = LDAP_OTHER;
953                 *text = "internal error (cannot check entry file)";
954
955         } else if ( need_dir != NULL ) {
956                 *need_dir = NULL;
957                 rc = get_parent_path( dnpath, &ppath );
958                 /* If parent dir exists, so does parent .ldif:
959                  * The directory gets created after and removed before the .ldif.
960                  * Except with the database directory, which has no matching entry.
961                  */
962                 if ( rc == LDAP_SUCCESS && stat( ppath.bv_val, &st ) < 0 ) {
963                         rc = errno == ENOENT && ppath.bv_len > li->li_base_path.bv_len
964                                 ? LDAP_NO_SUCH_OBJECT : LDAP_OTHER;
965                 }
966                 switch ( rc ) {
967                 case LDAP_NO_SUCH_OBJECT:
968                         /* No parent dir, check parent .ldif */
969                         dir2ldif_name( ppath );
970                         rc = ldif_read_entry( op, ppath.bv_val, NULL, NULL,
971                                 (op->o_tag != LDAP_REQ_ADD || get_manageDSAit( op )
972                                  ? &parent : NULL),
973                                 text );
974                         switch ( rc ) {
975                         case LDAP_SUCCESS:
976                                 /* Check that parent is not a referral, unless
977                                  * ldif_back_referrals() already checked.
978                                  */
979                                 if ( parent != NULL ) {
980                                         int is_ref = is_entry_referral( parent );
981                                         entry_free( parent );
982                                         if ( is_ref ) {
983                                                 rc = LDAP_AFFECTS_MULTIPLE_DSAS;
984                                                 *text = op->o_tag == LDAP_REQ_MODDN
985                                                         ? "newSuperior is a referral object"
986                                                         : "parent is a referral object";
987                                                 break;
988                                         }
989                                 }
990                                 /* Must create parent directory. */
991                                 ldif2dir_name( ppath );
992                                 *need_dir = ppath.bv_val;
993                                 break;
994                         case LDAP_NO_SUCH_OBJECT:
995                                 *text = op->o_tag == LDAP_REQ_MODDN
996                                         ? "newSuperior object does not exist"
997                                         : "parent does not exist";
998                                 break;
999                         }
1000                         break;
1001                 case LDAP_OTHER:
1002                         Debug( LDAP_DEBUG_ANY,
1003                                 "ldif_prepare_create: cannot stat \"%s\" parent dir: %s\n",
1004                                 ndn->bv_val, STRERROR( errno ), 0 );
1005                         *text = "internal error (cannot stat parent dir)";
1006                         break;
1007                 }
1008                 if ( *need_dir == NULL && ppath.bv_val != NULL )
1009                         SLAP_FREE( ppath.bv_val );
1010         }
1011
1012         if ( rc != LDAP_SUCCESS ) {
1013                 SLAP_FREE( dnpath->bv_val );
1014                 BER_BVZERO( dnpath );
1015         }
1016         return rc;
1017 }
1018
1019 static int
1020 apply_modify_to_entry(
1021         Entry *entry,
1022         Modifications *modlist,
1023         Operation *op,
1024         SlapReply *rs,
1025         char *textbuf )
1026 {
1027         int rc = modlist ? LDAP_UNWILLING_TO_PERFORM : LDAP_SUCCESS;
1028         int is_oc = 0;
1029         Modification *mods;
1030
1031         if (!acl_check_modlist(op, entry, modlist)) {
1032                 return LDAP_INSUFFICIENT_ACCESS;
1033         }
1034
1035         for (; modlist != NULL; modlist = modlist->sml_next) {
1036                 mods = &modlist->sml_mod;
1037
1038                 if ( mods->sm_desc == slap_schema.si_ad_objectClass ) {
1039                         is_oc = 1;
1040                 }
1041                 switch (mods->sm_op) {
1042                 case LDAP_MOD_ADD:
1043                         rc = modify_add_values(entry, mods,
1044                                    get_permissiveModify(op),
1045                                    &rs->sr_text, textbuf,
1046                                    SLAP_TEXT_BUFLEN );
1047                         break;
1048
1049                 case LDAP_MOD_DELETE:
1050                         rc = modify_delete_values(entry, mods,
1051                                 get_permissiveModify(op),
1052                                 &rs->sr_text, textbuf,
1053                                 SLAP_TEXT_BUFLEN );
1054                         break;
1055
1056                 case LDAP_MOD_REPLACE:
1057                         rc = modify_replace_values(entry, mods,
1058                                  get_permissiveModify(op),
1059                                  &rs->sr_text, textbuf,
1060                                  SLAP_TEXT_BUFLEN );
1061                         break;
1062
1063                 case LDAP_MOD_INCREMENT:
1064                         rc = modify_increment_values( entry,
1065                                 mods, get_permissiveModify(op),
1066                                 &rs->sr_text, textbuf,
1067                                 SLAP_TEXT_BUFLEN );
1068                         break;
1069
1070                 case SLAP_MOD_SOFTADD:
1071                         mods->sm_op = LDAP_MOD_ADD;
1072                         rc = modify_add_values(entry, mods,
1073                                    get_permissiveModify(op),
1074                                    &rs->sr_text, textbuf,
1075                                    SLAP_TEXT_BUFLEN );
1076                         mods->sm_op = SLAP_MOD_SOFTADD;
1077                         if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
1078                                 rc = LDAP_SUCCESS;
1079                         }
1080                         break;
1081                 }
1082                 if(rc != LDAP_SUCCESS) break;
1083         }
1084
1085         if ( rc == LDAP_SUCCESS ) {
1086                 rs->sr_text = NULL; /* Needed at least with SLAP_MOD_SOFTADD */
1087                 if ( is_oc ) {
1088                         entry->e_ocflags = 0;
1089                 }
1090                 /* check that the entry still obeys the schema */
1091                 rc = entry_schema_check( op, entry, NULL, 0, 0, NULL,
1092                           &rs->sr_text, textbuf, SLAP_TEXT_BUFLEN );
1093         }
1094
1095         return rc;
1096 }
1097
1098
1099 static int
1100 ldif_back_referrals( Operation *op, SlapReply *rs )
1101 {
1102         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1103         struct berval path, dn = op->o_req_dn, ndn = op->o_req_ndn;
1104         ber_len_t min_dnlen;
1105         Entry *entry = NULL, **entryp;
1106         BerVarray ref;
1107         int rc;
1108
1109         min_dnlen = op->o_bd->be_nsuffix[0].bv_len;
1110         if ( min_dnlen == 0 ) {
1111                 /* Catch root DSE (empty DN), it is not a referral */
1112                 min_dnlen = 1;
1113         }
1114         if ( ndn2path( op, &ndn, &path, 0 ) != LDAP_SUCCESS ) {
1115                 return LDAP_SUCCESS;    /* Root DSE again */
1116         }
1117
1118         entryp = get_manageDSAit( op ) ? NULL : &entry;
1119         ldap_pvt_thread_rdwr_rlock( &li->li_rdwr );
1120
1121         for (;;) {
1122                 dnParent( &dn, &dn );
1123                 dnParent( &ndn, &ndn );
1124                 rc = ldif_read_entry( op, path.bv_val, &dn, &ndn,
1125                         entryp, &rs->sr_text );
1126                 if ( rc != LDAP_NO_SUCH_OBJECT )
1127                         break;
1128
1129                 rc = LDAP_SUCCESS;
1130                 if ( ndn.bv_len < min_dnlen )
1131                         break;
1132                 (void) get_parent_path( &path, NULL );
1133                 dir2ldif_name( path );
1134                 entryp = &entry;
1135         }
1136
1137         ldap_pvt_thread_rdwr_runlock( &li->li_rdwr );
1138         SLAP_FREE( path.bv_val );
1139
1140         if ( entry != NULL ) {
1141                 if ( is_entry_referral( entry ) ) {
1142                         Debug( LDAP_DEBUG_TRACE,
1143                                 "ldif_back_referrals: tag=%lu target=\"%s\" matched=\"%s\"\n",
1144                                 (unsigned long) op->o_tag, op->o_req_dn.bv_val, entry->e_dn );
1145
1146                         ref = get_entry_referrals( op, entry );
1147                         rs->sr_ref = referral_rewrite( ref, &entry->e_name, &op->o_req_dn,
1148                                 op->o_tag == LDAP_REQ_SEARCH ?
1149                                 op->ors_scope : LDAP_SCOPE_DEFAULT );
1150                         ber_bvarray_free( ref );
1151
1152                         if ( rs->sr_ref != NULL ) {
1153                                 /* send referral */
1154                                 rc = rs->sr_err = LDAP_REFERRAL;
1155                                 rs->sr_matched = entry->e_dn;
1156                                 send_ldap_result( op, rs );
1157                                 ber_bvarray_free( rs->sr_ref );
1158                                 rs->sr_ref = NULL;
1159                         } else {
1160                                 rc = LDAP_OTHER;
1161                                 rs->sr_text = "bad referral object";
1162                         }
1163                         rs->sr_matched = NULL;
1164                 }
1165
1166                 entry_free( entry );
1167         }
1168
1169         return rc;
1170 }
1171
1172
1173 /* LDAP operations */
1174
1175 static int
1176 ldif_back_bind( Operation *op, SlapReply *rs )
1177 {
1178         struct ldif_info *li;
1179         Attribute *a;
1180         AttributeDescription *password = slap_schema.si_ad_userPassword;
1181         int return_val;
1182         Entry *entry = NULL;
1183
1184         switch ( be_rootdn_bind( op, rs ) ) {
1185         case SLAP_CB_CONTINUE:
1186                 break;
1187
1188         default:
1189                 /* in case of success, front end will send result;
1190                  * otherwise, be_rootdn_bind() did */
1191                 return rs->sr_err;
1192         }
1193
1194         li = (struct ldif_info *) op->o_bd->be_private;
1195         ldap_pvt_thread_rdwr_rlock(&li->li_rdwr);
1196         return_val = get_entry(op, &entry, NULL, NULL);
1197
1198         /* no object is found for them */
1199         if(return_val != LDAP_SUCCESS) {
1200                 rs->sr_err = return_val = LDAP_INVALID_CREDENTIALS;
1201                 goto return_result;
1202         }
1203
1204         /* they don't have userpassword */
1205         if((a = attr_find(entry->e_attrs, password)) == NULL) {
1206                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1207                 return_val = 1;
1208                 goto return_result;
1209         }
1210
1211         /* authentication actually failed */
1212         if(slap_passwd_check(op, entry, a, &op->oq_bind.rb_cred,
1213                              &rs->sr_text) != 0) {
1214                 rs->sr_err = LDAP_INVALID_CREDENTIALS;
1215                 return_val = 1;
1216                 goto return_result;
1217         }
1218
1219         /* let the front-end send success */
1220         return_val = LDAP_SUCCESS;
1221
1222  return_result:
1223         ldap_pvt_thread_rdwr_runlock(&li->li_rdwr);
1224         if(return_val != LDAP_SUCCESS)
1225                 send_ldap_result( op, rs );
1226         if(entry != NULL)
1227                 entry_free(entry);
1228         return return_val;
1229 }
1230
1231 static int
1232 ldif_back_search( Operation *op, SlapReply *rs )
1233 {
1234         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1235
1236         ldap_pvt_thread_rdwr_rlock(&li->li_rdwr);
1237         rs->sr_err = search_tree( op, rs );
1238         ldap_pvt_thread_rdwr_runlock(&li->li_rdwr);
1239         send_ldap_result(op, rs);
1240
1241         return rs->sr_err;
1242 }
1243
1244 static int
1245 ldif_back_add( Operation *op, SlapReply *rs )
1246 {
1247         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1248         Entry * e = op->ora_e;
1249         struct berval path;
1250         char *parentdir;
1251         char textbuf[SLAP_TEXT_BUFLEN];
1252         int rc;
1253
1254         Debug( LDAP_DEBUG_TRACE, "ldif_back_add: \"%s\"\n", e->e_dn, 0, 0 );
1255
1256         rc = entry_schema_check( op, e, NULL, 0, 1, NULL,
1257                 &rs->sr_text, textbuf, sizeof( textbuf ) );
1258         if ( rc != LDAP_SUCCESS )
1259                 goto send_res;
1260
1261         rc = slap_add_opattrs( op, &rs->sr_text, textbuf, sizeof( textbuf ), 1 );
1262         if ( rc != LDAP_SUCCESS )
1263                 goto send_res;
1264
1265         ldap_pvt_thread_mutex_lock( &li->li_modop_mutex );
1266
1267         rc = ldif_prepare_create( op, e, &path, &parentdir, &rs->sr_text );
1268         if ( rc == LDAP_SUCCESS ) {
1269                 ldap_pvt_thread_rdwr_wlock( &li->li_rdwr );
1270                 rc = ldif_write_entry( op, e, &path, parentdir, &rs->sr_text );
1271                 ldap_pvt_thread_rdwr_wunlock( &li->li_rdwr );
1272
1273                 SLAP_FREE( path.bv_val );
1274                 if ( parentdir != NULL )
1275                         SLAP_FREE( parentdir );
1276         }
1277
1278         ldap_pvt_thread_mutex_unlock( &li->li_modop_mutex );
1279
1280  send_res:
1281         rs->sr_err = rc;
1282         Debug( LDAP_DEBUG_TRACE, "ldif_back_add: err: %d text: %s\n",
1283                 rc, rs->sr_text ? rs->sr_text : "", 0 );
1284         send_ldap_result( op, rs );
1285         slap_graduate_commit_csn( op );
1286         rs->sr_text = NULL;     /* remove possible pointer to textbuf */
1287         return rs->sr_err;
1288 }
1289
1290 static int
1291 ldif_back_modify( Operation *op, SlapReply *rs )
1292 {
1293         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1294         Modifications * modlst = op->orm_modlist;
1295         struct berval path;
1296         Entry *entry;
1297         char textbuf[SLAP_TEXT_BUFLEN];
1298         int rc;
1299
1300         slap_mods_opattrs( op, &op->orm_modlist, 1 );
1301
1302         ldap_pvt_thread_mutex_lock( &li->li_modop_mutex );
1303
1304         rc = get_entry( op, &entry, &path, &rs->sr_text );
1305         if ( rc == LDAP_SUCCESS ) {
1306                 rc = apply_modify_to_entry( entry, modlst, op, rs, textbuf );
1307                 if ( rc == LDAP_SUCCESS ) {
1308                         ldap_pvt_thread_rdwr_wlock( &li->li_rdwr );
1309                         rc = ldif_write_entry( op, entry, &path, NULL, &rs->sr_text );
1310                         ldap_pvt_thread_rdwr_wunlock( &li->li_rdwr );
1311                 }
1312
1313                 entry_free( entry );
1314                 SLAP_FREE( path.bv_val );
1315         }
1316
1317         ldap_pvt_thread_mutex_unlock( &li->li_modop_mutex );
1318
1319         rs->sr_err = rc;
1320         send_ldap_result( op, rs );
1321         slap_graduate_commit_csn( op );
1322         rs->sr_text = NULL;     /* remove possible pointer to textbuf */
1323         return rs->sr_err;
1324 }
1325
1326 static int
1327 ldif_back_delete( Operation *op, SlapReply *rs )
1328 {
1329         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1330         struct berval path;
1331         int rc = LDAP_SUCCESS;
1332
1333         if ( BER_BVISEMPTY( &op->o_csn )) {
1334                 struct berval csn;
1335                 char csnbuf[LDAP_PVT_CSNSTR_BUFSIZE];
1336
1337                 csn.bv_val = csnbuf;
1338                 csn.bv_len = sizeof( csnbuf );
1339                 slap_get_csn( op, &csn, 1 );
1340         }
1341
1342         ldap_pvt_thread_mutex_lock( &li->li_modop_mutex );
1343         ldap_pvt_thread_rdwr_wlock( &li->li_rdwr );
1344         if ( op->o_abandon ) {
1345                 rc = SLAPD_ABANDON;
1346                 goto done;
1347         }
1348
1349         rc = ndn2path( op, &op->o_req_ndn, &path, 0 );
1350         if ( rc != LDAP_SUCCESS ) {
1351                 goto done;
1352         }
1353
1354         ldif2dir_len( path );
1355         ldif2dir_name( path );
1356         if ( rmdir( path.bv_val ) < 0 ) {
1357                 switch ( errno ) {
1358                 case ENOTEMPTY:
1359                         rc = LDAP_NOT_ALLOWED_ON_NONLEAF;
1360                         break;
1361                 case ENOENT:
1362                         /* is leaf, go on */
1363                         break;
1364                 default:
1365                         rc = LDAP_OTHER;
1366                         rs->sr_text = "internal error (cannot delete subtree directory)";
1367                         break;
1368                 }
1369         }
1370
1371         if ( rc == LDAP_SUCCESS ) {
1372                 dir2ldif_name( path );
1373                 if ( unlink( path.bv_val ) < 0 ) {
1374                         rc = LDAP_NO_SUCH_OBJECT;
1375                         if ( errno != ENOENT ) {
1376                                 rc = LDAP_OTHER;
1377                                 rs->sr_text = "internal error (cannot delete entry file)";
1378                         }
1379                 }
1380         }
1381
1382         if ( rc == LDAP_OTHER ) {
1383                 Debug( LDAP_DEBUG_ANY, "ldif_back_delete: %s \"%s\": %s\n",
1384                         "cannot delete", path.bv_val, STRERROR( errno ) );
1385         }
1386
1387         SLAP_FREE( path.bv_val );
1388  done:
1389         ldap_pvt_thread_rdwr_wunlock( &li->li_rdwr );
1390         ldap_pvt_thread_mutex_unlock( &li->li_modop_mutex );
1391         rs->sr_err = rc;
1392         send_ldap_result( op, rs );
1393         slap_graduate_commit_csn( op );
1394         return rs->sr_err;
1395 }
1396
1397
1398 static int
1399 ldif_move_entry(
1400         Operation *op,
1401         Entry *entry,
1402         int same_ndn,
1403         struct berval *oldpath,
1404         const char **text )
1405 {
1406         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1407         struct berval newpath;
1408         char *parentdir = NULL, *trash;
1409         int rc, rename_res;
1410
1411         if ( same_ndn ) {
1412                 rc = LDAP_SUCCESS;
1413                 newpath = *oldpath;
1414         } else {
1415                 rc = ldif_prepare_create( op, entry, &newpath,
1416                         op->orr_newSup ? &parentdir : NULL, text );
1417         }
1418
1419         if ( rc == LDAP_SUCCESS ) {
1420                 ldap_pvt_thread_rdwr_wlock( &li->li_rdwr );
1421
1422                 rc = ldif_write_entry( op, entry, &newpath, parentdir, text );
1423                 if ( rc == LDAP_SUCCESS && !same_ndn ) {
1424                         trash = oldpath->bv_val; /* will be .ldif file to delete */
1425                         ldif2dir_len( newpath );
1426                         ldif2dir_len( *oldpath );
1427                         /* Move subdir before deleting old entry,
1428                          * so .ldif always exists if subdir does.
1429                          */
1430                         ldif2dir_name( newpath );
1431                         ldif2dir_name( *oldpath );
1432                         rename_res = move_dir( oldpath->bv_val, newpath.bv_val );
1433                         if ( rename_res != 0 && errno != ENOENT ) {
1434                                 rc = LDAP_OTHER;
1435                                 *text = "internal error (cannot move this subtree)";
1436                                 trash = newpath.bv_val;
1437                         }
1438
1439                         /* Delete old entry, or if error undo change */
1440                         for (;;) {
1441                                 dir2ldif_name( newpath );
1442                                 dir2ldif_name( *oldpath );
1443                                 if ( unlink( trash ) == 0 )
1444                                         break;
1445                                 if ( rc == LDAP_SUCCESS ) {
1446                                         /* Prepare to undo change and return failure */
1447                                         rc = LDAP_OTHER;
1448                                         *text = "internal error (cannot move this entry)";
1449                                         trash = newpath.bv_val;
1450                                         if ( rename_res != 0 )
1451                                                 continue;
1452                                         /* First move subdirectory back */
1453                                         ldif2dir_name( newpath );
1454                                         ldif2dir_name( *oldpath );
1455                                         if ( move_dir( newpath.bv_val, oldpath->bv_val ) == 0 )
1456                                                 continue;
1457                                 }
1458                                 *text = "added new but couldn't delete old entry!";
1459                                 break;
1460                         }
1461
1462                         if ( rc != LDAP_SUCCESS ) {
1463                                 char s[128];
1464                                 snprintf( s, sizeof s, "%s (%s)", *text, STRERROR( errno ));
1465                                 Debug( LDAP_DEBUG_ANY,
1466                                         "ldif_move_entry: %s: \"%s\" -> \"%s\"\n",
1467                                         s, op->o_req_dn.bv_val, entry->e_dn );
1468                         }
1469                 }
1470
1471                 ldap_pvt_thread_rdwr_wunlock( &li->li_rdwr );
1472                 if ( !same_ndn )
1473                         SLAP_FREE( newpath.bv_val );
1474                 if ( parentdir != NULL )
1475                         SLAP_FREE( parentdir );
1476         }
1477
1478         return rc;
1479 }
1480
1481 static int
1482 ldif_back_modrdn( Operation *op, SlapReply *rs )
1483 {
1484         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1485         struct berval new_dn = BER_BVNULL, new_ndn = BER_BVNULL;
1486         struct berval p_dn, old_path;
1487         Entry *entry;
1488         char textbuf[SLAP_TEXT_BUFLEN];
1489         int rc, same_ndn;
1490
1491         slap_mods_opattrs( op, &op->orr_modlist, 1 );
1492
1493         ldap_pvt_thread_mutex_lock( &li->li_modop_mutex );
1494
1495         rc = get_entry( op, &entry, &old_path, &rs->sr_text );
1496         if ( rc == LDAP_SUCCESS ) {
1497                 /* build new dn, and new ndn for the entry */
1498                 if ( op->oq_modrdn.rs_newSup != NULL ) {
1499                         p_dn = *op->oq_modrdn.rs_newSup;
1500                 } else {
1501                         dnParent( &entry->e_name, &p_dn );
1502                 }
1503                 build_new_dn( &new_dn, &p_dn, &op->oq_modrdn.rs_newrdn, NULL );
1504                 dnNormalize( 0, NULL, NULL, &new_dn, &new_ndn, NULL );
1505                 same_ndn = !ber_bvcmp( &entry->e_nname, &new_ndn );
1506                 ber_memfree_x( entry->e_name.bv_val, NULL );
1507                 ber_memfree_x( entry->e_nname.bv_val, NULL );
1508                 entry->e_name = new_dn;
1509                 entry->e_nname = new_ndn;
1510
1511                 /* perform the modifications */
1512                 rc = apply_modify_to_entry( entry, op->orr_modlist, op, rs, textbuf );
1513                 if ( rc == LDAP_SUCCESS )
1514                         rc = ldif_move_entry( op, entry, same_ndn, &old_path,
1515                                 &rs->sr_text );
1516
1517                 entry_free( entry );
1518                 SLAP_FREE( old_path.bv_val );
1519         }
1520
1521         ldap_pvt_thread_mutex_unlock( &li->li_modop_mutex );
1522         rs->sr_err = rc;
1523         send_ldap_result( op, rs );
1524         slap_graduate_commit_csn( op );
1525         rs->sr_text = NULL;     /* remove possible pointer to textbuf */
1526         return rs->sr_err;
1527 }
1528
1529
1530 /* Return LDAP_SUCCESS IFF we retrieve the specified entry. */
1531 static int
1532 ldif_back_entry_get(
1533         Operation *op,
1534         struct berval *ndn,
1535         ObjectClass *oc,
1536         AttributeDescription *at,
1537         int rw,
1538         Entry **e )
1539 {
1540         struct ldif_info *li = (struct ldif_info *) op->o_bd->be_private;
1541         struct berval op_dn = op->o_req_dn, op_ndn = op->o_req_ndn;
1542         int rc;
1543
1544         assert( ndn != NULL );
1545         assert( !BER_BVISNULL( ndn ) );
1546
1547         ldap_pvt_thread_rdwr_rlock( &li->li_rdwr );
1548         op->o_req_dn = *ndn;
1549         op->o_req_ndn = *ndn;
1550         rc = get_entry( op, e, NULL, NULL );
1551         op->o_req_dn = op_dn;
1552         op->o_req_ndn = op_ndn;
1553         ldap_pvt_thread_rdwr_runlock( &li->li_rdwr );
1554
1555         if ( rc == LDAP_SUCCESS && oc && !is_entry_objectclass_or_sub( *e, oc ) ) {
1556                 rc = LDAP_NO_SUCH_ATTRIBUTE;
1557                 entry_free( *e );
1558                 *e = NULL;
1559         }
1560
1561         return rc;
1562 }
1563
1564
1565 /* Slap tools */
1566
1567 static int
1568 ldif_tool_entry_open( BackendDB *be, int mode )
1569 {
1570         struct ldif_tool *tl = &((struct ldif_info *) be->be_private)->li_tool;
1571
1572         tl->ecurrent = 0;
1573         return 0;
1574 }
1575
1576 static int
1577 ldif_tool_entry_close( BackendDB *be )
1578 {
1579         struct ldif_tool *tl = &((struct ldif_info *) be->be_private)->li_tool;
1580         Entry **entries = tl->entries;
1581         ID i;
1582
1583         for ( i = tl->ecount; i--; )
1584                 if ( entries[i] )
1585                         entry_free( entries[i] );
1586         SLAP_FREE( entries );
1587         tl->entries = NULL;
1588         tl->ecount = tl->elen = 0;
1589         return 0;
1590 }
1591
1592 static ID
1593 ldif_tool_entry_next( BackendDB *be )
1594 {
1595         struct ldif_tool *tl = &((struct ldif_info *) be->be_private)->li_tool;
1596
1597         do {
1598                 Entry *e = tl->entries[ tl->ecurrent ];
1599
1600                 if ( tl->ecurrent >= tl->ecount ) {
1601                         return NOID;
1602                 }
1603
1604                 ++tl->ecurrent;
1605
1606                 if ( tl->tl_base && !dnIsSuffixScope( &e->e_nname, tl->tl_base, tl->tl_scope ) ) {
1607                         continue;
1608                 }
1609
1610                 if ( tl->tl_filter && test_filter( NULL, e, tl->tl_filter  ) != LDAP_COMPARE_TRUE ) {
1611                         continue;
1612                 }
1613
1614                 break;
1615         } while ( 1 );
1616
1617         return tl->ecurrent;
1618 }
1619
1620 static ID
1621 ldif_tool_entry_first_x( BackendDB *be, struct berval *base, int scope, Filter *f )
1622 {
1623         struct ldif_tool *tl = &((struct ldif_info *) be->be_private)->li_tool;
1624
1625         tl->tl_base = base;
1626         tl->tl_scope = scope;
1627         tl->tl_filter = f;
1628
1629         if ( tl->entries == NULL ) {
1630                 Operation op = {0};
1631
1632                 op.o_bd = be;
1633                 op.o_req_dn = *be->be_suffix;
1634                 op.o_req_ndn = *be->be_nsuffix;
1635                 op.ors_scope = LDAP_SCOPE_SUBTREE;
1636                 if ( search_tree( &op, NULL ) != LDAP_SUCCESS ) {
1637                         tl->ecurrent = tl->ecount; /* fail ldif_tool_entry_next() */
1638                         return 0; /* fail ldif_tool_entry_get() */
1639                 }
1640         }
1641         return ldif_tool_entry_next( be );
1642 }
1643
1644 static Entry *
1645 ldif_tool_entry_get( BackendDB *be, ID id )
1646 {
1647         struct ldif_tool *tl = &((struct ldif_info *) be->be_private)->li_tool;
1648         Entry *e = NULL;
1649
1650         --id;
1651         if ( id < tl->ecount ) {
1652                 e = tl->entries[id];
1653                 tl->entries[id] = NULL;
1654         }
1655         return e;
1656 }
1657
1658 static ID
1659 ldif_tool_entry_put( BackendDB *be, Entry *e, struct berval *text )
1660 {
1661         int rc;
1662         const char *errmsg = NULL;
1663         struct berval path;
1664         char *parentdir;
1665         Operation op = {0};
1666
1667         op.o_bd = be;
1668         rc = ldif_prepare_create( &op, e, &path, &parentdir, &errmsg );
1669         if ( rc == LDAP_SUCCESS ) {
1670                 rc = ldif_write_entry( &op, e, &path, parentdir, &errmsg );
1671
1672                 SLAP_FREE( path.bv_val );
1673                 if ( parentdir != NULL )
1674                         SLAP_FREE( parentdir );
1675                 if ( rc == LDAP_SUCCESS )
1676                         return 1;
1677         }
1678
1679         if ( errmsg == NULL && rc != LDAP_OTHER )
1680                 errmsg = ldap_err2string( rc );
1681         if ( errmsg != NULL )
1682                 snprintf( text->bv_val, text->bv_len, "%s", errmsg );
1683         return NOID;
1684 }
1685
1686
1687 /* Setup */
1688
1689 static int
1690 ldif_back_db_init( BackendDB *be, ConfigReply *cr )
1691 {
1692         struct ldif_info *li;
1693
1694         li = ch_calloc( 1, sizeof(struct ldif_info) );
1695         be->be_private = li;
1696         be->be_cf_ocs = ldifocs;
1697         ldap_pvt_thread_mutex_init( &li->li_modop_mutex );
1698         ldap_pvt_thread_rdwr_init( &li->li_rdwr );
1699         SLAP_DBFLAGS( be ) |= SLAP_DBFLAG_ONE_SUFFIX;
1700         return 0;
1701 }
1702
1703 static int
1704 ldif_back_db_destroy( Backend *be, ConfigReply *cr )
1705 {
1706         struct ldif_info *li = be->be_private;
1707
1708         ch_free( li->li_base_path.bv_val );
1709         ldap_pvt_thread_rdwr_destroy( &li->li_rdwr );
1710         ldap_pvt_thread_mutex_destroy( &li->li_modop_mutex );
1711         free( be->be_private );
1712         return 0;
1713 }
1714
1715 static int
1716 ldif_back_db_open( Backend *be, ConfigReply *cr )
1717 {
1718         struct ldif_info *li = (struct ldif_info *) be->be_private;
1719         if( BER_BVISEMPTY(&li->li_base_path)) {/* missing base path */
1720                 Debug( LDAP_DEBUG_ANY, "missing base path for back-ldif\n", 0, 0, 0);
1721                 return 1;
1722         }
1723         return 0;
1724 }
1725
1726 int
1727 ldif_back_initialize( BackendInfo *bi )
1728 {
1729         static char *controls[] = {
1730                 LDAP_CONTROL_MANAGEDSAIT,
1731                 NULL
1732         };
1733         int rc;
1734
1735         bi->bi_flags |=
1736                 SLAP_BFLAG_INCREMENT |
1737                 SLAP_BFLAG_REFERRALS;
1738
1739         bi->bi_controls = controls;
1740
1741         bi->bi_open = 0;
1742         bi->bi_close = 0;
1743         bi->bi_config = 0;
1744         bi->bi_destroy = 0;
1745
1746         bi->bi_db_init = ldif_back_db_init;
1747         bi->bi_db_config = config_generic_wrapper;
1748         bi->bi_db_open = ldif_back_db_open;
1749         bi->bi_db_close = 0;
1750         bi->bi_db_destroy = ldif_back_db_destroy;
1751
1752         bi->bi_op_bind = ldif_back_bind;
1753         bi->bi_op_unbind = 0;
1754         bi->bi_op_search = ldif_back_search;
1755         bi->bi_op_compare = 0;
1756         bi->bi_op_modify = ldif_back_modify;
1757         bi->bi_op_modrdn = ldif_back_modrdn;
1758         bi->bi_op_add = ldif_back_add;
1759         bi->bi_op_delete = ldif_back_delete;
1760         bi->bi_op_abandon = 0;
1761
1762         bi->bi_extended = 0;
1763
1764         bi->bi_chk_referrals = ldif_back_referrals;
1765
1766         bi->bi_connection_init = 0;
1767         bi->bi_connection_destroy = 0;
1768
1769         bi->bi_entry_get_rw = ldif_back_entry_get;
1770
1771 #if 0   /* NOTE: uncomment to completely disable access control */
1772         bi->bi_access_allowed = slap_access_always_allowed;
1773 #endif
1774
1775         bi->bi_tool_entry_open = ldif_tool_entry_open;
1776         bi->bi_tool_entry_close = ldif_tool_entry_close;
1777         bi->bi_tool_entry_first = backend_tool_entry_first;
1778         bi->bi_tool_entry_first_x = ldif_tool_entry_first_x;
1779         bi->bi_tool_entry_next = ldif_tool_entry_next;
1780         bi->bi_tool_entry_get = ldif_tool_entry_get;
1781         bi->bi_tool_entry_put = ldif_tool_entry_put;
1782         bi->bi_tool_entry_reindex = 0;
1783         bi->bi_tool_sync = 0;
1784
1785         bi->bi_tool_dn2id_get = 0;
1786         bi->bi_tool_entry_modify = 0;
1787
1788         bi->bi_cf_ocs = ldifocs;
1789
1790         rc = config_register_schema( ldifcfg, ldifocs );
1791         if ( rc ) return rc;
1792         return 0;
1793 }