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