r4474: - converted ldb to use talloc internally
[metze/samba/wip.git] / source4 / 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 2 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, write to the Free Software
22    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23 */
24
25 /*
26  *  Name: ldb
27  *
28  *  Component: ldif routines
29  *
30  *  Description: ldif pack/unpack routines
31  *
32  *  Author: Andrew Tridgell
33  */
34
35 /*
36   see RFC2849 for the LDIF format definition
37 */
38
39 #include "includes.h"
40 #include "ldb/include/ldb.h"
41 #include "ldb/include/ldb_private.h"
42 #include <ctype.h>
43
44
45 /*
46   this base64 decoder was taken from jitterbug (written by tridge).
47   we might need to replace it with a new version
48 */
49 static int base64_decode(char *s)
50 {
51         const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
52         int bit_offset, byte_offset, idx, i, n;
53         uint8_t *d = (uint8_t *)s;
54         char *p;
55
56         n=i=0;
57
58         while (*s && (p=strchr(b64,*s))) {
59                 idx = (int)(p - b64);
60                 byte_offset = (i*6)/8;
61                 bit_offset = (i*6)%8;
62                 d[byte_offset] &= ~((1<<(8-bit_offset))-1);
63                 if (bit_offset < 3) {
64                         d[byte_offset] |= (idx << (2-bit_offset));
65                         n = byte_offset+1;
66                 } else {
67                         d[byte_offset] |= (idx >> (bit_offset-2));
68                         d[byte_offset+1] = 0;
69                         d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF;
70                         n = byte_offset+2;
71                 }
72                 s++; i++;
73         }
74
75         if (*s && !p) {
76                 /* the only termination allowed */
77                 if (*s != '=') {
78                         return -1;
79                 }
80         }
81
82         /* null terminate */
83         d[n] = 0;
84         return n;
85 }
86
87
88 /*
89   encode as base64
90   caller frees
91 */
92 char *ldb_base64_encode(struct ldb_context *ldb, const char *buf, int len)
93 {
94         const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
95         int bit_offset, byte_offset, idx, i;
96         const uint8_t *d = (const uint8_t *)buf;
97         int bytes = (len*8 + 5)/6;
98         char *out;
99
100         out = talloc_array_p(ldb, char, bytes+2);
101         if (!out) return NULL;
102
103         for (i=0;i<bytes;i++) {
104                 byte_offset = (i*6)/8;
105                 bit_offset = (i*6)%8;
106                 if (bit_offset < 3) {
107                         idx = (d[byte_offset] >> (2-bit_offset)) & 0x3F;
108                 } else {
109                         idx = (d[byte_offset] << (bit_offset-2)) & 0x3F;
110                         if (byte_offset+1 < len) {
111                                 idx |= (d[byte_offset+1] >> (8-(bit_offset-2)));
112                         }
113                 }
114                 out[i] = b64[idx];
115         }
116
117         out[i++] = '=';
118         out[i] = 0;
119
120         return out;
121 }
122
123 /*
124   see if a buffer should be base64 encoded
125 */
126 int ldb_should_b64_encode(const struct ldb_val *val)
127 {
128         unsigned int i;
129         uint8_t *p = val->data;
130
131         if (val->length == 0) {
132                 return 0;
133         }
134
135         if (p[0] == ' ' || p[0] == ':') {
136                 return 1;
137         }
138
139         for (i=0; i<val->length; i++) {
140                 if (!isprint(p[i]) || p[i] == '\n') {
141                         return 1;
142                 }
143         }
144         return 0;
145 }
146
147 /* this macro is used to handle the return checking on fprintf_fn() */
148 #define CHECK_RET do { if (ret < 0) return ret; total += ret; } while (0)
149
150 /*
151   write a line folded string onto a file
152 */
153 static int fold_string(int (*fprintf_fn)(void *, const char *, ...), void *private_data,
154                         const char *buf, size_t length, int start_pos)
155 {
156         unsigned int i;
157         int total=0, ret;
158
159         for (i=0;i<length;i++) {
160                 ret = fprintf_fn(private_data, "%c", buf[i]);
161                 CHECK_RET;
162                 if (i != (length-1) && (i + start_pos) % 77 == 0) {
163                         ret = fprintf_fn(private_data, "\n ");
164                         CHECK_RET;
165                 }
166         }
167
168         return total;
169 }
170
171 /*
172   encode as base64 to a file
173 */
174 static int base64_encode_f(struct ldb_context *ldb,
175                            int (*fprintf_fn)(void *, const char *, ...), 
176                            void *private_data,
177                            const char *buf, int len, int start_pos)
178 {
179         char *b = ldb_base64_encode(ldb, buf, len);
180         int ret;
181
182         if (!b) {
183                 return -1;
184         }
185
186         ret = fold_string(fprintf_fn, private_data, b, strlen(b), start_pos);
187
188         talloc_free(b);
189         return ret;
190 }
191
192
193 static const struct {
194         const char *name;
195         enum ldb_changetype changetype;
196 } ldb_changetypes[] = {
197         {"add",    LDB_CHANGETYPE_ADD},
198         {"delete", LDB_CHANGETYPE_DELETE},
199         {"modify", LDB_CHANGETYPE_MODIFY},
200         {NULL, 0}
201 };
202
203 /*
204   write to ldif, using a caller supplied write method
205 */
206 int ldb_ldif_write(struct ldb_context *ldb,
207                    int (*fprintf_fn)(void *, const char *, ...), 
208                    void *private_data,
209                    const struct ldb_ldif *ldif)
210 {
211         unsigned int i, j;
212         int total=0, ret;
213         const struct ldb_message *msg;
214
215         msg = ldif->msg;
216
217         ret = fprintf_fn(private_data, "dn: %s\n", msg->dn);
218         CHECK_RET;
219
220         if (ldif->changetype != LDB_CHANGETYPE_NONE) {
221                 for (i=0;ldb_changetypes[i].name;i++) {
222                         if (ldb_changetypes[i].changetype == ldif->changetype) {
223                                 break;
224                         }
225                 }
226                 if (!ldb_changetypes[i].name) {
227                         ldb_debug(ldb, LDB_DEBUG_ERROR, "Error: Invalid ldif changetype %d\n",
228                                   ldif->changetype);
229                         return -1;
230                 }
231                 ret = fprintf_fn(private_data, "changetype: %s\n", ldb_changetypes[i].name);
232                 CHECK_RET;
233         }
234
235         for (i=0;i<msg->num_elements;i++) {
236                 if (ldif->changetype == LDB_CHANGETYPE_MODIFY) {
237                         switch (msg->elements[i].flags & LDB_FLAG_MOD_MASK) {
238                         case LDB_FLAG_MOD_ADD:
239                                 fprintf_fn(private_data, "add: %s\n", 
240                                            msg->elements[i].name);
241                                 break;
242                         case LDB_FLAG_MOD_DELETE:
243                                 fprintf_fn(private_data, "delete: %s\n", 
244                                            msg->elements[i].name);
245                                 break;
246                         case LDB_FLAG_MOD_REPLACE:
247                                 fprintf_fn(private_data, "replace: %s\n", 
248                                            msg->elements[i].name);
249                                 break;
250                         }
251                 }
252
253                 for (j=0;j<msg->elements[i].num_values;j++) {
254                         if (ldb_should_b64_encode(&msg->elements[i].values[j])) {
255                                 ret = fprintf_fn(private_data, "%s:: ", 
256                                                  msg->elements[i].name);
257                                 CHECK_RET;
258                                 ret = base64_encode_f(ldb, fprintf_fn, private_data, 
259                                                       msg->elements[i].values[j].data, 
260                                                       msg->elements[i].values[j].length,
261                                                       strlen(msg->elements[i].name)+3);
262                                 CHECK_RET;
263                                 ret = fprintf_fn(private_data, "\n");
264                                 CHECK_RET;
265                         } else {
266                                 ret = fprintf_fn(private_data, "%s: ", msg->elements[i].name);
267                                 CHECK_RET;
268                                 ret = fold_string(fprintf_fn, private_data,
269                                                   msg->elements[i].values[j].data,
270                                                   msg->elements[i].values[j].length,
271                                                   strlen(msg->elements[i].name)+2);
272                                 CHECK_RET;
273                                 ret = fprintf_fn(private_data, "\n");
274                                 CHECK_RET;
275                         }
276                 }
277                 if (ldif->changetype == LDB_CHANGETYPE_MODIFY) {
278                         fprintf_fn(private_data, "-\n");
279                 }
280         }
281         ret = fprintf_fn(private_data,"\n");
282         CHECK_RET;
283
284         return total;
285 }
286
287 #undef CHECK_RET
288
289
290 /*
291   pull a ldif chunk, which is defined as a piece of data ending in \n\n or EOF
292   this routine removes any RFC2849 continuations and comments
293
294   caller frees
295 */
296 static char *next_chunk(struct ldb_context *ldb, 
297                         int (*fgetc_fn)(void *), void *private_data)
298 {
299         size_t alloc_size=0, chunk_size = 0;
300         char *chunk = NULL;
301         int c;
302         int in_comment = 0;
303
304         while ((c = fgetc_fn(private_data)) != EOF) {
305                 if (chunk_size+1 >= alloc_size) {
306                         char *c2;
307                         alloc_size += 1024;
308                         c2 = talloc_realloc_p(ldb, chunk, char, alloc_size);
309                         if (!c2) {
310                                 talloc_free(chunk);
311                                 errno = ENOMEM;
312                                 return NULL;
313                         }
314                         chunk = c2;
315                 }
316
317                 if (in_comment) {
318                         if (c == '\n') {
319                                 in_comment = 0;
320                         }
321                         continue;                       
322                 }
323                 
324                 /* handle continuation lines - see RFC2849 */
325                 if (c == ' ' && chunk_size > 1 && chunk[chunk_size-1] == '\n') {
326                         chunk_size--;
327                         continue;
328                 }
329                 
330                 /* chunks are terminated by a double line-feed */
331                 if (c == '\n' && chunk_size > 0 && chunk[chunk_size-1] == '\n') {
332                         chunk[chunk_size-1] = 0;
333                         return chunk;
334                 }
335
336                 if (c == '#' && (chunk_size == 0 || chunk[chunk_size-1] == '\n')) {
337                         in_comment = 1;
338                         continue;
339                 }
340
341                 /* ignore leading blank lines */
342                 if (chunk_size == 0 && c == '\n') {
343                         continue;
344                 }
345
346                 chunk[chunk_size++] = c;
347         }
348
349         if (chunk) {
350                 chunk[chunk_size] = 0;
351         }
352
353         return chunk;
354 }
355
356
357 /* simple ldif attribute parser */
358 static int next_attr(char **s, const char **attr, struct ldb_val *value)
359 {
360         char *p;
361         int base64_encoded = 0;
362
363         if (strncmp(*s, "-\n", 2) == 0) {
364                 value->length = 0;
365                 *attr = "-";
366                 *s += 2;
367                 return 0;
368         }
369
370         p = strchr(*s, ':');
371         if (!p) {
372                 return -1;
373         }
374
375         *p++ = 0;
376
377         if (*p == ':') {
378                 base64_encoded = 1;
379                 p++;
380         }
381
382         *attr = *s;
383
384         while (*p == ' ' || *p == '\t') {
385                 p++;
386         }
387
388         value->data = p;
389
390         p = strchr(p, '\n');
391
392         if (!p) {
393                 value->length = strlen((char *)value->data);
394                 *s = ((char *)value->data) + value->length;
395         } else {
396                 value->length = p - (char *)value->data;
397                 *s = p+1;
398                 *p = 0;
399         }
400
401         if (base64_encoded) {
402                 int len = base64_decode(value->data);
403                 if (len == -1) {
404                         /* it wasn't valid base64 data */
405                         return -1;
406                 }
407                 value->length = len;
408         }
409
410         return 0;
411 }
412
413
414 /*
415   free a message from a ldif_read
416 */
417 void ldb_ldif_read_free(struct ldb_context *ldb, struct ldb_ldif *ldif)
418 {
419         talloc_free(ldif);
420 }
421
422 /*
423   add an empty element
424 */
425 static int msg_add_empty(struct ldb_context *ldb,
426                          struct ldb_message *msg, const char *name, unsigned flags)
427 {
428         struct ldb_message_element *el2, *el;
429
430         el2 = talloc_realloc_p(msg, msg->elements, 
431                                struct ldb_message_element, msg->num_elements+1);
432         if (!el2) {
433                 errno = ENOMEM;
434                 return -1;
435         }
436         
437         msg->elements = el2;
438
439         el = &msg->elements[msg->num_elements];
440         
441         el->name = talloc_strdup(msg->elements, name);
442         el->num_values = 0;
443         el->values = NULL;
444         el->flags = flags;
445
446         if (!el->name) {
447                 errno = ENOMEM;
448                 return -1;
449         }
450
451         msg->num_elements++;
452
453         return 0;
454 }
455
456 /*
457  read from a LDIF source, creating a ldb_message
458 */
459 struct ldb_ldif *ldb_ldif_read(struct ldb_context *ldb,
460                                int (*fgetc_fn)(void *), void *private_data)
461 {
462         struct ldb_ldif *ldif;
463         struct ldb_message *msg;
464         const char *attr=NULL;
465         char *chunk=NULL, *s;
466         struct ldb_val value;
467         unsigned flags = 0;
468
469         value.data = NULL;
470
471         ldif = talloc_p(ldb, struct ldb_ldif);
472         if (!ldif) return NULL;
473
474         ldif->msg = talloc_p(ldif, struct ldb_message);
475         if (ldif->msg == NULL) {
476                 talloc_free(ldif);
477                 return NULL;
478         }
479
480         ldif->changetype = LDB_CHANGETYPE_NONE;
481         msg = ldif->msg;
482
483         msg->dn = NULL;
484         msg->elements = NULL;
485         msg->num_elements = 0;
486         msg->private_data = NULL;
487
488         chunk = next_chunk(ldb, fgetc_fn, private_data);
489         if (!chunk) {
490                 goto failed;
491         }
492
493         msg->private_data = chunk;
494         s = chunk;
495
496         if (next_attr(&s, &attr, &value) != 0) {
497                 goto failed;
498         }
499         
500         /* first line must be a dn */
501         if (ldb_attr_cmp(attr, "dn") != 0) {
502                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Error: First line of ldif must be a dn not '%s'\n", 
503                           attr);
504                 goto failed;
505         }
506
507         msg->dn = value.data;
508
509         while (next_attr(&s, &attr, &value) == 0) {
510                 struct ldb_message_element *el;
511                 int empty = 0;
512
513                 if (ldb_attr_cmp(attr, "changetype") == 0) {
514                         int i;
515                         for (i=0;ldb_changetypes[i].name;i++) {
516                                 if (ldb_attr_cmp((char *)value.data, ldb_changetypes[i].name) == 0) {
517                                         ldif->changetype = ldb_changetypes[i].changetype;
518                                         break;
519                                 }
520                         }
521                         if (!ldb_changetypes[i].name) {
522                                 ldb_debug(ldb, LDB_DEBUG_ERROR, 
523                                           "Error: Bad ldif changetype '%s'\n",(char *)value.data);
524                         }
525                         flags = 0;
526                         continue;
527                 }
528
529                 if (ldb_attr_cmp(attr, "add") == 0) {
530                         flags = LDB_FLAG_MOD_ADD;
531                         empty = 1;
532                 }
533                 if (ldb_attr_cmp(attr, "delete") == 0) {
534                         flags = LDB_FLAG_MOD_DELETE;
535                         empty = 1;
536                 }
537                 if (ldb_attr_cmp(attr, "replace") == 0) {
538                         flags = LDB_FLAG_MOD_REPLACE;
539                         empty = 1;
540                 }
541                 if (ldb_attr_cmp(attr, "-") == 0) {
542                         flags = 0;
543                         continue;
544                 }
545
546                 if (empty) {
547                         if (msg_add_empty(ldb, msg, (char *)value.data, flags) != 0) {
548                                 goto failed;
549                         }
550                         continue;
551                 }
552                 
553                 el = &msg->elements[msg->num_elements-1];
554
555                 if (msg->num_elements > 0 && ldb_attr_cmp(attr, el->name) == 0 &&
556                     flags == el->flags) {
557                         /* its a continuation */
558                         el->values = 
559                                 talloc_realloc_p(msg->elements, el->values, 
560                                                  struct ldb_val, el->num_values+1);
561                         if (!el->values) {
562                                 goto failed;
563                         }
564                         el->values[el->num_values] = value;
565                         el->num_values++;
566                 } else {
567                         /* its a new attribute */
568                         msg->elements = talloc_realloc_p(ldif, msg->elements, 
569                                                          struct ldb_message_element, 
570                                                          msg->num_elements+1);
571                         if (!msg->elements) {
572                                 goto failed;
573                         }
574                         el = &msg->elements[msg->num_elements];
575                         el->flags = flags;
576                         el->name = talloc_strdup(msg->elements, attr);
577                         el->values = talloc_p(msg->elements, struct ldb_val);
578                         if (!el->values || !el->name) {
579                                 goto failed;
580                         }
581                         el->num_values = 1;
582                         el->values[0] = value;
583                         msg->num_elements++;
584                 }
585         }
586
587         return ldif;
588
589 failed:
590         talloc_free(ldif);
591         return NULL;
592 }
593
594
595
596 /*
597   a wrapper around ldif_read() for reading from FILE*
598 */
599 struct ldif_read_file_state {
600         FILE *f;
601 };
602
603 static int fgetc_file(void *private_data)
604 {
605         struct ldif_read_file_state *state = private_data;
606         return fgetc(state->f);
607 }
608
609 struct ldb_ldif *ldb_ldif_read_file(struct ldb_context *ldb, FILE *f)
610 {
611         struct ldif_read_file_state state;
612         state.f = f;
613         return ldb_ldif_read(ldb, fgetc_file, &state);
614 }
615
616
617 /*
618   a wrapper around ldif_read() for reading from const char*
619 */
620 struct ldif_read_string_state {
621         const char *s;
622 };
623
624 static int fgetc_string(void *private_data)
625 {
626         struct ldif_read_string_state *state = private_data;
627         if (state->s[0] != 0) {
628                 return *state->s++;
629         }
630         return EOF;
631 }
632
633 struct ldb_ldif *ldb_ldif_read_string(struct ldb_context *ldb, const char *s)
634 {
635         struct ldif_read_string_state state;
636         state.s = s;
637         return ldb_ldif_read(ldb, fgetc_string, &state);
638 }
639
640
641 /*
642   wrapper around ldif_write() for a file
643 */
644 struct ldif_write_file_state {
645         FILE *f;
646 };
647
648 static int fprintf_file(void *private_data, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3);
649
650 static int fprintf_file(void *private_data, const char *fmt, ...)
651 {
652         struct ldif_write_file_state *state = private_data;
653         int ret;
654         va_list ap;
655
656         va_start(ap, fmt);
657         ret = vfprintf(state->f, fmt, ap);
658         va_end(ap);
659         return ret;
660 }
661
662 int ldb_ldif_write_file(struct ldb_context *ldb, FILE *f, const struct ldb_ldif *ldif)
663 {
664         struct ldif_write_file_state state;
665         state.f = f;
666         return ldb_ldif_write(ldb, fprintf_file, &state, ldif);
667 }