Until the new ldb changes land, make ldb_wait set the error string.
[amitay/samba.git] / source4 / 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 3 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, see <http://www.gnu.org/licenses/>.
23 */
24
25 /*
26  *  Name: ldb
27  *
28  *  Component: ldb core API
29  *
30  *  Description: core API routines interfacing to ldb backends
31  *
32  *  Author: Andrew Tridgell
33  */
34
35 #include "ldb_includes.h"
36
37 /* 
38    initialise a ldb context
39    The mem_ctx is optional
40 */
41 struct ldb_context *ldb_init(void *mem_ctx)
42 {
43         struct ldb_context *ldb = talloc_zero(mem_ctx, struct ldb_context);
44         int ret;
45
46         ret = ldb_setup_wellknown_attributes(ldb);
47         if (ret != 0) {
48                 talloc_free(ldb);
49                 return NULL;
50         }
51
52         ldb_set_utf8_default(ldb);
53         ldb_set_create_perms(ldb, 0666);
54         ldb_set_modules_dir(ldb, LDB_MODULESDIR);
55
56         return ldb;
57 }
58
59 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
66 static ldb_connect_fn ldb_find_backend(const char *url)
67 {
68         struct ldb_backend *backend;
69
70         for (backend = ldb_backends; backend; backend = backend->next) {
71                 if (strncmp(backend->name, url, strlen(backend->name)) == 0) {
72                         return backend->connect_fn;
73                 }
74         }
75
76         return NULL;
77 }
78
79 /*
80  register a new ldb backend
81 */
82 int ldb_register_backend(const char *url_prefix, ldb_connect_fn connectfn)
83 {
84         struct ldb_backend *backend = talloc(talloc_autofree_context(), struct ldb_backend);
85
86         if (ldb_find_backend(url_prefix)) {
87                 return LDB_SUCCESS;
88         }
89
90         /* Maybe check for duplicity here later on? */
91
92         backend->name = talloc_strdup(backend, url_prefix);
93         backend->connect_fn = connectfn;
94         DLIST_ADD(ldb_backends, backend);
95
96         return LDB_SUCCESS;
97 }
98
99 /* 
100    Return the ldb module form of a database. The URL can either be one of the following forms
101    ldb://path
102    ldapi://path
103
104    flags is made up of LDB_FLG_*
105
106    the options are passed uninterpreted to the backend, and are
107    backend specific.
108
109   This allows modules to get at only the backend module, for example where a module 
110   may wish to direct certain requests at a particular backend.
111 */
112 int ldb_connect_backend(struct ldb_context *ldb, const char *url, const char *options[],
113                         struct ldb_module **backend_module)
114 {
115         int ret;
116         char *backend;
117         ldb_connect_fn fn;
118
119         if (strchr(url, ':') != NULL) {
120                 backend = talloc_strndup(ldb, url, strchr(url, ':')-url);
121         } else {
122                 /* Default to tdb */
123                 backend = talloc_strdup(ldb, "tdb");
124         }
125
126         fn = ldb_find_backend(backend);
127
128         if (fn == NULL) {
129                 int (*init_fn) (void);
130
131                 init_fn = ldb_dso_load_symbol(ldb, backend,
132                                               "init_module");
133                 if (init_fn != NULL && init_fn() == 0) {
134                         fn = ldb_find_backend(backend);
135                 }
136         }
137
138         talloc_free(backend);
139
140         if (fn == NULL) {
141                 ldb_debug(ldb, LDB_DEBUG_FATAL, "Unable to find backend for '%s'\n", url);
142                 return LDB_ERR_OTHER;
143         }
144
145         ret = fn(ldb, url, ldb->flags, options, backend_module);
146
147         if (ret != LDB_SUCCESS) {
148                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to connect to '%s'\n", url);
149                 return ret;
150         }
151         return ret;
152 }
153
154 /*
155   try to autodetect a basedn if none specified. This fixes one of my
156   pet hates about ldapsearch, which is that you have to get a long,
157   complex basedn right to make any use of it.
158 */
159 void ldb_set_default_dns(struct ldb_context *ldb)
160 {
161         TALLOC_CTX *tmp_ctx;
162         int ret;
163         struct ldb_result *res;
164         struct ldb_dn *tmp_dn=NULL;
165         static const char *attrs[] = {
166                 "rootDomainNamingContext",
167                 "configurationNamingContext",
168                 "schemaNamingContext",
169                 "defaultNamingContext",
170                 NULL
171         };
172
173         tmp_ctx = talloc_new(ldb);
174         ret = ldb_search(ldb, ldb_dn_new(tmp_ctx, ldb, NULL), LDB_SCOPE_BASE, 
175                          "(objectClass=*)", attrs, &res);
176         if (ret == LDB_SUCCESS) {
177                 if (res->count == 1) {
178                         if (!ldb_get_opaque(ldb, "rootDomainNamingContext")) {
179                                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0], "rootDomainNamingContext");
180                                 ldb_set_opaque(ldb, "rootDomainNamingContext", tmp_dn);
181                         }
182
183                         if (!ldb_get_opaque(ldb, "configurationNamingContext")) {
184                                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0], "configurationNamingContext");
185                                 ldb_set_opaque(ldb, "configurationNamingContext", tmp_dn);
186                         }
187
188                         if (!ldb_get_opaque(ldb, "schemaNamingContext")) {
189                                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0], "schemaNamingContext");
190                                 ldb_set_opaque(ldb, "schemaNamingContext", tmp_dn);
191                         }
192
193                         if (!ldb_get_opaque(ldb, "defaultNamingContext")) {
194                                 tmp_dn = ldb_msg_find_attr_as_dn(ldb, ldb, res->msgs[0], "defaultNamingContext");
195                                 ldb_set_opaque(ldb, "defaultNamingContext", tmp_dn);
196                         }
197                 }
198                 talloc_free(res);
199         }
200
201         talloc_free(tmp_ctx);
202 }
203
204 struct ldb_dn *ldb_get_root_basedn(struct ldb_context *ldb)
205 {
206         return talloc_get_type(ldb_get_opaque(ldb, "rootDomainNamingContext"), struct ldb_dn);
207 }
208
209 struct ldb_dn *ldb_get_config_basedn(struct ldb_context *ldb)
210 {
211         return talloc_get_type(ldb_get_opaque(ldb, "configurationNamingContext"), struct ldb_dn);
212 }
213
214 struct ldb_dn *ldb_get_schema_basedn(struct ldb_context *ldb)
215 {
216         return talloc_get_type(ldb_get_opaque(ldb, "schemaNamingContext"), struct ldb_dn);
217 }
218
219 struct ldb_dn *ldb_get_default_basedn(struct ldb_context *ldb)
220 {
221         return talloc_get_type(ldb_get_opaque(ldb, "defaultNamingContext"), struct ldb_dn);
222 }
223
224 /* 
225  connect to a database. The URL can either be one of the following forms
226    ldb://path
227    ldapi://path
228
229    flags is made up of LDB_FLG_*
230
231    the options are passed uninterpreted to the backend, and are
232    backend specific
233 */
234 int ldb_connect(struct ldb_context *ldb, const char *url, unsigned int flags, const char *options[])
235 {
236         int ret;
237         const char *url2;
238         /* We seem to need to do this here, or else some utilities don't get ldb backends */
239         ldb_global_init();
240
241         ldb->flags = flags;
242
243         url2 = talloc_strdup(ldb, url);
244         if (!url2) {
245                 ldb_oom(ldb);
246                 return LDB_ERR_OPERATIONS_ERROR;
247         }
248         ret = ldb_set_opaque(ldb, "ldb_url", talloc_strdup(ldb, url2));
249         if (ret != LDB_SUCCESS) {
250                 return ret;
251         }
252
253         ret = ldb_connect_backend(ldb, url, options, &ldb->modules);
254         if (ret != LDB_SUCCESS) {
255                 return ret;
256         }
257
258         if (ldb_load_modules(ldb, options) != LDB_SUCCESS) {
259                 ldb_debug(ldb, LDB_DEBUG_FATAL, "Unable to load modules for %s: %s\n",
260                           url, ldb_errstring(ldb));
261                 return LDB_ERR_OTHER;
262         }
263
264         /* TODO: get timeout from options if available there */
265         ldb->default_timeout = 300; /* set default to 5 minutes */
266
267         /* set the default base dn */
268         ldb_set_default_dns(ldb);
269
270         return LDB_SUCCESS;
271 }
272
273 void ldb_set_errstring(struct ldb_context *ldb, const char *err_string)
274 {
275         if (ldb->err_string) {
276                 talloc_free(ldb->err_string);
277         }
278         ldb->err_string = talloc_strdup(ldb, err_string);
279 }
280
281 void ldb_asprintf_errstring(struct ldb_context *ldb, const char *format, ...)
282 {
283         va_list ap;
284         char *old_string = NULL;
285
286         if (ldb->err_string) {
287                 old_string = ldb->err_string;
288         }
289
290         va_start(ap, format);
291         ldb->err_string = talloc_vasprintf(ldb, format, ap);
292         va_end(ap);
293         talloc_free(old_string);
294 }
295
296 void ldb_reset_err_string(struct ldb_context *ldb)
297 {
298         if (ldb->err_string) {
299                 talloc_free(ldb->err_string);
300                 ldb->err_string = NULL;
301         }
302 }
303
304 #define FIRST_OP(ldb, op) do { \
305         module = ldb->modules;                                  \
306         while (module && module->ops->op == NULL) module = module->next; \
307         if (module == NULL) {                                           \
308                 ldb_asprintf_errstring(ldb, "unable to find module or backend to handle operation: " #op); \
309                 return LDB_ERR_OPERATIONS_ERROR;                        \
310         } \
311 } while (0)
312
313 /*
314   start a transaction
315 */
316 static int ldb_transaction_start_internal(struct ldb_context *ldb)
317 {
318         struct ldb_module *module;
319         int status;
320         FIRST_OP(ldb, start_transaction);
321
322         ldb_reset_err_string(ldb);
323
324         status = module->ops->start_transaction(module);
325         if (status != LDB_SUCCESS) {
326                 if (ldb->err_string == NULL) {
327                         /* no error string was setup by the backend */
328                         ldb_asprintf_errstring(ldb,
329                                                 "ldb transaction start: %s (%d)", 
330                                                 ldb_strerror(status), 
331                                                 status);
332                 }
333         }
334         return status;
335 }
336
337 /*
338   commit a transaction
339 */
340 static int ldb_transaction_commit_internal(struct ldb_context *ldb)
341 {
342         struct ldb_module *module;
343         int status;
344         FIRST_OP(ldb, end_transaction);
345
346         ldb_reset_err_string(ldb);
347
348         status = module->ops->end_transaction(module);
349         if (status != LDB_SUCCESS) {
350                 if (ldb->err_string == NULL) {
351                         /* no error string was setup by the backend */
352                         ldb_asprintf_errstring(ldb, 
353                                                 "ldb transaction commit: %s (%d)", 
354                                                 ldb_strerror(status), 
355                                                 status);
356                 }
357         }
358         return status;
359 }
360
361 /*
362   cancel a transaction
363 */
364 static int ldb_transaction_cancel_internal(struct ldb_context *ldb)
365 {
366         struct ldb_module *module;
367         int status;
368         FIRST_OP(ldb, del_transaction);
369
370         status = module->ops->del_transaction(module);
371         if (status != LDB_SUCCESS) {
372                 if (ldb->err_string == NULL) {
373                         /* no error string was setup by the backend */
374                         ldb_asprintf_errstring(ldb, 
375                                                 "ldb transaction cancel: %s (%d)", 
376                                                 ldb_strerror(status), 
377                                                 status);
378                 }
379         }
380         return status;
381 }
382
383 int ldb_transaction_start(struct ldb_context *ldb)
384 {
385         /* disable autotransactions */
386         ldb->transaction_active++;
387
388         return ldb_transaction_start_internal(ldb);
389 }
390
391 int ldb_transaction_commit(struct ldb_context *ldb)
392 {
393         /* renable autotransactions (when we reach 0) */
394         if (ldb->transaction_active > 0)
395                 ldb->transaction_active--;
396
397         return ldb_transaction_commit_internal(ldb);
398 }
399
400 int ldb_transaction_cancel(struct ldb_context *ldb)
401 {
402         /* renable autotransactions (when we reach 0) */
403         if (ldb->transaction_active > 0)
404                 ldb->transaction_active--;
405
406         return ldb_transaction_cancel_internal(ldb);
407 }
408
409 static int ldb_autotransaction_start(struct ldb_context *ldb)
410 {
411         /* explicit transaction active, ignore autotransaction request */
412         if (ldb->transaction_active)
413                 return LDB_SUCCESS;
414
415         return ldb_transaction_start_internal(ldb);
416 }
417
418 static int ldb_autotransaction_commit(struct ldb_context *ldb)
419 {
420         /* explicit transaction active, ignore autotransaction request */
421         if (ldb->transaction_active)
422                 return LDB_SUCCESS;
423
424         return ldb_transaction_commit_internal(ldb);
425 }
426
427 static int ldb_autotransaction_cancel(struct ldb_context *ldb)
428 {
429         /* explicit transaction active, ignore autotransaction request */
430         if (ldb->transaction_active)
431                 return LDB_SUCCESS;
432
433         return ldb_transaction_cancel_internal(ldb);
434 }
435
436 /* autostarts a transacion if none active */
437 static int ldb_autotransaction_request(struct ldb_context *ldb, struct ldb_request *req)
438 {
439         int ret;
440
441         ret = ldb_autotransaction_start(ldb);
442         if (ret != LDB_SUCCESS) {
443                 return ret;
444         }
445
446         ret = ldb_request(ldb, req);
447         if (ret == LDB_SUCCESS) {
448                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
449         }
450
451         if (ret == LDB_SUCCESS) {
452                 return ldb_autotransaction_commit(ldb);
453         }
454         ldb_autotransaction_cancel(ldb);
455
456         if (ldb->err_string == NULL) {
457                 /* no error string was setup by the backend */
458                 ldb_asprintf_errstring(ldb, "%s (%d)", ldb_strerror(ret), ret);
459         }
460
461         return ret;
462 }
463
464 int ldb_wait(struct ldb_handle *handle, enum ldb_wait_type type)
465 {
466         int ret;
467         if (!handle) {
468                 return LDB_SUCCESS;
469         }
470
471         ret = handle->module->ops->wait(handle, type);
472         if (!ldb_errstring(handle->module->ldb)) {
473                 /* Set a default error string, to place the blame somewhere */
474                 ldb_asprintf_errstring(handle->module->ldb, "error waiting on module %s: %s (%d)", handle->module->ops->name, ldb_strerror(ret), ret);
475         }
476         return ret;
477 }
478
479 /* set the specified timeout or, if timeout is 0 set the default timeout */
480 /* timeout == -1 means no timeout */
481 int ldb_set_timeout(struct ldb_context *ldb, struct ldb_request *req, int timeout)
482 {
483         if (req == NULL) return LDB_ERR_OPERATIONS_ERROR;
484         
485         if (timeout != 0) {
486                 req->timeout = timeout;
487         } else {
488                 req->timeout = ldb->default_timeout;
489         }
490         req->starttime = time(NULL);
491
492         return LDB_SUCCESS;
493 }
494
495 /* calculates the new timeout based on the previous starttime and timeout */
496 int ldb_set_timeout_from_prev_req(struct ldb_context *ldb, struct ldb_request *oldreq, struct ldb_request *newreq)
497 {
498         time_t now;
499
500         if (newreq == NULL) return LDB_ERR_OPERATIONS_ERROR;
501
502         now = time(NULL);
503
504         if (oldreq == NULL)
505                 return ldb_set_timeout(ldb, newreq, 0);
506
507         if ((now - oldreq->starttime) > oldreq->timeout) {
508                 return LDB_ERR_TIME_LIMIT_EXCEEDED;
509         }
510         newreq->starttime = oldreq->starttime;
511         newreq->timeout = oldreq->timeout - (now - oldreq->starttime);
512
513         return LDB_SUCCESS;
514 }
515
516
517 /* 
518    set the permissions for new files to be passed to open() in
519    backends that use local files
520  */
521 void ldb_set_create_perms(struct ldb_context *ldb, unsigned int perms)
522 {
523         ldb->create_perms = perms;
524 }
525
526 /*
527   start an ldb request
528   NOTE: the request must be a talloc context.
529   returns LDB_ERR_* on errors.
530 */
531 int ldb_request(struct ldb_context *ldb, struct ldb_request *req)
532 {
533         struct ldb_module *module;
534         int ret;
535
536         ldb_reset_err_string(ldb);
537
538         /* call the first module in the chain */
539         switch (req->operation) {
540         case LDB_SEARCH:
541                 FIRST_OP(ldb, search);
542                 ret = module->ops->search(module, req);
543                 break;
544         case LDB_ADD:
545                 FIRST_OP(ldb, add);
546                 ret = module->ops->add(module, req);
547                 break;
548         case LDB_MODIFY:
549                 FIRST_OP(ldb, modify);
550                 ret = module->ops->modify(module, req);
551                 break;
552         case LDB_DELETE:
553                 FIRST_OP(ldb, del);
554                 ret = module->ops->del(module, req);
555                 break;
556         case LDB_RENAME:
557                 FIRST_OP(ldb, rename);
558                 ret = module->ops->rename(module, req);
559                 break;
560         case LDB_EXTENDED:
561                 FIRST_OP(ldb, extended);
562                 ret = module->ops->extended(module, req);
563                 break;
564         case LDB_SEQUENCE_NUMBER:
565                 FIRST_OP(ldb, sequence_number);
566                 ret = module->ops->sequence_number(module, req);
567                 break;
568         default:
569                 FIRST_OP(ldb, request);
570                 ret = module->ops->request(module, req);
571                 break;
572         }
573
574         return ret;
575 }
576
577 /*
578   search the database given a LDAP-like search expression
579
580   returns an LDB error code
581
582   Use talloc_free to free the ldb_message returned in 'res', if successful
583
584 */
585 int ldb_search_default_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
586 {
587         struct ldb_result *res;
588         int n;
589         
590         if (!context) {
591                 ldb_set_errstring(ldb, "NULL Context in callback");
592                 return LDB_ERR_OPERATIONS_ERROR;
593         }       
594
595         res = talloc_get_type(context, struct ldb_result);
596
597         if (!res || !ares) {
598                 ldb_set_errstring(ldb, "NULL res or ares in callback");
599                 goto error;
600         }
601
602         switch (ares->type) {
603         case LDB_REPLY_ENTRY:
604                 res->msgs = talloc_realloc(res, res->msgs, struct ldb_message *, res->count + 2);
605                 if (! res->msgs) {
606                         goto error;
607                 }
608
609                 res->msgs[res->count + 1] = NULL;
610
611                 res->msgs[res->count] = talloc_move(res->msgs, &ares->message);
612                 res->count++;
613                 break;
614         case LDB_REPLY_REFERRAL:
615                 if (res->refs) {
616                         for (n = 0; res->refs[n]; n++) /*noop*/ ;
617                 } else {
618                         n = 0;
619                 }
620
621                 res->refs = talloc_realloc(res, res->refs, char *, n + 2);
622                 if (! res->refs) {
623                         goto error;
624                 }
625
626                 res->refs[n] = talloc_move(res->refs, &ares->referral);
627                 res->refs[n + 1] = NULL;
628                 break;
629         case LDB_REPLY_EXTENDED:
630         case LDB_REPLY_DONE:
631                 /* TODO: we should really support controls on entries and referrals too! */
632                 res->controls = talloc_move(res, &ares->controls);
633                 break;          
634         }
635         talloc_free(ares);
636         return LDB_SUCCESS;
637
638 error:
639         talloc_free(ares);
640         return LDB_ERR_OPERATIONS_ERROR;
641 }
642
643 int ldb_build_search_req(struct ldb_request **ret_req,
644                         struct ldb_context *ldb,
645                         void *mem_ctx,
646                         struct ldb_dn *base,
647                         enum ldb_scope scope,
648                         const char *expression,
649                         const char * const *attrs,
650                         struct ldb_control **controls,
651                         void *context,
652                         ldb_request_callback_t callback)
653 {
654         struct ldb_request *req;
655
656         *ret_req = NULL;
657
658         req = talloc(mem_ctx, struct ldb_request);
659         if (req == NULL) {
660                 ldb_set_errstring(ldb, "Out of Memory");
661                 return LDB_ERR_OPERATIONS_ERROR;
662         }
663
664         req->operation = LDB_SEARCH;
665         if (base == NULL) {
666                 req->op.search.base = ldb_dn_new(req, ldb, NULL);
667         } else {
668                 req->op.search.base = base;
669         }
670         req->op.search.scope = scope;
671
672         req->op.search.tree = ldb_parse_tree(req, expression);
673         if (req->op.search.tree == NULL) {
674                 ldb_set_errstring(ldb, "Unable to parse search expression");
675                 talloc_free(req);
676                 return LDB_ERR_OPERATIONS_ERROR;
677         }
678
679         req->op.search.attrs = attrs;
680         req->controls = controls;
681         req->context = context;
682         req->callback = callback;
683
684         *ret_req = req;
685         return LDB_SUCCESS;
686 }
687
688 int ldb_build_add_req(struct ldb_request **ret_req,
689                         struct ldb_context *ldb,
690                         void *mem_ctx,
691                         const struct ldb_message *message,
692                         struct ldb_control **controls,
693                         void *context,
694                         ldb_request_callback_t callback)
695 {
696         struct ldb_request *req;
697
698         *ret_req = NULL;
699
700         req = talloc(mem_ctx, struct ldb_request);
701         if (req == NULL) {
702                 ldb_set_errstring(ldb, "Out of Memory");
703                 return LDB_ERR_OPERATIONS_ERROR;
704         }
705
706         req->operation = LDB_ADD;
707         req->op.add.message = message;
708         req->controls = controls;
709         req->context = context;
710         req->callback = callback;
711
712         *ret_req = req;
713
714         return LDB_SUCCESS;
715 }
716
717 int ldb_build_mod_req(struct ldb_request **ret_req,
718                         struct ldb_context *ldb,
719                         void *mem_ctx,
720                         const struct ldb_message *message,
721                         struct ldb_control **controls,
722                         void *context,
723                         ldb_request_callback_t callback)
724 {
725         struct ldb_request *req;
726
727         *ret_req = NULL;
728
729         req = talloc(mem_ctx, struct ldb_request);
730         if (req == NULL) {
731                 ldb_set_errstring(ldb, "Out of Memory");
732                 return LDB_ERR_OPERATIONS_ERROR;
733         }
734
735         req->operation = LDB_MODIFY;
736         req->op.mod.message = message;
737         req->controls = controls;
738         req->context = context;
739         req->callback = callback;
740
741         *ret_req = req;
742
743         return LDB_SUCCESS;
744 }
745
746 int ldb_build_del_req(struct ldb_request **ret_req,
747                         struct ldb_context *ldb,
748                         void *mem_ctx,
749                         struct ldb_dn *dn,
750                         struct ldb_control **controls,
751                         void *context,
752                         ldb_request_callback_t callback)
753 {
754         struct ldb_request *req;
755
756         *ret_req = NULL;
757
758         req = talloc(mem_ctx, struct ldb_request);
759         if (req == NULL) {
760                 ldb_set_errstring(ldb, "Out of Memory");
761                 return LDB_ERR_OPERATIONS_ERROR;
762         }
763
764         req->operation = LDB_DELETE;
765         req->op.del.dn = dn;
766         req->controls = controls;
767         req->context = context;
768         req->callback = callback;
769
770         *ret_req = req;
771
772         return LDB_SUCCESS;
773 }
774
775 int ldb_build_rename_req(struct ldb_request **ret_req,
776                         struct ldb_context *ldb,
777                         void *mem_ctx,
778                         struct ldb_dn *olddn,
779                         struct ldb_dn *newdn,
780                         struct ldb_control **controls,
781                         void *context,
782                         ldb_request_callback_t callback)
783 {
784         struct ldb_request *req;
785
786         *ret_req = NULL;
787
788         req = talloc(mem_ctx, struct ldb_request);
789         if (req == NULL) {
790                 ldb_set_errstring(ldb, "Out of Memory");
791                 return LDB_ERR_OPERATIONS_ERROR;
792         }
793
794         req->operation = LDB_RENAME;
795         req->op.rename.olddn = olddn;
796         req->op.rename.newdn = newdn;
797         req->controls = controls;
798         req->context = context;
799         req->callback = callback;
800
801         *ret_req = req;
802
803         return LDB_SUCCESS;
804 }
805
806 int ldb_extended_default_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
807 {
808         struct ldb_result *res;
809         
810         if (!context) {
811                 ldb_set_errstring(ldb, "NULL Context in callback");
812                 return LDB_ERR_OPERATIONS_ERROR;
813         }
814
815         res = talloc_get_type(context, struct ldb_result);
816         if (!res || !ares) {
817                 ldb_set_errstring(ldb, "NULL res or ares in callback");
818                 goto error;
819         }
820
821         switch (ares->type) {
822         case LDB_REPLY_ENTRY:
823         case LDB_REPLY_REFERRAL:
824         case LDB_REPLY_DONE:
825                 ldb_set_errstring(ldb, "invalid ares type in callback");
826                 goto error;
827         case LDB_REPLY_EXTENDED:
828                 /* TODO: we should really support controls on entries and referrals too! */
829                 res->extended = talloc_move(res, &ares->response);
830                 res->controls = talloc_move(res, &ares->controls);
831                 break;          
832         }
833         talloc_free(ares);
834         return LDB_SUCCESS;
835
836 error:
837         talloc_free(ares);
838         return LDB_ERR_OPERATIONS_ERROR;
839 }
840
841 int ldb_build_extended_req(struct ldb_request **ret_req,
842                            struct ldb_context *ldb,
843                            void *mem_ctx,
844                            const char *oid,
845                            void *data,
846                            struct ldb_control **controls,
847                            void *context,
848                            ldb_request_callback_t callback)
849 {
850         struct ldb_request *req;
851
852         *ret_req = NULL;
853
854         req = talloc(mem_ctx, struct ldb_request);
855         if (req == NULL) {
856                 ldb_set_errstring(ldb, "Out of Memory");
857                 return LDB_ERR_OPERATIONS_ERROR;
858         }
859
860         req->operation = LDB_EXTENDED;
861         req->op.extended.oid = oid;
862         req->op.extended.data = data;
863         req->controls = controls;
864         req->context = context;
865         req->callback = callback;
866
867         *ret_req = req;
868
869         return LDB_SUCCESS;
870 }
871
872 int ldb_extended(struct ldb_context *ldb, 
873                  const char *oid,
874                  void *data,
875                  struct ldb_result **_res)
876 {
877         struct ldb_request *req;
878         int ret;
879         struct ldb_result *res;
880
881         *_res = NULL;
882
883         res = talloc_zero(ldb, struct ldb_result);
884         if (!res) {
885                 return LDB_ERR_OPERATIONS_ERROR;
886         }
887
888         ret = ldb_build_extended_req(&req, ldb, ldb,
889                                      oid, data, NULL,
890                                      res, ldb_extended_default_callback);
891         if (ret != LDB_SUCCESS) goto done;
892
893         ldb_set_timeout(ldb, req, 0); /* use default timeout */
894
895         ret = ldb_request(ldb, req);
896         
897         if (ret == LDB_SUCCESS) {
898                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
899         }
900
901         talloc_free(req);
902
903 done:
904         if (ret != LDB_SUCCESS) {
905                 talloc_free(res);
906         }
907
908         *_res = res;
909         return ret;
910 }
911
912 /*
913   note that ldb_search() will automatically replace a NULL 'base' value with the 
914   defaultNamingContext from the rootDSE if available.
915 */
916 int ldb_search(struct ldb_context *ldb, 
917                struct ldb_dn *base,
918                enum ldb_scope scope,
919                const char *expression,
920                const char * const *attrs, 
921                struct ldb_result **_res)
922 {
923         struct ldb_request *req;
924         int ret;
925         struct ldb_result *res;
926
927         *_res = NULL;
928
929         res = talloc_zero(ldb, struct ldb_result);
930         if (!res) {
931                 return LDB_ERR_OPERATIONS_ERROR;
932         }
933
934         ret = ldb_build_search_req(&req, ldb, ldb,
935                                         base?base:ldb_get_default_basedn(ldb),
936                                         scope,
937                                         expression,
938                                         attrs,
939                                         NULL,
940                                         res,
941                                         ldb_search_default_callback);
942
943         if (ret != LDB_SUCCESS) goto done;
944
945         ldb_set_timeout(ldb, req, 0); /* use default timeout */
946
947         ret = ldb_request(ldb, req);
948         
949         if (ret == LDB_SUCCESS) {
950                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
951         }
952
953         talloc_free(req);
954
955 done:
956         if (ret != LDB_SUCCESS) {
957                 talloc_free(res);
958         }
959
960         *_res = res;
961         return ret;
962 }
963
964 /*
965  a useful search function where you can easily define the expression and that
966  takes a memory context where results are allocated
967 */
968
969 int ldb_search_exp_fmt(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_result **result,
970                         struct ldb_dn *base, enum ldb_scope scope, const char * const *attrs,
971                         const char *exp_fmt, ...)
972 {
973         struct ldb_result *res;
974         char *expression;
975         va_list ap;
976         int ret;
977
978         res = NULL;
979         *result = NULL;
980
981         va_start(ap, exp_fmt);
982         expression = talloc_vasprintf(mem_ctx, exp_fmt, ap);
983         va_end(ap);
984
985         if ( ! expression) {
986                 return LDB_ERR_OPERATIONS_ERROR;
987         }
988
989         ret = ldb_search(ldb, base, scope, expression, attrs, &res);
990
991         if (ret == LDB_SUCCESS) {
992                 talloc_steal(mem_ctx, res);
993                 *result = res;
994         }
995
996         talloc_free(expression);
997
998         return ret;
999 }
1000
1001 /*
1002   add a record to the database. Will fail if a record with the given class and key
1003   already exists
1004 */
1005 int ldb_add(struct ldb_context *ldb, 
1006             const struct ldb_message *message)
1007 {
1008         struct ldb_request *req;
1009         int ret;
1010
1011         ret = ldb_msg_sanity_check(ldb, message);
1012         if (ret != LDB_SUCCESS) {
1013                 return ret;
1014         }
1015
1016         ret = ldb_build_add_req(&req, ldb, ldb,
1017                                         message,
1018                                         NULL,
1019                                         NULL,
1020                                         NULL);
1021
1022         if (ret != LDB_SUCCESS) return ret;
1023
1024         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1025
1026         /* do request and autostart a transaction */
1027         ret = ldb_autotransaction_request(ldb, req);
1028
1029         talloc_free(req);
1030         return ret;
1031 }
1032
1033 /*
1034   modify the specified attributes of a record
1035 */
1036 int ldb_modify(struct ldb_context *ldb, 
1037                const struct ldb_message *message)
1038 {
1039         struct ldb_request *req;
1040         int ret;
1041
1042         ret = ldb_msg_sanity_check(ldb, message);
1043         if (ret != LDB_SUCCESS) {
1044                 return ret;
1045         }
1046
1047         ret = ldb_build_mod_req(&req, ldb, ldb,
1048                                         message,
1049                                         NULL,
1050                                         NULL,
1051                                         NULL);
1052
1053         if (ret != LDB_SUCCESS) return ret;
1054
1055         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1056
1057         /* do request and autostart a transaction */
1058         ret = ldb_autotransaction_request(ldb, req);
1059
1060         talloc_free(req);
1061         return ret;
1062 }
1063
1064
1065 /*
1066   delete a record from the database
1067 */
1068 int ldb_delete(struct ldb_context *ldb, struct ldb_dn *dn)
1069 {
1070         struct ldb_request *req;
1071         int ret;
1072
1073         ret = ldb_build_del_req(&req, ldb, ldb,
1074                                         dn,
1075                                         NULL,
1076                                         NULL,
1077                                         NULL);
1078
1079         if (ret != LDB_SUCCESS) return ret;
1080
1081         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1082
1083         /* do request and autostart a transaction */
1084         ret = ldb_autotransaction_request(ldb, req);
1085
1086         talloc_free(req);
1087         return ret;
1088 }
1089
1090 /*
1091   rename a record in the database
1092 */
1093 int ldb_rename(struct ldb_context *ldb, struct ldb_dn *olddn, struct ldb_dn *newdn)
1094 {
1095         struct ldb_request *req;
1096         int ret;
1097
1098         ret = ldb_build_rename_req(&req, ldb, ldb,
1099                                         olddn,
1100                                         newdn,
1101                                         NULL,
1102                                         NULL,
1103                                         NULL);
1104
1105         if (ret != LDB_SUCCESS) return ret;
1106
1107         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1108
1109         /* do request and autostart a transaction */
1110         ret = ldb_autotransaction_request(ldb, req);
1111
1112         talloc_free(req);
1113         return ret;
1114 }
1115
1116
1117 /*
1118   return the global sequence number
1119 */
1120 int ldb_sequence_number(struct ldb_context *ldb, enum ldb_sequence_type type, uint64_t *seq_num)
1121 {
1122         struct ldb_request *req;
1123         int ret;
1124
1125         req = talloc(ldb, struct ldb_request);
1126         if (req == NULL) {
1127                 ldb_set_errstring(ldb, "Out of Memory");
1128                 return LDB_ERR_OPERATIONS_ERROR;
1129         }
1130
1131         req->operation = LDB_SEQUENCE_NUMBER;
1132         req->controls = NULL;
1133         req->context = NULL;
1134         req->callback = NULL;
1135         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1136
1137         req->op.seq_num.type = type;
1138         /* do request and autostart a transaction */
1139         ret = ldb_request(ldb, req);
1140         
1141         if (ret == LDB_SUCCESS) {
1142                 *seq_num = req->op.seq_num.seq_num;
1143         }
1144
1145         talloc_free(req);
1146         return ret;
1147 }
1148
1149
1150
1151 /*
1152   return extended error information 
1153 */
1154 const char *ldb_errstring(struct ldb_context *ldb)
1155 {
1156         if (ldb->err_string) {
1157                 return ldb->err_string;
1158         }
1159
1160         return NULL;
1161 }
1162
1163 /*
1164   return a string explaining what a ldb error constant meancs
1165 */
1166 const char *ldb_strerror(int ldb_err)
1167 {
1168         switch (ldb_err) {
1169         case LDB_SUCCESS:
1170                 return "Success";
1171         case LDB_ERR_OPERATIONS_ERROR:
1172                 return "Operations error";
1173         case LDB_ERR_PROTOCOL_ERROR:
1174                 return "Protocol error";
1175         case LDB_ERR_TIME_LIMIT_EXCEEDED:
1176                 return "Time limit exceeded";
1177         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
1178                 return "Size limit exceeded";
1179         case LDB_ERR_COMPARE_FALSE:
1180                 return "Compare false";
1181         case LDB_ERR_COMPARE_TRUE:
1182                 return "Compare true";
1183         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
1184                 return "Auth method not supported";
1185         case LDB_ERR_STRONG_AUTH_REQUIRED:
1186                 return "Strong auth required";
1187 /* 9 RESERVED */
1188         case LDB_ERR_REFERRAL:
1189                 return "Referral error";
1190         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
1191                 return "Admin limit exceeded";
1192         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
1193                 return "Unsupported critical extension";
1194         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
1195                 return "Confidentiality required";
1196         case LDB_ERR_SASL_BIND_IN_PROGRESS:
1197                 return "SASL bind in progress";
1198         case LDB_ERR_NO_SUCH_ATTRIBUTE:
1199                 return "No such attribute";
1200         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
1201                 return "Undefined attribute type";
1202         case LDB_ERR_INAPPROPRIATE_MATCHING:
1203                 return "Inappropriate matching";
1204         case LDB_ERR_CONSTRAINT_VIOLATION:
1205                 return "Constraint violation";
1206         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
1207                 return "Attribute or value exists";
1208         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
1209                 return "Invalid attribute syntax";
1210 /* 22-31 unused */
1211         case LDB_ERR_NO_SUCH_OBJECT:
1212                 return "No such object";
1213         case LDB_ERR_ALIAS_PROBLEM:
1214                 return "Alias problem";
1215         case LDB_ERR_INVALID_DN_SYNTAX:
1216                 return "Invalid DN syntax";
1217 /* 35 RESERVED */
1218         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
1219                 return "Alias dereferencing problem";
1220 /* 37-47 unused */
1221         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
1222                 return "Inappropriate authentication";
1223         case LDB_ERR_INVALID_CREDENTIALS:
1224                 return "Invalid credentials";
1225         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
1226                 return "insufficient access rights";
1227         case LDB_ERR_BUSY:
1228                 return "Busy";
1229         case LDB_ERR_UNAVAILABLE:
1230                 return "Unavailable";
1231         case LDB_ERR_UNWILLING_TO_PERFORM:
1232                 return "Unwilling to perform";
1233         case LDB_ERR_LOOP_DETECT:
1234                 return "Loop detect";
1235 /* 55-63 unused */
1236         case LDB_ERR_NAMING_VIOLATION:
1237                 return "Naming violation";
1238         case LDB_ERR_OBJECT_CLASS_VIOLATION:
1239                 return "Object class violation";
1240         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
1241                 return "Not allowed on non-leaf";
1242         case LDB_ERR_NOT_ALLOWED_ON_RDN:
1243                 return "Not allowed on RDN";
1244         case LDB_ERR_ENTRY_ALREADY_EXISTS:
1245                 return "Entry already exists";
1246         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
1247                 return "Object class mods prohibited";
1248 /* 70 RESERVED FOR CLDAP */
1249         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
1250                 return "Affects multiple DSAs";
1251 /* 72-79 unused */
1252         case LDB_ERR_OTHER:
1253                 return "Other";
1254         }
1255
1256         return "Unknown error";
1257 }
1258
1259 /*
1260   set backend specific opaque parameters
1261 */
1262 int ldb_set_opaque(struct ldb_context *ldb, const char *name, void *value)
1263 {
1264         struct ldb_opaque *o;
1265
1266         /* allow updating an existing value */
1267         for (o=ldb->opaque;o;o=o->next) {
1268                 if (strcmp(o->name, name) == 0) {
1269                         o->value = value;
1270                         return LDB_SUCCESS;
1271                 }
1272         }
1273
1274         o = talloc(ldb, struct ldb_opaque);
1275         if (o == NULL) {
1276                 ldb_oom(ldb);
1277                 return LDB_ERR_OTHER;
1278         }
1279         o->next = ldb->opaque;
1280         o->name = name;
1281         o->value = value;
1282         ldb->opaque = o;
1283         return LDB_SUCCESS;
1284 }
1285
1286 /*
1287   get a previously set opaque value
1288 */
1289 void *ldb_get_opaque(struct ldb_context *ldb, const char *name)
1290 {
1291         struct ldb_opaque *o;
1292         for (o=ldb->opaque;o;o=o->next) {
1293                 if (strcmp(o->name, name) == 0) {
1294                         return o->value;
1295                 }
1296         }
1297         return NULL;
1298 }