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