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