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