a2e448846a0c336e1762c640d0d0bed31d20796d
[metze/samba/wip.git] / lib / ldb / common / ldb_ldif.c
1 /* 
2    ldb database library
3
4    Copyright (C) Andrew Tridgell  2004
5
6      ** NOTE! The following LGPL license applies to the ldb
7      ** library. This does NOT imply that all of Samba is released
8      ** under the LGPL
9    
10    This library is free software; you can redistribute it and/or
11    modify it under the terms of the GNU Lesser General Public
12    License as published by the Free Software Foundation; either
13    version 3 of the License, or (at your option) any later version.
14
15    This library is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    Lesser General Public License for more details.
19
20    You should have received a copy of the GNU Lesser General Public
21    License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 */
23
24 /*
25  *  Name: ldb
26  *
27  *  Component: ldif routines
28  *
29  *  Description: ldif pack/unpack routines
30  *
31  *  Author: Andrew Tridgell
32  */
33
34 /*
35   see RFC2849 for the LDIF format definition
36 */
37
38 #include "ldb_private.h"
39 #include "system/locale.h"
40
41 /*
42   
43 */
44 static int ldb_read_data_file(TALLOC_CTX *mem_ctx, struct ldb_val *value)
45 {
46         struct stat statbuf;
47         char *buf;
48         int count, size, bytes;
49         int ret;
50         int f;
51         const char *fname = (const char *)value->data;
52
53         if (strncmp(fname, "file://", 7) != 0) {
54                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
55         }
56         fname += 7;
57
58         f = open(fname, O_RDONLY);
59         if (f == -1) {
60                 return -1;
61         }
62
63         if (fstat(f, &statbuf) != 0) {
64                 ret = -1;
65                 goto done;
66         }
67
68         if (statbuf.st_size == 0) {
69                 ret = -1;
70                 goto done;
71         }
72
73         value->data = (uint8_t *)talloc_size(mem_ctx, statbuf.st_size + 1);
74         if (value->data == NULL) {
75                 ret = -1;
76                 goto done;
77         }
78         value->data[statbuf.st_size] = 0;
79
80         count = 0;
81         size = statbuf.st_size;
82         buf = (char *)value->data;
83         while (count < statbuf.st_size) {
84                 bytes = read(f, buf, size);
85                 if (bytes == -1) {
86                         talloc_free(value->data);
87                         ret = -1;
88                         goto done;
89                 }
90                 count += bytes;
91                 buf += bytes;
92                 size -= bytes;
93         }
94
95         value->length = statbuf.st_size;
96         ret = statbuf.st_size;
97
98 done:
99         close(f);
100         return ret;
101 }
102
103 /*
104   this base64 decoder was taken from jitterbug (written by tridge).
105   we might need to replace it with a new version
106 */
107 int ldb_base64_decode(char *s)
108 {
109         const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
110         int bit_offset=0, byte_offset, idx, i, n;
111         uint8_t *d = (uint8_t *)s;
112         char *p=NULL;
113
114         n=i=0;
115
116         while (*s && (p=strchr(b64,*s))) {
117                 idx = (int)(p - b64);
118                 byte_offset = (i*6)/8;
119                 bit_offset = (i*6)%8;
120                 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
121                 if (bit_offset < 3) {
122                         d[byte_offset] |= (idx << (2-bit_offset));
123                         n = byte_offset+1;
124                 } else {
125                         d[byte_offset] |= (idx >> (bit_offset-2));
126                         d[byte_offset+1] = 0;
127                         d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
128                         n = byte_offset+2;
129                 }
130                 s++; i++;
131         }
132         if (bit_offset >= 3) {
133                 n--;
134         }
135
136         if (*s && !p) {
137                 /* the only termination allowed */
138                 if (*s != '=') {
139                         return -1;
140                 }
141         }
142
143         /* null terminate */
144         d[n] = 0;
145         return n;
146 }
147
148
149 /*
150   encode as base64
151   caller frees
152 */
153 char *ldb_base64_encode(TALLOC_CTX *mem_ctx, const char *buf, int len)
154 {
155         const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
156         int bit_offset, byte_offset, idx, i;
157         const uint8_t *d = (const uint8_t *)buf;
158         int bytes = (len*8 + 5)/6, pad_bytes = (bytes % 4) ? 4 - (bytes % 4) : 0;
159         char *out;
160
161         out = talloc_array(mem_ctx, char, bytes+pad_bytes+1);
162         if (!out) return NULL;
163
164         for (i=0;i<bytes;i++) {
165                 byte_offset = (i*6)/8;
166                 bit_offset = (i*6)%8;
167                 if (bit_offset < 3) {
168                         idx = (d[byte_offset] >> (2-bit_offset)) & 0x3F;
169                 } else {
170                         idx = (d[byte_offset] << (bit_offset-2)) & 0x3F;
171                         if (byte_offset+1 < len) {
172                                 idx |= (d[byte_offset+1] >> (8-(bit_offset-2)));
173                         }
174                 }
175                 out[i] = b64[idx];
176         }
177
178         for (;i<bytes+pad_bytes;i++)
179                 out[i] = '=';
180         out[i] = 0;
181
182         return out;
183 }
184
185 /*
186   see if a buffer should be base64 encoded
187 */
188 int ldb_should_b64_encode(struct ldb_context *ldb, const struct ldb_val *val)
189 {
190         unsigned int i;
191         uint8_t *p = val->data;
192
193         if (val->length == 0) {
194                 return 0;
195         }
196
197         if (p[0] == ' ' || p[0] == ':') {
198                 return 1;
199         }
200
201         for (i=0; i<val->length; i++) {
202                 if (!isprint(p[i]) || p[i] == '\n') {
203                         return 1;
204                 }
205         }
206         return 0;
207 }
208
209 /* this macro is used to handle the return checking on fprintf_fn() */
210 #define CHECK_RET do { if (ret < 0) return ret; total += ret; } while (0)
211
212 /*
213   write a line folded string onto a file
214 */
215 static int fold_string(int (*fprintf_fn)(void *, const char *, ...), void *private_data,
216                         const char *buf, size_t length, int start_pos)
217 {
218         size_t i;
219         int total=0, ret;
220
221         for (i=0;i<length;i++) {
222                 ret = fprintf_fn(private_data, "%c", buf[i]);
223                 CHECK_RET;
224                 if (i != (length-1) && (i + start_pos) % 77 == 0) {
225                         ret = fprintf_fn(private_data, "\n ");
226                         CHECK_RET;
227                 }
228         }
229
230         return total;
231 }
232
233 #undef CHECK_RET
234
235 /*
236   encode as base64 to a file
237 */
238 static int base64_encode_f(struct ldb_context *ldb,
239                            int (*fprintf_fn)(void *, const char *, ...), 
240                            void *private_data,
241                            const char *buf, int len, int start_pos)
242 {
243         char *b = ldb_base64_encode(ldb, buf, len);
244         int ret;
245
246         if (!b) {
247                 return -1;
248         }
249
250         ret = fold_string(fprintf_fn, private_data, b, strlen(b), start_pos);
251
252         talloc_free(b);
253         return ret;
254 }
255
256
257 static const struct {
258         const char *name;
259         enum ldb_changetype changetype;
260 } ldb_changetypes[] = {
261         {"add",    LDB_CHANGETYPE_ADD},
262         {"delete", LDB_CHANGETYPE_DELETE},
263         {"modify", LDB_CHANGETYPE_MODIFY},
264         {"modrdn", LDB_CHANGETYPE_MODRDN},
265         {"moddn",  LDB_CHANGETYPE_MODRDN},
266         {NULL, 0}
267 };
268
269 /* this macro is used to handle the return checking on fprintf_fn() */
270 #define CHECK_RET do { if (ret < 0) { talloc_free(mem_ctx); return ret; } total += ret; } while (0)
271
272 /*
273   write to ldif, using a caller supplied write method, and only printing secrets if we are not in a trace
274 */
275 static int ldb_ldif_write_trace(struct ldb_context *ldb,
276                                 int (*fprintf_fn)(void *, const char *, ...), 
277                                 void *private_data,
278                                 const struct ldb_ldif *ldif, 
279                                 bool in_trace)
280 {
281         TALLOC_CTX *mem_ctx;
282         unsigned int i, j;
283         int total=0, ret;
284         char *p;
285         const struct ldb_message *msg;
286         const char * const * secret_attributes = ldb_get_opaque(ldb, LDB_SECRET_ATTRIBUTE_LIST_OPAQUE);
287
288         mem_ctx = talloc_named_const(NULL, 0, "ldb_ldif_write");
289
290         msg = ldif->msg;
291         p = ldb_dn_get_extended_linearized(mem_ctx, msg->dn, 1);
292         ret = fprintf_fn(private_data, "dn: %s\n", p);
293         talloc_free(p);
294         CHECK_RET;
295
296         if (ldif->changetype != LDB_CHANGETYPE_NONE) {
297                 for (i=0;ldb_changetypes[i].name;i++) {
298                         if (ldb_changetypes[i].changetype == ldif->changetype) {
299                                 break;
300                         }
301                 }
302                 if (!ldb_changetypes[i].name) {
303                         ldb_debug(ldb, LDB_DEBUG_ERROR, "Error: Invalid ldif changetype %d",
304                                   ldif->changetype);
305                         talloc_free(mem_ctx);
306                         return -1;
307                 }
308                 ret = fprintf_fn(private_data, "changetype: %s\n", ldb_changetypes[i].name);
309                 CHECK_RET;
310         }
311
312         for (i=0;i<msg->num_elements;i++) {
313                 const struct ldb_schema_attribute *a;
314
315                 a = ldb_schema_attribute_by_name(ldb, msg->elements[i].name);
316
317                 if (ldif->changetype == LDB_CHANGETYPE_MODIFY) {
318                         switch (msg->elements[i].flags & LDB_FLAG_MOD_MASK) {
319                         case LDB_FLAG_MOD_ADD:
320                                 fprintf_fn(private_data, "add: %s\n", 
321                                            msg->elements[i].name);
322                                 break;
323                         case LDB_FLAG_MOD_DELETE:
324                                 fprintf_fn(private_data, "delete: %s\n", 
325                                            msg->elements[i].name);
326                                 break;
327                         case LDB_FLAG_MOD_REPLACE:
328                                 fprintf_fn(private_data, "replace: %s\n", 
329                                            msg->elements[i].name);
330                                 break;
331                         }
332                 }
333                 
334                 if (in_trace && secret_attributes && ldb_attr_in_list(secret_attributes, msg->elements[i].name)) {
335                         /* Deliberatly skip printing this password */
336                         ret = fprintf_fn(private_data, "# %s::: REDACTED SECRET ATTRIBUTE\n",
337                                          msg->elements[i].name);
338                         CHECK_RET;
339                         continue;
340                 }
341
342                 for (j=0;j<msg->elements[i].num_values;j++) {
343                         struct ldb_val v;
344                         bool use_b64_encode;
345                         ret = a->syntax->ldif_write_fn(ldb, mem_ctx, &msg->elements[i].values[j], &v);
346                         if (ret != LDB_SUCCESS) {
347                                 v = msg->elements[i].values[j];
348                         }
349                         use_b64_encode = !(ldb->flags & LDB_FLG_SHOW_BINARY)
350                                         && ldb_should_b64_encode(ldb, &v);
351                         if (ret != LDB_SUCCESS || use_b64_encode) {
352                                 ret = fprintf_fn(private_data, "%s:: ", 
353                                                  msg->elements[i].name);
354                                 CHECK_RET;
355                                 ret = base64_encode_f(ldb, fprintf_fn, private_data, 
356                                                       (char *)v.data, v.length,
357                                                       strlen(msg->elements[i].name)+3);
358                                 CHECK_RET;
359                                 ret = fprintf_fn(private_data, "\n");
360                                 CHECK_RET;
361                         } else {
362                                 ret = fprintf_fn(private_data, "%s: ", msg->elements[i].name);
363                                 CHECK_RET;
364                                 if (ldb->flags & LDB_FLG_SHOW_BINARY) {
365                                         ret = fprintf_fn(private_data, "%*.*s", 
366                                                          v.length, v.length, (char *)v.data);
367                                 } else {
368                                         ret = fold_string(fprintf_fn, private_data,
369                                                           (char *)v.data, v.length,
370                                                           strlen(msg->elements[i].name)+2);
371                                 }
372                                 CHECK_RET;
373                                 ret = fprintf_fn(private_data, "\n");
374                                 CHECK_RET;
375                         }
376                         if (v.data != msg->elements[i].values[j].data) {
377                                 talloc_free(v.data);
378                         }
379                 }
380                 if (ldif->changetype == LDB_CHANGETYPE_MODIFY) {
381                         fprintf_fn(private_data, "-\n");
382                 }
383         }
384         ret = fprintf_fn(private_data,"\n");
385         CHECK_RET;
386
387         talloc_free(mem_ctx);
388
389         return total;
390 }
391
392 #undef CHECK_RET
393
394
395 /*
396   write to ldif, using a caller supplied write method
397 */
398 int ldb_ldif_write(struct ldb_context *ldb,
399                    int (*fprintf_fn)(void *, const char *, ...), 
400                    void *private_data,
401                    const struct ldb_ldif *ldif)
402 {
403         return ldb_ldif_write_trace(ldb, fprintf_fn, private_data, ldif, false);
404 }
405
406
407 /*
408   pull a ldif chunk, which is defined as a piece of data ending in \n\n or EOF
409   this routine removes any RFC2849 continuations and comments
410
411   caller frees
412 */
413 static char *next_chunk(struct ldb_context *ldb, 
414                         int (*fgetc_fn)(void *), void *private_data)
415 {
416         size_t alloc_size=0, chunk_size = 0;
417         char *chunk = NULL;
418         int c;
419         int in_comment = 0;
420
421         while ((c = fgetc_fn(private_data)) != EOF) {
422                 if (chunk_size+1 >= alloc_size) {
423                         char *c2;
424                         alloc_size += 1024;
425                         c2 = talloc_realloc(ldb, chunk, char, alloc_size);
426                         if (!c2) {
427                                 talloc_free(chunk);
428                                 errno = ENOMEM;
429                                 return NULL;
430                         }
431                         chunk = c2;
432                 }
433
434                 if (in_comment) {
435                         if (c == '\n') {
436                                 in_comment = 0;
437                         }
438                         continue;                       
439                 }
440                 
441                 /* handle continuation lines - see RFC2849 */
442                 if (c == ' ' && chunk_size > 1 && chunk[chunk_size-1] == '\n') {
443                         chunk_size--;
444                         continue;
445                 }
446                 
447                 /* chunks are terminated by a double line-feed */
448                 if (c == '\n' && chunk_size > 0 && chunk[chunk_size-1] == '\n') {
449                         chunk[chunk_size-1] = 0;
450                         return chunk;
451                 }
452
453                 if (c == '#' && (chunk_size == 0 || chunk[chunk_size-1] == '\n')) {
454                         in_comment = 1;
455                         continue;
456                 }
457
458                 /* ignore leading blank lines */
459                 if (chunk_size == 0 && c == '\n') {
460                         continue;
461                 }
462
463                 chunk[chunk_size++] = c;
464         }
465
466         if (chunk) {
467                 chunk[chunk_size] = 0;
468         }
469
470         return chunk;
471 }
472
473
474 /* simple ldif attribute parser */
475 static int next_attr(TALLOC_CTX *mem_ctx, char **s, const char **attr, struct ldb_val *value)
476 {
477         char *p;
478         int base64_encoded = 0;
479         int binary_file = 0;
480
481         if (strncmp(*s, "-\n", 2) == 0) {
482                 value->length = 0;
483                 *attr = "-";
484                 *s += 2;
485                 return 0;
486         }
487
488         p = strchr(*s, ':');
489         if (!p) {
490                 return -1;
491         }
492
493         *p++ = 0;
494
495         if (*p == ':') {
496                 base64_encoded = 1;
497                 p++;
498         }
499
500         if (*p == '<') {
501                 binary_file = 1;
502                 p++;
503         }
504
505         *attr = *s;
506
507         while (*p == ' ' || *p == '\t') {
508                 p++;
509         }
510
511         value->data = (uint8_t *)p;
512
513         p = strchr(p, '\n');
514
515         if (!p) {
516                 value->length = strlen((char *)value->data);
517                 *s = ((char *)value->data) + value->length;
518         } else {
519                 value->length = p - (char *)value->data;
520                 *s = p+1;
521                 *p = 0;
522         }
523
524         if (base64_encoded) {
525                 int len = ldb_base64_decode((char *)value->data);
526                 if (len == -1) {
527                         /* it wasn't valid base64 data */
528                         return -1;
529                 }
530                 value->length = len;
531         }
532
533         if (binary_file) {
534                 int len = ldb_read_data_file(mem_ctx, value);
535                 if (len == -1) {
536                         /* an error occurred while trying to retrieve the file */
537                         return -1;
538                 }
539         }
540
541         return 0;
542 }
543
544
545 /*
546   free a message from a ldif_read
547 */
548 void ldb_ldif_read_free(struct ldb_context *ldb, struct ldb_ldif *ldif)
549 {
550         talloc_free(ldif);
551 }
552
553 int ldb_ldif_parse_modrdn(struct ldb_context *ldb,
554                           const struct ldb_ldif *ldif,
555                           TALLOC_CTX *mem_ctx,
556                           struct ldb_dn **_olddn,
557                           struct ldb_dn **_newrdn,
558                           bool *_deleteoldrdn,
559                           struct ldb_dn **_newsuperior,
560                           struct ldb_dn **_newdn)
561 {
562         struct ldb_message *msg = ldif->msg;
563         struct ldb_val *newrdn_val = NULL;
564         struct ldb_val *deleteoldrdn_val = NULL;
565         struct ldb_val *newsuperior_val = NULL;
566         struct ldb_dn *olddn = NULL;
567         struct ldb_dn *newrdn = NULL;
568         bool deleteoldrdn = true;
569         struct ldb_dn *newsuperior = NULL;
570         struct ldb_dn *newdn = NULL;
571         struct ldb_val tmp_false;
572         struct ldb_val tmp_true;
573         bool ok;
574         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
575
576         if (tmp_ctx == NULL) {
577                 ldb_debug(ldb, LDB_DEBUG_FATAL,
578                           "Error: talloc_new() failed");
579                 goto err_op;
580         }
581
582         if (ldif->changetype != LDB_CHANGETYPE_MODRDN) {
583                 ldb_debug(ldb, LDB_DEBUG_ERROR,
584                           "Error: invalid changetype '%d'",
585                           ldif->changetype);
586                 goto err_other;
587         }
588
589         if (msg->num_elements < 2) {
590                 ldb_debug(ldb, LDB_DEBUG_ERROR,
591                           "Error: num_elements[%u] < 2",
592                           msg->num_elements);
593                 goto err_other;
594         }
595
596         if (msg->num_elements > 3) {
597                 ldb_debug(ldb, LDB_DEBUG_ERROR,
598                           "Error: num_elements[%u] > 3",
599                           msg->num_elements);
600                 goto err_other;
601         }
602
603 #define CHECK_ELEMENT(i, _name, v, needed) do { \
604         v = NULL; \
605         if (msg->num_elements < (i + 1)) { \
606                 if (needed) { \
607                         ldb_debug(ldb, LDB_DEBUG_ERROR, \
608                                   "Error: num_elements[%u] < (%u + 1)", \
609                                   msg->num_elements, i); \
610                         goto err_other; \
611                 } \
612         } else if (ldb_attr_cmp(msg->elements[i].name, _name) != 0) { \
613                 ldb_debug(ldb, LDB_DEBUG_ERROR, \
614                           "Error: elements[%u].name[%s] != [%s]", \
615                           i, msg->elements[i].name, _name); \
616                 goto err_other; \
617         } else if (msg->elements[i].flags != 0) { \
618                 ldb_debug(ldb, LDB_DEBUG_ERROR, \
619                           "Error: elements[%u].flags[0x%X} != [0x0]", \
620                           i, msg->elements[i].flags); \
621                 goto err_other; \
622         } else if (msg->elements[i].num_values != 1) { \
623                 ldb_debug(ldb, LDB_DEBUG_ERROR, \
624                           "Error: elements[%u].num_values[%u] != 1", \
625                           i, msg->elements[i].num_values); \
626                 goto err_other; \
627         } else { \
628                 v = &msg->elements[i].values[0]; \
629         } \
630 } while (0)
631
632         CHECK_ELEMENT(0, "newrdn", newrdn_val, true);
633         CHECK_ELEMENT(1, "deleteoldrdn", deleteoldrdn_val, true);
634         CHECK_ELEMENT(2, "newsuperior", newsuperior_val, false);
635
636 #undef CHECK_ELEMENT
637
638         olddn = ldb_dn_copy(tmp_ctx, msg->dn);
639         if (olddn == NULL) {
640                 ldb_debug(ldb, LDB_DEBUG_ERROR,
641                           "Error: failed to copy olddn '%s'",
642                           ldb_dn_get_linearized(msg->dn));
643                 goto err_op;
644         }
645
646         newrdn = ldb_dn_from_ldb_val(tmp_ctx, ldb, newrdn_val);
647         if (!ldb_dn_validate(newrdn)) {
648                 ldb_debug(ldb, LDB_DEBUG_ERROR,
649                           "Error: Unable to parse dn '%s'",
650                           (char *)newrdn_val->data);
651                 goto err_dn;
652         }
653
654         tmp_false.length = 1;
655         tmp_false.data = discard_const_p(uint8_t, "0");
656         tmp_true.length = 1;
657         tmp_true.data = discard_const_p(uint8_t, "1");
658         if (ldb_val_equal_exact(deleteoldrdn_val, &tmp_false) == 1) {
659                 deleteoldrdn = false;
660         } else if (ldb_val_equal_exact(deleteoldrdn_val, &tmp_true) == 1) {
661                 deleteoldrdn = true;
662         } else {
663                 ldb_debug(ldb, LDB_DEBUG_ERROR,
664                           "Error: deleteoldrdn value invalid '%s' not '0'/'1'",
665                           (char *)deleteoldrdn_val->data);
666                 goto err_attr;
667         }
668
669         if (newsuperior_val) {
670                 newsuperior = ldb_dn_from_ldb_val(tmp_ctx, ldb, newsuperior_val);
671                 if (!ldb_dn_validate(newsuperior)) {
672                         ldb_debug(ldb, LDB_DEBUG_ERROR,
673                                   "Error: Unable to parse dn '%s'",
674                                   (char *)newsuperior_val->data);
675                         goto err_dn;
676                 }
677         } else {
678                 newsuperior = ldb_dn_get_parent(tmp_ctx, msg->dn);
679                 if (newsuperior == NULL) {
680                         ldb_debug(ldb, LDB_DEBUG_ERROR,
681                                   "Error: Unable to get parent dn '%s'",
682                                   ldb_dn_get_linearized(msg->dn));
683                         goto err_dn;
684                 }
685         }
686
687         newdn = ldb_dn_copy(tmp_ctx, newrdn);
688         if (newdn == NULL) {
689                 ldb_debug(ldb, LDB_DEBUG_ERROR,
690                           "Error: failed to copy newrdn '%s'",
691                           ldb_dn_get_linearized(newrdn));
692                 goto err_op;
693         }
694
695         ok = ldb_dn_add_base(newdn, newsuperior);
696         if (!ok) {
697                 ldb_debug(ldb, LDB_DEBUG_ERROR,
698                           "Error: failed to base '%s' to newdn '%s'",
699                           ldb_dn_get_linearized(newsuperior),
700                           ldb_dn_get_linearized(newdn));
701                 goto err_op;
702         }
703
704         if (_olddn) {
705                 *_olddn = talloc_move(mem_ctx, &olddn);
706         }
707         if (_newrdn) {
708                 *_newrdn = talloc_move(mem_ctx, &newrdn);
709         }
710         if (_deleteoldrdn) {
711                 *_deleteoldrdn = deleteoldrdn;
712         }
713         if (_newsuperior) {
714                 if (newsuperior_val) {
715                         *_newrdn = talloc_move(mem_ctx, &newrdn);
716                 } else {
717                         *_newrdn = NULL;
718                 }
719         }
720         if (_newdn) {
721                 *_newdn = talloc_move(mem_ctx, &newdn);
722         }
723
724         talloc_free(tmp_ctx);
725         return LDB_SUCCESS;
726 err_other:
727         talloc_free(tmp_ctx);
728         return LDB_ERR_OTHER;
729 err_op:
730         talloc_free(tmp_ctx);
731         return LDB_ERR_OPERATIONS_ERROR;
732 err_attr:
733         talloc_free(tmp_ctx);
734         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
735 err_dn:
736         talloc_free(tmp_ctx);
737         return LDB_ERR_INVALID_DN_SYNTAX;
738 }
739
740 /*
741  read from a LDIF source, creating a ldb_message
742 */
743 struct ldb_ldif *ldb_ldif_read(struct ldb_context *ldb,
744                                int (*fgetc_fn)(void *), void *private_data)
745 {
746         struct ldb_ldif *ldif;
747         struct ldb_message *msg;
748         const char *attr=NULL;
749         char *chunk=NULL, *s;
750         struct ldb_val value;
751         unsigned flags = 0;
752         value.data = NULL;
753
754         ldif = talloc(ldb, struct ldb_ldif);
755         if (!ldif) return NULL;
756
757         ldif->msg = talloc(ldif, struct ldb_message);
758         if (ldif->msg == NULL) {
759                 talloc_free(ldif);
760                 return NULL;
761         }
762
763         ldif->changetype = LDB_CHANGETYPE_NONE;
764         msg = ldif->msg;
765
766         msg->dn = NULL;
767         msg->elements = NULL;
768         msg->num_elements = 0;
769
770         chunk = next_chunk(ldb, fgetc_fn, private_data);
771         if (!chunk) {
772                 goto failed;
773         }
774         talloc_steal(ldif, chunk);
775
776         s = chunk;
777
778         if (next_attr(ldif, &s, &attr, &value) != 0) {
779                 goto failed;
780         }
781         
782         /* first line must be a dn */
783         if (ldb_attr_cmp(attr, "dn") != 0) {
784                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Error: First line of ldif must be a dn not '%s'",
785                           attr);
786                 goto failed;
787         }
788
789         msg->dn = ldb_dn_from_ldb_val(msg, ldb, &value);
790
791         if ( ! ldb_dn_validate(msg->dn)) {
792                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Error: Unable to parse dn '%s'",
793                           (char *)value.data);
794                 goto failed;
795         }
796
797         while (next_attr(ldif, &s, &attr, &value) == 0) {
798                 const struct ldb_schema_attribute *a;
799                 struct ldb_message_element *el;
800                 int ret, empty = 0;
801
802                 if (ldb_attr_cmp(attr, "changetype") == 0) {
803                         int i;
804                         for (i=0;ldb_changetypes[i].name;i++) {
805                                 if (ldb_attr_cmp((char *)value.data, ldb_changetypes[i].name) == 0) {
806                                         ldif->changetype = ldb_changetypes[i].changetype;
807                                         break;
808                                 }
809                         }
810                         if (!ldb_changetypes[i].name) {
811                                 ldb_debug(ldb, LDB_DEBUG_ERROR,
812                                           "Error: Bad ldif changetype '%s'",(char *)value.data);
813                         }
814                         flags = 0;
815                         continue;
816                 }
817
818                 if (ldb_attr_cmp(attr, "add") == 0) {
819                         flags = LDB_FLAG_MOD_ADD;
820                         empty = 1;
821                 }
822                 if (ldb_attr_cmp(attr, "delete") == 0) {
823                         flags = LDB_FLAG_MOD_DELETE;
824                         empty = 1;
825                 }
826                 if (ldb_attr_cmp(attr, "replace") == 0) {
827                         flags = LDB_FLAG_MOD_REPLACE;
828                         empty = 1;
829                 }
830                 if (ldb_attr_cmp(attr, "-") == 0) {
831                         flags = 0;
832                         continue;
833                 }
834
835                 if (empty) {
836                         if (ldb_msg_add_empty(msg, (char *)value.data, flags, NULL) != 0) {
837                                 goto failed;
838                         }
839                         continue;
840                 }
841                 
842                 el = &msg->elements[msg->num_elements-1];
843
844                 a = ldb_schema_attribute_by_name(ldb, attr);
845
846                 if (msg->num_elements > 0 && ldb_attr_cmp(attr, el->name) == 0 &&
847                     flags == el->flags) {
848                         /* its a continuation */
849                         el->values = 
850                                 talloc_realloc(msg->elements, el->values, 
851                                                  struct ldb_val, el->num_values+1);
852                         if (!el->values) {
853                                 goto failed;
854                         }
855                         ret = a->syntax->ldif_read_fn(ldb, el->values, &value, &el->values[el->num_values]);
856                         if (ret != 0) {
857                                 goto failed;
858                         }
859                         if (value.length == 0) {
860                                 ldb_debug(ldb, LDB_DEBUG_ERROR,
861                                           "Error: Attribute value cannot be empty for attribute '%s'", el->name);
862                                 goto failed;
863                         }
864                         if (value.data != el->values[el->num_values].data) {
865                                 talloc_steal(el->values, el->values[el->num_values].data);
866                         }
867                         el->num_values++;
868                 } else {
869                         /* its a new attribute */
870                         msg->elements = talloc_realloc(msg, msg->elements, 
871                                                          struct ldb_message_element, 
872                                                          msg->num_elements+1);
873                         if (!msg->elements) {
874                                 goto failed;
875                         }
876                         el = &msg->elements[msg->num_elements];
877                         el->flags = flags;
878                         el->name = talloc_strdup(msg->elements, attr);
879                         el->values = talloc(msg->elements, struct ldb_val);
880                         if (!el->values || !el->name) {
881                                 goto failed;
882                         }
883                         el->num_values = 1;
884                         ret = a->syntax->ldif_read_fn(ldb, el->values, &value, &el->values[0]);
885                         if (ret != 0) {
886                                 goto failed;
887                         }
888                         if (value.data != el->values[0].data) {
889                                 talloc_steal(el->values, el->values[0].data);
890                         }
891                         msg->num_elements++;
892                 }
893         }
894
895         if (ldif->changetype == LDB_CHANGETYPE_MODRDN) {
896                 int ret;
897
898                 ret = ldb_ldif_parse_modrdn(ldb, ldif, ldif,
899                                             NULL, NULL, NULL, NULL, NULL);
900                 if (ret != LDB_SUCCESS) {
901                         goto failed;
902                 }
903         }
904
905         return ldif;
906
907 failed:
908         talloc_free(ldif);
909         return NULL;
910 }
911
912
913
914 /*
915   a wrapper around ldif_read() for reading from FILE*
916 */
917
918 static int fgetc_file(void *private_data)
919 {
920         int c;
921         struct ldif_read_file_state *state =
922                 (struct ldif_read_file_state *)private_data;
923         c = fgetc(state->f);
924         if (c == '\n') {
925                 state->line_no++;
926         }
927         return c;
928 }
929
930 struct ldb_ldif *ldb_ldif_read_file_state(struct ldb_context *ldb, 
931                                           struct ldif_read_file_state *state)
932 {
933         return ldb_ldif_read(ldb, fgetc_file, state);
934 }
935
936 struct ldb_ldif *ldb_ldif_read_file(struct ldb_context *ldb, FILE *f)
937 {
938         struct ldif_read_file_state state;
939         state.f = f;
940         return ldb_ldif_read_file_state(ldb, &state);
941 }
942
943 /*
944   a wrapper around ldif_read() for reading from const char*
945 */
946 struct ldif_read_string_state {
947         const char *s;
948 };
949
950 static int fgetc_string(void *private_data)
951 {
952         struct ldif_read_string_state *state =
953                 (struct ldif_read_string_state *)private_data;
954         if (state->s[0] != 0) {
955                 return *state->s++;
956         }
957         return EOF;
958 }
959
960 struct ldb_ldif *ldb_ldif_read_string(struct ldb_context *ldb, const char **s)
961 {
962         struct ldif_read_string_state state;
963         struct ldb_ldif *ldif;
964         state.s = *s;
965         ldif = ldb_ldif_read(ldb, fgetc_string, &state);
966         *s = state.s;
967         return ldif;
968 }
969
970
971 /*
972   wrapper around ldif_write() for a file
973 */
974 struct ldif_write_file_state {
975         FILE *f;
976 };
977
978 static int fprintf_file(void *private_data, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3);
979
980 static int fprintf_file(void *private_data, const char *fmt, ...)
981 {
982         struct ldif_write_file_state *state =
983                 (struct ldif_write_file_state *)private_data;
984         int ret;
985         va_list ap;
986
987         va_start(ap, fmt);
988         ret = vfprintf(state->f, fmt, ap);
989         va_end(ap);
990         return ret;
991 }
992
993 int ldb_ldif_write_file(struct ldb_context *ldb, FILE *f, const struct ldb_ldif *ldif)
994 {
995         struct ldif_write_file_state state;
996         state.f = f;
997         return ldb_ldif_write(ldb, fprintf_file, &state, ldif);
998 }
999
1000 /*
1001   wrapper around ldif_write() for a string
1002 */
1003 struct ldif_write_string_state {
1004         char *string;
1005 };
1006
1007 static int ldif_printf_string(void *private_data, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3);
1008
1009 static int ldif_printf_string(void *private_data, const char *fmt, ...)
1010 {
1011         struct ldif_write_string_state *state =
1012                 (struct ldif_write_string_state *)private_data;
1013         va_list ap;
1014         size_t oldlen = talloc_get_size(state->string);
1015         va_start(ap, fmt);
1016         
1017         state->string = talloc_vasprintf_append(state->string, fmt, ap);
1018         va_end(ap);
1019         if (!state->string) {
1020                 return -1;
1021         }
1022
1023         return talloc_get_size(state->string) - oldlen;
1024 }
1025
1026 char *ldb_ldif_write_redacted_trace_string(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
1027                                            const struct ldb_ldif *ldif)
1028 {
1029         struct ldif_write_string_state state;
1030         state.string = talloc_strdup(mem_ctx, "");
1031         if (!state.string) {
1032                 return NULL;
1033         }
1034         if (ldb_ldif_write_trace(ldb, ldif_printf_string, &state, ldif, true) == -1) {
1035                 return NULL;
1036         }
1037         return state.string;
1038 }
1039
1040 char *ldb_ldif_write_string(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
1041                             const struct ldb_ldif *ldif)
1042 {
1043         struct ldif_write_string_state state;
1044         state.string = talloc_strdup(mem_ctx, "");
1045         if (!state.string) {
1046                 return NULL;
1047         }
1048         if (ldb_ldif_write(ldb, ldif_printf_string, &state, ldif) == -1) {
1049                 return NULL;
1050         }
1051         return state.string;
1052 }
1053
1054 /*
1055   convenient function to turn a ldb_message into a string. Useful for
1056   debugging
1057  */
1058 char *ldb_ldif_message_string(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
1059                               enum ldb_changetype changetype,
1060                               const struct ldb_message *msg)
1061 {
1062         struct ldb_ldif ldif;
1063
1064         ldif.changetype = changetype;
1065         ldif.msg = discard_const_p(struct ldb_message, msg);
1066
1067         return ldb_ldif_write_string(ldb, mem_ctx, &ldif);
1068 }