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