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