r16007: If no error string was setup by the backend, ensure that we always get
[kai/samba.git] / source / lib / ldb / common / ldb.c
1 /* 
2    ldb database library
3
4    Copyright (C) Andrew Tridgell  2004
5    Copyright (C) Simo Sorce  2005-2006
6
7      ** NOTE! The following LGPL license applies to the ldb
8      ** library. This does NOT imply that all of Samba is released
9      ** under the LGPL
10    
11    This library is free software; you can redistribute it and/or
12    modify it under the terms of the GNU Lesser General Public
13    License as published by the Free Software Foundation; either
14    version 2 of the License, or (at your option) any later version.
15
16    This library is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19    Lesser General Public License for more details.
20
21    You should have received a copy of the GNU Lesser General Public
22    License along with this library; if not, write to the Free Software
23    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24 */
25
26 /*
27  *  Name: ldb
28  *
29  *  Component: ldb core API
30  *
31  *  Description: core API routines interfacing to ldb backends
32  *
33  *  Author: Andrew Tridgell
34  */
35
36 #include "includes.h"
37 #include "ldb/include/includes.h"
38
39 /* 
40    initialise a ldb context
41    The mem_ctx is optional
42 */
43 struct ldb_context *ldb_init(void *mem_ctx)
44 {
45         struct ldb_context *ldb = talloc_zero(mem_ctx, struct ldb_context);
46         int ret;
47
48         ret = ldb_setup_wellknown_attributes(ldb);
49         if (ret != 0) {
50                 talloc_free(ldb);
51                 return NULL;
52         }
53
54         ldb_set_utf8_default(ldb);
55
56         return ldb;
57 }
58
59 static struct ldb_backend {
60         const char *name;
61         ldb_connect_fn connect_fn;
62         struct ldb_backend *prev, *next;
63 } *ldb_backends = NULL;
64 /*
65  register a new ldb backend
66 */
67 int ldb_register_backend(const char *url_prefix, ldb_connect_fn connectfn)
68 {
69         struct ldb_backend *backend = talloc(talloc_autofree_context(), struct ldb_backend);
70
71         /* Maybe check for duplicity here later on? */
72
73         backend->name = talloc_strdup(backend, url_prefix);
74         backend->connect_fn = connectfn;
75         DLIST_ADD(ldb_backends, backend);
76
77         return LDB_SUCCESS;
78 }
79
80 static ldb_connect_fn ldb_find_backend(const char *url)
81 {
82         struct ldb_backend *backend;
83
84         for (backend = ldb_backends; backend; backend = backend->next) {
85                 if (strncmp(backend->name, url, strlen(backend->name)) == 0) {
86                         return backend->connect_fn;
87                 }
88         }
89
90         return NULL;
91 }
92
93 /* 
94  connect to a database. The URL can either be one of the following forms
95    ldb://path
96    ldapi://path
97
98    flags is made up of LDB_FLG_*
99
100    the options are passed uninterpreted to the backend, and are
101    backend specific
102 */
103 int ldb_connect(struct ldb_context *ldb, const char *url, unsigned int flags, const char *options[])
104 {
105         int ret;
106         char *backend;
107         ldb_connect_fn fn;
108
109         if (strchr(url, ':') != NULL) {
110                 backend = talloc_strndup(ldb, url, strchr(url, ':')-url);
111         } else {
112                 /* Default to tdb */
113                 backend = talloc_strdup(ldb, "tdb");
114         }
115
116         fn = ldb_find_backend(backend);
117
118         if (fn == NULL) {
119                 if (ldb_try_load_dso(ldb, backend) == 0) {
120                         fn = ldb_find_backend(backend);
121                 }
122         }
123
124         talloc_free(backend);
125
126         if (fn == NULL) {
127                 ldb_debug(ldb, LDB_DEBUG_FATAL, "Unable to find backend for '%s'\n", url);
128                 return LDB_ERR_OTHER;
129         }
130
131         ret = fn(ldb, url, flags, options);
132
133         if (ret != LDB_SUCCESS) {
134                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to connect to '%s'\n", url);
135                 return ret;
136         }
137
138         if (ldb_load_modules(ldb, options) != LDB_SUCCESS) {
139                 ldb_debug(ldb, LDB_DEBUG_FATAL, "Unable to load modules for '%s'\n", url);
140                 return LDB_ERR_OTHER;
141         }
142
143         return LDB_SUCCESS;
144 }
145
146 void ldb_set_errstring(struct ldb_context *ldb, char *err_string)
147 {
148         if (ldb->err_string) {
149                 talloc_free(ldb->err_string);
150         }
151         ldb->err_string = talloc_steal(ldb, err_string);
152 }
153
154 void ldb_reset_err_string(struct ldb_context *ldb)
155 {
156         if (ldb->err_string) {
157                 talloc_free(ldb->err_string);
158                 ldb->err_string = NULL;
159         }
160 }
161
162 #define FIRST_OP(ldb, op) do { \
163         module = ldb->modules; \
164         while (module && module->ops->op == NULL) module = module->next; \
165         if (module == NULL) return LDB_ERR_OPERATIONS_ERROR; \
166 } while (0)
167
168 /*
169   start a transaction
170 */
171 int ldb_transaction_start(struct ldb_context *ldb)
172 {
173         struct ldb_module *module;
174         int status;
175         FIRST_OP(ldb, start_transaction);
176         
177         ldb->transaction_active++;
178
179         ldb_reset_err_string(ldb);
180
181         status = module->ops->start_transaction(module);
182         if (status != LDB_SUCCESS) {
183                 if (ldb->err_string == NULL) {
184                         /* no error string was setup by the backend */
185                         ldb_set_errstring(ldb, 
186                                           talloc_asprintf(ldb, "ldb transaction start error %d", status));
187                 }
188         }
189         return status;
190 }
191
192 /*
193   commit a transaction
194 */
195 int ldb_transaction_commit(struct ldb_context *ldb)
196 {
197         struct ldb_module *module;
198         int status;
199         FIRST_OP(ldb, end_transaction);
200
201         if (ldb->transaction_active > 0) {
202                 ldb->transaction_active--;
203         } else {
204                 return LDB_ERR_OPERATIONS_ERROR;
205         }
206
207         ldb_reset_err_string(ldb);
208
209         status = module->ops->end_transaction(module);
210         if (status != LDB_SUCCESS) {
211                 if (ldb->err_string == NULL) {
212                         /* no error string was setup by the backend */
213                         ldb_set_errstring(ldb, 
214                                           talloc_asprintf(ldb, "ldb transaction commit error %d", status));
215                 }
216         }
217         return status;
218 }
219
220 /*
221   cancel a transaction
222 */
223 int ldb_transaction_cancel(struct ldb_context *ldb)
224 {
225         struct ldb_module *module;
226         int status;
227         FIRST_OP(ldb, del_transaction);
228
229         if (ldb->transaction_active > 0) {
230                 ldb->transaction_active--;
231         } else {
232                 return LDB_ERR_OPERATIONS_ERROR;
233         }
234
235         status = module->ops->del_transaction(module);
236         if (status != LDB_SUCCESS) {
237                 if (ldb->err_string == NULL) {
238                         /* no error string was setup by the backend */
239                         ldb_set_errstring(ldb, 
240                                           talloc_asprintf(ldb, "ldb transaction cancel error %d", status));
241                 }
242         }
243         return status;
244 }
245
246 int ldb_async_wait(struct ldb_async_handle *handle, enum ldb_async_wait_type type)
247 {
248         if (!handle) {
249                 return LDB_SUCCESS;
250         }
251
252         return handle->module->ops->async_wait(handle, type);
253 }
254
255
256 /*
257   check for an error return from an op 
258   if an op fails, but has not setup an error string, then setup one now
259 */
260 static int ldb_op_finish(struct ldb_context *ldb, int status)
261 {
262         if (status == LDB_SUCCESS) {
263                 return ldb_transaction_commit(ldb);
264         }
265         if (ldb->err_string == NULL) {
266                 /* no error string was setup by the backend */
267                 ldb_set_errstring(ldb, 
268                                   talloc_asprintf(ldb, "%s (%d)", 
269                                                   ldb_strerror(status), status));
270         }
271         ldb_transaction_cancel(ldb);
272         return status;
273 }
274
275 /*
276   start an ldb request
277   NOTE: the request must be a talloc context.
278   returns LDB_ERR_* on errors.
279 */
280 int ldb_request(struct ldb_context *ldb, struct ldb_request *req)
281 {
282         struct ldb_module *module;
283         int ret;
284
285         ldb_reset_err_string(ldb);
286
287         /* call the first module in the chain */
288         switch (req->operation) {
289         case LDB_SEARCH:
290                 FIRST_OP(ldb, search);
291                 ret = module->ops->search(module, req);
292                 break;
293         case LDB_ADD:
294                 FIRST_OP(ldb, add);
295                 ret = module->ops->add(module, req);
296                 break;
297         case LDB_MODIFY:
298                 FIRST_OP(ldb, modify);
299                 ret = module->ops->modify(module, req);
300                 break;
301         case LDB_DELETE:
302                 FIRST_OP(ldb, del);
303                 ret = module->ops->del(module, req);
304                 break;
305         case LDB_RENAME:
306                 FIRST_OP(ldb, rename);
307                 ret = module->ops->rename(module, req);
308                 break;
309         default:
310                 FIRST_OP(ldb, request);
311                 ret = module->ops->request(module, req);
312                 break;
313         }
314
315         return ret;
316 }
317
318 /*
319   search the database given a LDAP-like search expression
320
321   returns an LDB error code
322
323   Use talloc_free to free the ldb_message returned in 'res', if successful
324
325 */
326 static int ldb_search_callback(struct ldb_context *ldb, void *context, struct ldb_async_result *ares)
327 {
328         struct ldb_result *res;
329         int n;
330         
331         if (!context) {
332                 ldb_set_errstring(ldb, talloc_asprintf(ldb, "NULL Context in callback"));
333                 return LDB_ERR_OPERATIONS_ERROR;
334         }       
335
336         res = *((struct ldb_result **)context);
337
338         if (!res || !ares) {
339                 goto error;
340         }
341
342         if (ares->type == LDB_REPLY_ENTRY) {
343                 res->msgs = talloc_realloc(res, res->msgs, struct ldb_message *, res->count + 2);
344                 if (! res->msgs) {
345                         goto error;
346                 }
347
348                 res->msgs[res->count + 1] = NULL;
349
350                 res->msgs[res->count] = talloc_steal(res->msgs, ares->message);
351                 if (! res->msgs[res->count]) {
352                         goto error;
353                 }
354
355                 res->count++;
356         }
357
358         if (ares->type == LDB_REPLY_REFERRAL) {
359                 if (res->refs) {
360                         for (n = 0; res->refs[n]; n++) /*noop*/ ;
361                 } else {
362                         n = 0;
363                 }
364
365                 res->refs = talloc_realloc(res, res->refs, char *, n + 2);
366                 if (! res->refs) {
367                         goto error;
368                 }
369
370                 res->refs[n] = talloc_steal(res->refs, ares->referral);
371                 res->refs[n + 1] = NULL;
372         }
373
374         if (ares->controls) {
375                 res->controls = talloc_steal(res, ares->controls);
376                 if (! res->controls) {
377                         goto error;
378                 }
379         }
380
381         talloc_free(ares);
382         return LDB_SUCCESS;
383
384 error:
385         talloc_free(ares);
386         talloc_free(res);
387         *((struct ldb_result **)context) = NULL;
388         return LDB_ERR_OPERATIONS_ERROR;
389 }
390
391 int ldb_search(struct ldb_context *ldb, 
392                const struct ldb_dn *base,
393                enum ldb_scope scope,
394                const char *expression,
395                const char * const *attrs, 
396                struct ldb_result **res)
397 {
398         struct ldb_request *req;
399         int ret;
400
401         *res = talloc_zero(ldb, struct ldb_result);
402         if (! *res) {
403                 return LDB_ERR_OPERATIONS_ERROR;
404         }
405
406         req = talloc(ldb, struct ldb_request);
407         if (req == NULL) {
408                 ldb_set_errstring(ldb, talloc_strdup(ldb, "Out of memory!"));
409                 return LDB_ERR_OPERATIONS_ERROR;
410         }
411
412         req->operation = LDB_SEARCH;
413         req->op.search.base = base;
414         req->op.search.scope = scope;
415
416         req->op.search.tree = ldb_parse_tree(req, expression);
417         if (req->op.search.tree == NULL) {
418                 ldb_set_errstring(ldb, talloc_strdup(ldb, "Unable to parse search expression"));
419                 talloc_free(req);
420                 return LDB_ERR_OPERATIONS_ERROR;
421         }
422
423         req->op.search.attrs = attrs;
424         req->controls = NULL;
425         req->async.context = res;
426         req->async.callback = ldb_search_callback;
427         req->async.timeout = 600; /* 10 minutes */
428
429         ret = ldb_request(ldb, req);
430         
431         if (ret == LDB_SUCCESS) {
432                 ret = ldb_async_wait(req->async.handle, LDB_WAIT_ALL);
433         }
434         
435         if (ret != LDB_SUCCESS) {
436                 talloc_free(*res);
437                 *res = NULL;
438         }
439
440         talloc_free(req);
441         return ret;
442 }
443
444 /* autostarts a transacion if none active */
445 static int ldb_autotransaction_request(struct ldb_context *ldb, struct ldb_request *req)
446 {
447         int ret, close_transaction;
448
449         close_transaction = 0;
450         if (!ldb->transaction_active) {
451                 ret = ldb_transaction_start(ldb);
452                 if (ret != LDB_SUCCESS) {
453                         return ret;
454                 }
455                 close_transaction = 1;
456         }
457
458         ret = ldb_request(ldb, req);
459         if (ret == LDB_SUCCESS) {
460                 ret = ldb_async_wait(req->async.handle, LDB_WAIT_ALL);
461         }
462
463         if (close_transaction) {
464                 return ldb_op_finish(ldb, ret);
465         }
466
467         if (ldb->err_string == NULL) {
468                 /* no error string was setup by the backend */
469                 ldb_set_errstring(ldb, 
470                                   talloc_asprintf(ldb, "%s (%d)", 
471                                                   ldb_strerror(ret), ret));
472         }
473
474         return ret;
475 }
476
477
478 /*
479   add a record to the database. Will fail if a record with the given class and key
480   already exists
481 */
482 int ldb_add(struct ldb_context *ldb, 
483             const struct ldb_message *message)
484 {
485         struct ldb_request *req;
486         int ret;
487
488         ret = ldb_msg_sanity_check(message);
489         if (ret != LDB_SUCCESS) return ret;
490
491         req = talloc(ldb, struct ldb_request);
492         if (req == NULL) {
493                 ldb_set_errstring(ldb, talloc_strdup(ldb, "Out of memory!"));
494                 return LDB_ERR_OPERATIONS_ERROR;
495         }
496
497         req->operation = LDB_ADD;
498         req->op.add.message = message;
499         req->controls = NULL;
500         req->async.context = NULL;
501         req->async.callback = NULL;
502         req->async.timeout = 600; /* 10 minutes */
503
504         /* do request and autostart a transaction */
505         ret = ldb_autotransaction_request(ldb, req);
506
507         talloc_free(req);
508         return ret;
509 }
510
511 /*
512   modify the specified attributes of a record
513 */
514 int ldb_modify(struct ldb_context *ldb, 
515                const struct ldb_message *message)
516 {
517         struct ldb_request *req;
518         int ret;
519
520         ret = ldb_msg_sanity_check(message);
521         if (ret != LDB_SUCCESS) return ret;
522
523         req = talloc(ldb, struct ldb_request);
524         if (req == NULL) {
525                 ldb_set_errstring(ldb, talloc_strdup(ldb, "Out of memory!"));
526                 return LDB_ERR_OPERATIONS_ERROR;
527         }
528
529         req->operation = LDB_MODIFY;
530         req->op.add.message = message;
531         req->controls = NULL;
532         req->async.context = NULL;
533         req->async.callback = NULL;
534         req->async.timeout = 600; /* 10 minutes */
535
536         /* do request and autostart a transaction */
537         ret = ldb_autotransaction_request(ldb, req);
538
539         talloc_free(req);
540         return ret;
541 }
542
543
544 /*
545   delete a record from the database
546 */
547 int ldb_delete(struct ldb_context *ldb, const struct ldb_dn *dn)
548 {
549         struct ldb_request *req;
550         int ret;
551
552         req = talloc(ldb, struct ldb_request);
553         if (req == NULL) {
554                 ldb_set_errstring(ldb, talloc_strdup(ldb, "Out of memory!"));
555                 return LDB_ERR_OPERATIONS_ERROR;
556         }
557
558         req->operation = LDB_DELETE;
559         req->op.del.dn = dn;
560         req->controls = NULL;
561         req->async.context = NULL;
562         req->async.callback = NULL;
563         req->async.timeout = 600; /* 10 minutes */
564
565         /* do request and autostart a transaction */
566         ret = ldb_autotransaction_request(ldb, req);
567
568         talloc_free(req);
569         return ret;
570 }
571
572 /*
573   rename a record in the database
574 */
575 int ldb_rename(struct ldb_context *ldb, const struct ldb_dn *olddn, const struct ldb_dn *newdn)
576 {
577         struct ldb_request *req;
578         int ret;
579
580         req = talloc(ldb, struct ldb_request);
581         if (req == NULL) {
582                 ldb_set_errstring(ldb, talloc_strdup(ldb, "Out of memory!"));
583                 return LDB_ERR_OPERATIONS_ERROR;
584         }
585
586         req->operation = LDB_RENAME;
587         req->op.rename.olddn = olddn;
588         req->op.rename.newdn = newdn;
589         req->controls = NULL;
590         req->async.context = NULL;
591         req->async.callback = NULL;
592         req->async.timeout = 600; /* 10 minutes */
593
594         /* do request and autostart a transaction */
595         ret = ldb_autotransaction_request(ldb, req);
596
597         talloc_free(req);
598         return ret;
599 }
600
601
602
603 /*
604   return extended error information 
605 */
606 const char *ldb_errstring(struct ldb_context *ldb)
607 {
608         if (ldb->err_string) {
609                 return ldb->err_string;
610         }
611
612         return NULL;
613 }
614
615 /*
616   return a string explaining what a ldb error constant meancs
617 */
618 const char *ldb_strerror(int ldb_err)
619 {
620         switch (ldb_err) {
621         case LDB_SUCCESS:
622                 return "Success";
623         case LDB_ERR_OPERATIONS_ERROR:
624                 return "Operations error";
625         case LDB_ERR_PROTOCOL_ERROR:
626                 return "Protocol error";
627         case LDB_ERR_TIME_LIMIT_EXCEEDED:
628                 return "Time limit exceeded";
629         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
630                 return "Size limit exceeded";
631         case LDB_ERR_COMPARE_FALSE:
632                 return "Compare false";
633         case LDB_ERR_COMPARE_TRUE:
634                 return "Compare true";
635         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
636                 return "Auth method not supported";
637         case LDB_ERR_STRONG_AUTH_REQUIRED:
638                 return "Strong auth required";
639 /* 9 RESERVED */
640         case LDB_ERR_REFERRAL:
641                 return "Referral error";
642         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
643                 return "Admin limit exceeded";
644         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
645                 return "Unsupported critical extension";
646         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
647                 return "Confidentiality required";
648         case LDB_ERR_SASL_BIND_IN_PROGRESS:
649                 return "SASL bind in progress";
650         case LDB_ERR_NO_SUCH_ATTRIBUTE:
651                 return "No such attribute";
652         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
653                 return "Undefined attribute type";
654         case LDB_ERR_INAPPROPRIATE_MATCHING:
655                 return "Inappropriate matching";
656         case LDB_ERR_CONSTRAINT_VIOLATION:
657                 return "Constraint violation";
658         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
659                 return "Attribute or value exists";
660         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
661                 return "Invalid attribute syntax";
662 /* 22-31 unused */
663         case LDB_ERR_NO_SUCH_OBJECT:
664                 return "No such object";
665         case LDB_ERR_ALIAS_PROBLEM:
666                 return "Alias problem";
667         case LDB_ERR_INVALID_DN_SYNTAX:
668                 return "Invalid DN syntax";
669 /* 35 RESERVED */
670         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
671                 return "Alias dereferencing problem";
672 /* 37-47 unused */
673         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
674                 return "Inappropriate authentication";
675         case LDB_ERR_INVALID_CREDENTIALS:
676                 return "Invalid credentials";
677         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
678                 return "insufficient access rights";
679         case LDB_ERR_BUSY:
680                 return "Busy";
681         case LDB_ERR_UNAVAILABLE:
682                 return "Unavailable";
683         case LDB_ERR_UNWILLING_TO_PERFORM:
684                 return "Unwilling to perform";
685         case LDB_ERR_LOOP_DETECT:
686                 return "Loop detect";
687 /* 55-63 unused */
688         case LDB_ERR_NAMING_VIOLATION:
689                 return "Naming violation";
690         case LDB_ERR_OBJECT_CLASS_VIOLATION:
691                 return "Object class violation";
692         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
693                 return "Not allowed on non-leaf";
694         case LDB_ERR_NOT_ALLOWED_ON_RDN:
695                 return "Not allowed on RDN";
696         case LDB_ERR_ENTRY_ALREADY_EXISTS:
697                 return "Entry already exists";
698         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
699                 return "Object class mods prohibited";
700 /* 70 RESERVED FOR CLDAP */
701         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
702                 return "Affects multiple DSAs";
703 /* 72-79 unused */
704         case LDB_ERR_OTHER:
705                 return "Other";
706         }
707
708         return "Unknown error";
709 }
710
711 /*
712   set backend specific opaque parameters
713 */
714 int ldb_set_opaque(struct ldb_context *ldb, const char *name, void *value)
715 {
716         struct ldb_opaque *o;
717
718         /* allow updating an existing value */
719         for (o=ldb->opaque;o;o=o->next) {
720                 if (strcmp(o->name, name) == 0) {
721                         o->value = value;
722                         return LDB_SUCCESS;
723                 }
724         }
725
726         o = talloc(ldb, struct ldb_opaque);
727         if (o == NULL) {
728                 ldb_oom(ldb);
729                 return LDB_ERR_OTHER;
730         }
731         o->next = ldb->opaque;
732         o->name = name;
733         o->value = value;
734         ldb->opaque = o;
735         return LDB_SUCCESS;
736 }
737
738 /*
739   get a previously set opaque value
740 */
741 void *ldb_get_opaque(struct ldb_context *ldb, const char *name)
742 {
743         struct ldb_opaque *o;
744         for (o=ldb->opaque;o;o=o->next) {
745                 if (strcmp(o->name, name) == 0) {
746                         return o->value;
747                 }
748         }
749         return NULL;
750 }