r18536: fixed the loading of external binary files from ldif into ldb
[kamenim/samba.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/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 = 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 /*
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         {NULL, 0}
265 };
266
267 /*
268   write to ldif, using a caller supplied write method
269 */
270 int ldb_ldif_write(struct ldb_context *ldb,
271                    int (*fprintf_fn)(void *, const char *, ...), 
272                    void *private_data,
273                    const struct ldb_ldif *ldif)
274 {
275         unsigned int i, j;
276         int total=0, ret;
277         const struct ldb_message *msg;
278
279         msg = ldif->msg;
280
281         ret = fprintf_fn(private_data, "dn: %s\n", ldb_dn_linearize(msg->dn, msg->dn));
282         CHECK_RET;
283
284         if (ldif->changetype != LDB_CHANGETYPE_NONE) {
285                 for (i=0;ldb_changetypes[i].name;i++) {
286                         if (ldb_changetypes[i].changetype == ldif->changetype) {
287                                 break;
288                         }
289                 }
290                 if (!ldb_changetypes[i].name) {
291                         ldb_debug(ldb, LDB_DEBUG_ERROR, "Error: Invalid ldif changetype %d\n",
292                                   ldif->changetype);
293                         return -1;
294                 }
295                 ret = fprintf_fn(private_data, "changetype: %s\n", ldb_changetypes[i].name);
296                 CHECK_RET;
297         }
298
299         for (i=0;i<msg->num_elements;i++) {
300                 const struct ldb_attrib_handler *h;
301
302                 h = ldb_attrib_handler(ldb, msg->elements[i].name);
303
304                 if (ldif->changetype == LDB_CHANGETYPE_MODIFY) {
305                         switch (msg->elements[i].flags & LDB_FLAG_MOD_MASK) {
306                         case LDB_FLAG_MOD_ADD:
307                                 fprintf_fn(private_data, "add: %s\n", 
308                                            msg->elements[i].name);
309                                 break;
310                         case LDB_FLAG_MOD_DELETE:
311                                 fprintf_fn(private_data, "delete: %s\n", 
312                                            msg->elements[i].name);
313                                 break;
314                         case LDB_FLAG_MOD_REPLACE:
315                                 fprintf_fn(private_data, "replace: %s\n", 
316                                            msg->elements[i].name);
317                                 break;
318                         }
319                 }
320
321                 for (j=0;j<msg->elements[i].num_values;j++) {
322                         struct ldb_val v;
323                         ret = h->ldif_write_fn(ldb, ldb, &msg->elements[i].values[j], &v);
324                         CHECK_RET;
325                         if (ldb_should_b64_encode(&v)) {
326                                 ret = fprintf_fn(private_data, "%s:: ", 
327                                                  msg->elements[i].name);
328                                 CHECK_RET;
329                                 ret = base64_encode_f(ldb, fprintf_fn, private_data, 
330                                                       (char *)v.data, v.length,
331                                                       strlen(msg->elements[i].name)+3);
332                                 CHECK_RET;
333                                 ret = fprintf_fn(private_data, "\n");
334                                 CHECK_RET;
335                         } else {
336                                 ret = fprintf_fn(private_data, "%s: ", msg->elements[i].name);
337                                 CHECK_RET;
338                                 ret = fold_string(fprintf_fn, private_data,
339                                                   (char *)v.data, v.length,
340                                                   strlen(msg->elements[i].name)+2);
341                                 CHECK_RET;
342                                 ret = fprintf_fn(private_data, "\n");
343                                 CHECK_RET;
344                         }
345                         if (v.data != msg->elements[i].values[j].data) {
346                                 talloc_free(v.data);
347                         }
348                 }
349                 if (ldif->changetype == LDB_CHANGETYPE_MODIFY) {
350                         fprintf_fn(private_data, "-\n");
351                 }
352         }
353         ret = fprintf_fn(private_data,"\n");
354         CHECK_RET;
355
356         return total;
357 }
358
359 #undef CHECK_RET
360
361
362 /*
363   pull a ldif chunk, which is defined as a piece of data ending in \n\n or EOF
364   this routine removes any RFC2849 continuations and comments
365
366   caller frees
367 */
368 static char *next_chunk(struct ldb_context *ldb, 
369                         int (*fgetc_fn)(void *), void *private_data)
370 {
371         size_t alloc_size=0, chunk_size = 0;
372         char *chunk = NULL;
373         int c;
374         int in_comment = 0;
375
376         while ((c = fgetc_fn(private_data)) != EOF) {
377                 if (chunk_size+1 >= alloc_size) {
378                         char *c2;
379                         alloc_size += 1024;
380                         c2 = talloc_realloc(ldb, chunk, char, alloc_size);
381                         if (!c2) {
382                                 talloc_free(chunk);
383                                 errno = ENOMEM;
384                                 return NULL;
385                         }
386                         chunk = c2;
387                 }
388
389                 if (in_comment) {
390                         if (c == '\n') {
391                                 in_comment = 0;
392                         }
393                         continue;                       
394                 }
395                 
396                 /* handle continuation lines - see RFC2849 */
397                 if (c == ' ' && chunk_size > 1 && chunk[chunk_size-1] == '\n') {
398                         chunk_size--;
399                         continue;
400                 }
401                 
402                 /* chunks are terminated by a double line-feed */
403                 if (c == '\n' && chunk_size > 0 && chunk[chunk_size-1] == '\n') {
404                         chunk[chunk_size-1] = 0;
405                         return chunk;
406                 }
407
408                 if (c == '#' && (chunk_size == 0 || chunk[chunk_size-1] == '\n')) {
409                         in_comment = 1;
410                         continue;
411                 }
412
413                 /* ignore leading blank lines */
414                 if (chunk_size == 0 && c == '\n') {
415                         continue;
416                 }
417
418                 chunk[chunk_size++] = c;
419         }
420
421         if (chunk) {
422                 chunk[chunk_size] = 0;
423         }
424
425         return chunk;
426 }
427
428
429 /* simple ldif attribute parser */
430 static int next_attr(void *mem_ctx, char **s, const char **attr, struct ldb_val *value)
431 {
432         char *p;
433         int base64_encoded = 0;
434         int binary_file = 0;
435
436         if (strncmp(*s, "-\n", 2) == 0) {
437                 value->length = 0;
438                 *attr = "-";
439                 *s += 2;
440                 return 0;
441         }
442
443         p = strchr(*s, ':');
444         if (!p) {
445                 return -1;
446         }
447
448         *p++ = 0;
449
450         if (*p == ':') {
451                 base64_encoded = 1;
452                 p++;
453         }
454
455         if (*p == '<') {
456                 binary_file = 1;
457                 p++;
458         }
459
460         *attr = *s;
461
462         while (*p == ' ' || *p == '\t') {
463                 p++;
464         }
465
466         value->data = (uint8_t *)p;
467
468         p = strchr(p, '\n');
469
470         if (!p) {
471                 value->length = strlen((char *)value->data);
472                 *s = ((char *)value->data) + value->length;
473         } else {
474                 value->length = p - (char *)value->data;
475                 *s = p+1;
476                 *p = 0;
477         }
478
479         if (base64_encoded) {
480                 int len = ldb_base64_decode((char *)value->data);
481                 if (len == -1) {
482                         /* it wasn't valid base64 data */
483                         return -1;
484                 }
485                 value->length = len;
486         }
487
488         if (binary_file) {
489                 int len = ldb_read_data_file(mem_ctx, value);
490                 if (len == -1) {
491                         /* an error occured hile trying to retrieve the file */
492                         return -1;
493                 }
494         }
495
496         return 0;
497 }
498
499
500 /*
501   free a message from a ldif_read
502 */
503 void ldb_ldif_read_free(struct ldb_context *ldb, struct ldb_ldif *ldif)
504 {
505         talloc_free(ldif);
506 }
507
508 /*
509  read from a LDIF source, creating a ldb_message
510 */
511 struct ldb_ldif *ldb_ldif_read(struct ldb_context *ldb,
512                                int (*fgetc_fn)(void *), void *private_data)
513 {
514         struct ldb_ldif *ldif;
515         struct ldb_message *msg;
516         const char *attr=NULL;
517         char *chunk=NULL, *s;
518         struct ldb_val value;
519         unsigned flags = 0;
520
521         value.data = NULL;
522
523         ldif = talloc(ldb, struct ldb_ldif);
524         if (!ldif) return NULL;
525
526         ldif->msg = talloc(ldif, struct ldb_message);
527         if (ldif->msg == NULL) {
528                 talloc_free(ldif);
529                 return NULL;
530         }
531
532         ldif->changetype = LDB_CHANGETYPE_NONE;
533         msg = ldif->msg;
534
535         msg->dn = NULL;
536         msg->elements = NULL;
537         msg->num_elements = 0;
538         msg->private_data = NULL;
539
540         chunk = next_chunk(ldb, fgetc_fn, private_data);
541         if (!chunk) {
542                 goto failed;
543         }
544
545         msg->private_data = chunk;
546         s = chunk;
547
548         if (next_attr(ldif, &s, &attr, &value) != 0) {
549                 goto failed;
550         }
551         
552         /* first line must be a dn */
553         if (ldb_attr_cmp(attr, "dn") != 0) {
554                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Error: First line of ldif must be a dn not '%s'\n", 
555                           attr);
556                 goto failed;
557         }
558
559         msg->dn = ldb_dn_explode(msg, (char *)value.data);
560
561         if (msg->dn == NULL) {
562                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Error: Unable to parse dn '%s'\n", 
563                                   value.data);
564                 goto failed;
565         }
566
567         while (next_attr(ldif, &s, &attr, &value) == 0) {
568                 const struct ldb_attrib_handler *h;             
569                 struct ldb_message_element *el;
570                 int ret, empty = 0;
571
572                 if (ldb_attr_cmp(attr, "changetype") == 0) {
573                         int i;
574                         for (i=0;ldb_changetypes[i].name;i++) {
575                                 if (ldb_attr_cmp((char *)value.data, ldb_changetypes[i].name) == 0) {
576                                         ldif->changetype = ldb_changetypes[i].changetype;
577                                         break;
578                                 }
579                         }
580                         if (!ldb_changetypes[i].name) {
581                                 ldb_debug(ldb, LDB_DEBUG_ERROR, 
582                                           "Error: Bad ldif changetype '%s'\n",(char *)value.data);
583                         }
584                         flags = 0;
585                         continue;
586                 }
587
588                 if (ldb_attr_cmp(attr, "add") == 0) {
589                         flags = LDB_FLAG_MOD_ADD;
590                         empty = 1;
591                 }
592                 if (ldb_attr_cmp(attr, "delete") == 0) {
593                         flags = LDB_FLAG_MOD_DELETE;
594                         empty = 1;
595                 }
596                 if (ldb_attr_cmp(attr, "replace") == 0) {
597                         flags = LDB_FLAG_MOD_REPLACE;
598                         empty = 1;
599                 }
600                 if (ldb_attr_cmp(attr, "-") == 0) {
601                         flags = 0;
602                         continue;
603                 }
604
605                 if (empty) {
606                         if (ldb_msg_add_empty(msg, (char *)value.data, flags) != 0) {
607                                 goto failed;
608                         }
609                         continue;
610                 }
611                 
612                 el = &msg->elements[msg->num_elements-1];
613
614                 h = ldb_attrib_handler(ldb, attr);
615
616                 if (msg->num_elements > 0 && ldb_attr_cmp(attr, el->name) == 0 &&
617                     flags == el->flags) {
618                         /* its a continuation */
619                         el->values = 
620                                 talloc_realloc(msg->elements, el->values, 
621                                                  struct ldb_val, el->num_values+1);
622                         if (!el->values) {
623                                 goto failed;
624                         }
625                         ret = h->ldif_read_fn(ldb, ldif, &value, &el->values[el->num_values]);
626                         if (ret != 0) {
627                                 goto failed;
628                         }
629                         if (value.length == 0) {
630                                 ldb_debug(ldb, LDB_DEBUG_ERROR,
631                                           "Error: Attribute value cannot be empty for attribute '%s'\n", el->name);
632                                 goto failed;
633                         }
634                         if (value.data != el->values[el->num_values].data) {
635                                 talloc_steal(el->values, el->values[el->num_values].data);
636                         }
637                         el->num_values++;
638                 } else {
639                         /* its a new attribute */
640                         msg->elements = talloc_realloc(ldif, msg->elements, 
641                                                          struct ldb_message_element, 
642                                                          msg->num_elements+1);
643                         if (!msg->elements) {
644                                 goto failed;
645                         }
646                         el = &msg->elements[msg->num_elements];
647                         el->flags = flags;
648                         el->name = talloc_strdup(msg->elements, attr);
649                         el->values = talloc(msg->elements, struct ldb_val);
650                         if (!el->values || !el->name) {
651                                 goto failed;
652                         }
653                         el->num_values = 1;
654                         ret = h->ldif_read_fn(ldb, ldif, &value, &el->values[0]);
655                         if (ret != 0) {
656                                 goto failed;
657                         }
658                         if (value.data != el->values[0].data) {
659                                 talloc_steal(el->values, el->values[0].data);
660                         }
661                         msg->num_elements++;
662                 }
663         }
664
665         return ldif;
666
667 failed:
668         talloc_free(ldif);
669         return NULL;
670 }
671
672
673
674 /*
675   a wrapper around ldif_read() for reading from FILE*
676 */
677 struct ldif_read_file_state {
678         FILE *f;
679 };
680
681 static int fgetc_file(void *private_data)
682 {
683         struct ldif_read_file_state *state = private_data;
684         return fgetc(state->f);
685 }
686
687 struct ldb_ldif *ldb_ldif_read_file(struct ldb_context *ldb, FILE *f)
688 {
689         struct ldif_read_file_state state;
690         state.f = f;
691         return ldb_ldif_read(ldb, fgetc_file, &state);
692 }
693
694
695 /*
696   a wrapper around ldif_read() for reading from const char*
697 */
698 struct ldif_read_string_state {
699         const char *s;
700 };
701
702 static int fgetc_string(void *private_data)
703 {
704         struct ldif_read_string_state *state = private_data;
705         if (state->s[0] != 0) {
706                 return *state->s++;
707         }
708         return EOF;
709 }
710
711 struct ldb_ldif *ldb_ldif_read_string(struct ldb_context *ldb, const char **s)
712 {
713         struct ldif_read_string_state state;
714         struct ldb_ldif *ldif;
715         state.s = *s;
716         ldif = ldb_ldif_read(ldb, fgetc_string, &state);
717         *s = state.s;
718         return ldif;
719 }
720
721
722 /*
723   wrapper around ldif_write() for a file
724 */
725 struct ldif_write_file_state {
726         FILE *f;
727 };
728
729 static int fprintf_file(void *private_data, const char *fmt, ...) PRINTF_ATTRIBUTE(2, 3);
730
731 static int fprintf_file(void *private_data, const char *fmt, ...)
732 {
733         struct ldif_write_file_state *state = private_data;
734         int ret;
735         va_list ap;
736
737         va_start(ap, fmt);
738         ret = vfprintf(state->f, fmt, ap);
739         va_end(ap);
740         return ret;
741 }
742
743 int ldb_ldif_write_file(struct ldb_context *ldb, FILE *f, const struct ldb_ldif *ldif)
744 {
745         struct ldif_write_file_state state;
746         state.f = f;
747         return ldb_ldif_write(ldb, fprintf_file, &state, ldif);
748 }