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