]> git.samba.org - metze/samba/wip.git/blob - source4/lib/ldb/common/ldb.c
Merge commit 'release-4-0-0alpha2' into v4-0-test
[metze/samba/wip.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         if (!handle) {
467                 return LDB_SUCCESS;
468         }
469
470         return handle->module->ops->wait(handle, type);
471 }
472
473 /* set the specified timeout or, if timeout is 0 set the default timeout */
474 /* timeout == -1 means no timeout */
475 int ldb_set_timeout(struct ldb_context *ldb, struct ldb_request *req, int timeout)
476 {
477         if (req == NULL) return LDB_ERR_OPERATIONS_ERROR;
478         
479         if (timeout != 0) {
480                 req->timeout = timeout;
481         } else {
482                 req->timeout = ldb->default_timeout;
483         }
484         req->starttime = time(NULL);
485
486         return LDB_SUCCESS;
487 }
488
489 /* calculates the new timeout based on the previous starttime and timeout */
490 int ldb_set_timeout_from_prev_req(struct ldb_context *ldb, struct ldb_request *oldreq, struct ldb_request *newreq)
491 {
492         time_t now;
493
494         if (newreq == NULL) return LDB_ERR_OPERATIONS_ERROR;
495
496         now = time(NULL);
497
498         if (oldreq == NULL)
499                 return ldb_set_timeout(ldb, newreq, 0);
500
501         if ((now - oldreq->starttime) > oldreq->timeout) {
502                 return LDB_ERR_TIME_LIMIT_EXCEEDED;
503         }
504         newreq->starttime = oldreq->starttime;
505         newreq->timeout = oldreq->timeout - (now - oldreq->starttime);
506
507         return LDB_SUCCESS;
508 }
509
510
511 /* 
512    set the permissions for new files to be passed to open() in
513    backends that use local files
514  */
515 void ldb_set_create_perms(struct ldb_context *ldb, unsigned int perms)
516 {
517         ldb->create_perms = perms;
518 }
519
520 /*
521   start an ldb request
522   NOTE: the request must be a talloc context.
523   returns LDB_ERR_* on errors.
524 */
525 int ldb_request(struct ldb_context *ldb, struct ldb_request *req)
526 {
527         struct ldb_module *module;
528         int ret;
529
530         ldb_reset_err_string(ldb);
531
532         /* call the first module in the chain */
533         switch (req->operation) {
534         case LDB_SEARCH:
535                 FIRST_OP(ldb, search);
536                 ret = module->ops->search(module, req);
537                 break;
538         case LDB_ADD:
539                 FIRST_OP(ldb, add);
540                 ret = module->ops->add(module, req);
541                 break;
542         case LDB_MODIFY:
543                 FIRST_OP(ldb, modify);
544                 ret = module->ops->modify(module, req);
545                 break;
546         case LDB_DELETE:
547                 FIRST_OP(ldb, del);
548                 ret = module->ops->del(module, req);
549                 break;
550         case LDB_RENAME:
551                 FIRST_OP(ldb, rename);
552                 ret = module->ops->rename(module, req);
553                 break;
554         case LDB_EXTENDED:
555                 FIRST_OP(ldb, extended);
556                 ret = module->ops->extended(module, req);
557                 break;
558         case LDB_SEQUENCE_NUMBER:
559                 FIRST_OP(ldb, sequence_number);
560                 ret = module->ops->sequence_number(module, req);
561                 break;
562         default:
563                 FIRST_OP(ldb, request);
564                 ret = module->ops->request(module, req);
565                 break;
566         }
567
568         return ret;
569 }
570
571 /*
572   search the database given a LDAP-like search expression
573
574   returns an LDB error code
575
576   Use talloc_free to free the ldb_message returned in 'res', if successful
577
578 */
579 int ldb_search_default_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
580 {
581         struct ldb_result *res;
582         int n;
583         
584         if (!context) {
585                 ldb_set_errstring(ldb, "NULL Context in callback");
586                 return LDB_ERR_OPERATIONS_ERROR;
587         }       
588
589         res = talloc_get_type(context, struct ldb_result);
590
591         if (!res || !ares) {
592                 ldb_set_errstring(ldb, "NULL res or ares in callback");
593                 goto error;
594         }
595
596         switch (ares->type) {
597         case LDB_REPLY_ENTRY:
598                 res->msgs = talloc_realloc(res, res->msgs, struct ldb_message *, res->count + 2);
599                 if (! res->msgs) {
600                         goto error;
601                 }
602
603                 res->msgs[res->count + 1] = NULL;
604
605                 res->msgs[res->count] = talloc_move(res->msgs, &ares->message);
606                 res->count++;
607                 break;
608         case LDB_REPLY_REFERRAL:
609                 if (res->refs) {
610                         for (n = 0; res->refs[n]; n++) /*noop*/ ;
611                 } else {
612                         n = 0;
613                 }
614
615                 res->refs = talloc_realloc(res, res->refs, char *, n + 2);
616                 if (! res->refs) {
617                         goto error;
618                 }
619
620                 res->refs[n] = talloc_move(res->refs, &ares->referral);
621                 res->refs[n + 1] = NULL;
622                 break;
623         case LDB_REPLY_EXTENDED:
624         case LDB_REPLY_DONE:
625                 /* TODO: we should really support controls on entries and referrals too! */
626                 res->controls = talloc_move(res, &ares->controls);
627                 break;          
628         }
629         talloc_free(ares);
630         return LDB_SUCCESS;
631
632 error:
633         talloc_free(ares);
634         return LDB_ERR_OPERATIONS_ERROR;
635 }
636
637 int ldb_build_search_req(struct ldb_request **ret_req,
638                         struct ldb_context *ldb,
639                         void *mem_ctx,
640                         struct ldb_dn *base,
641                         enum ldb_scope scope,
642                         const char *expression,
643                         const char * const *attrs,
644                         struct ldb_control **controls,
645                         void *context,
646                         ldb_request_callback_t callback)
647 {
648         struct ldb_request *req;
649
650         *ret_req = NULL;
651
652         req = talloc(mem_ctx, struct ldb_request);
653         if (req == NULL) {
654                 ldb_set_errstring(ldb, "Out of Memory");
655                 return LDB_ERR_OPERATIONS_ERROR;
656         }
657
658         req->operation = LDB_SEARCH;
659         if (base == NULL) {
660                 req->op.search.base = ldb_dn_new(req, ldb, NULL);
661         } else {
662                 req->op.search.base = base;
663         }
664         req->op.search.scope = scope;
665
666         req->op.search.tree = ldb_parse_tree(req, expression);
667         if (req->op.search.tree == NULL) {
668                 ldb_set_errstring(ldb, "Unable to parse search expression");
669                 talloc_free(req);
670                 return LDB_ERR_OPERATIONS_ERROR;
671         }
672
673         req->op.search.attrs = attrs;
674         req->controls = controls;
675         req->context = context;
676         req->callback = callback;
677
678         *ret_req = req;
679         return LDB_SUCCESS;
680 }
681
682 int ldb_build_add_req(struct ldb_request **ret_req,
683                         struct ldb_context *ldb,
684                         void *mem_ctx,
685                         const struct ldb_message *message,
686                         struct ldb_control **controls,
687                         void *context,
688                         ldb_request_callback_t callback)
689 {
690         struct ldb_request *req;
691
692         *ret_req = NULL;
693
694         req = talloc(mem_ctx, struct ldb_request);
695         if (req == NULL) {
696                 ldb_set_errstring(ldb, "Out of Memory");
697                 return LDB_ERR_OPERATIONS_ERROR;
698         }
699
700         req->operation = LDB_ADD;
701         req->op.add.message = message;
702         req->controls = controls;
703         req->context = context;
704         req->callback = callback;
705
706         *ret_req = req;
707
708         return LDB_SUCCESS;
709 }
710
711 int ldb_build_mod_req(struct ldb_request **ret_req,
712                         struct ldb_context *ldb,
713                         void *mem_ctx,
714                         const struct ldb_message *message,
715                         struct ldb_control **controls,
716                         void *context,
717                         ldb_request_callback_t callback)
718 {
719         struct ldb_request *req;
720
721         *ret_req = NULL;
722
723         req = talloc(mem_ctx, struct ldb_request);
724         if (req == NULL) {
725                 ldb_set_errstring(ldb, "Out of Memory");
726                 return LDB_ERR_OPERATIONS_ERROR;
727         }
728
729         req->operation = LDB_MODIFY;
730         req->op.mod.message = message;
731         req->controls = controls;
732         req->context = context;
733         req->callback = callback;
734
735         *ret_req = req;
736
737         return LDB_SUCCESS;
738 }
739
740 int ldb_build_del_req(struct ldb_request **ret_req,
741                         struct ldb_context *ldb,
742                         void *mem_ctx,
743                         struct ldb_dn *dn,
744                         struct ldb_control **controls,
745                         void *context,
746                         ldb_request_callback_t callback)
747 {
748         struct ldb_request *req;
749
750         *ret_req = NULL;
751
752         req = talloc(mem_ctx, struct ldb_request);
753         if (req == NULL) {
754                 ldb_set_errstring(ldb, "Out of Memory");
755                 return LDB_ERR_OPERATIONS_ERROR;
756         }
757
758         req->operation = LDB_DELETE;
759         req->op.del.dn = dn;
760         req->controls = controls;
761         req->context = context;
762         req->callback = callback;
763
764         *ret_req = req;
765
766         return LDB_SUCCESS;
767 }
768
769 int ldb_build_rename_req(struct ldb_request **ret_req,
770                         struct ldb_context *ldb,
771                         void *mem_ctx,
772                         struct ldb_dn *olddn,
773                         struct ldb_dn *newdn,
774                         struct ldb_control **controls,
775                         void *context,
776                         ldb_request_callback_t callback)
777 {
778         struct ldb_request *req;
779
780         *ret_req = NULL;
781
782         req = talloc(mem_ctx, struct ldb_request);
783         if (req == NULL) {
784                 ldb_set_errstring(ldb, "Out of Memory");
785                 return LDB_ERR_OPERATIONS_ERROR;
786         }
787
788         req->operation = LDB_RENAME;
789         req->op.rename.olddn = olddn;
790         req->op.rename.newdn = newdn;
791         req->controls = controls;
792         req->context = context;
793         req->callback = callback;
794
795         *ret_req = req;
796
797         return LDB_SUCCESS;
798 }
799
800 int ldb_extended_default_callback(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
801 {
802         struct ldb_result *res;
803         
804         if (!context) {
805                 ldb_set_errstring(ldb, "NULL Context in callback");
806                 return LDB_ERR_OPERATIONS_ERROR;
807         }
808
809         res = talloc_get_type(context, struct ldb_result);
810         if (!res || !ares) {
811                 ldb_set_errstring(ldb, "NULL res or ares in callback");
812                 goto error;
813         }
814
815         switch (ares->type) {
816         case LDB_REPLY_ENTRY:
817         case LDB_REPLY_REFERRAL:
818         case LDB_REPLY_DONE:
819                 ldb_set_errstring(ldb, "invalid ares type in callback");
820                 goto error;
821         case LDB_REPLY_EXTENDED:
822                 /* TODO: we should really support controls on entries and referrals too! */
823                 res->extended = talloc_move(res, &ares->response);
824                 res->controls = talloc_move(res, &ares->controls);
825                 break;          
826         }
827         talloc_free(ares);
828         return LDB_SUCCESS;
829
830 error:
831         talloc_free(ares);
832         return LDB_ERR_OPERATIONS_ERROR;
833 }
834
835 int ldb_build_extended_req(struct ldb_request **ret_req,
836                            struct ldb_context *ldb,
837                            void *mem_ctx,
838                            const char *oid,
839                            void *data,
840                            struct ldb_control **controls,
841                            void *context,
842                            ldb_request_callback_t callback)
843 {
844         struct ldb_request *req;
845
846         *ret_req = NULL;
847
848         req = talloc(mem_ctx, struct ldb_request);
849         if (req == NULL) {
850                 ldb_set_errstring(ldb, "Out of Memory");
851                 return LDB_ERR_OPERATIONS_ERROR;
852         }
853
854         req->operation = LDB_EXTENDED;
855         req->op.extended.oid = oid;
856         req->op.extended.data = data;
857         req->controls = controls;
858         req->context = context;
859         req->callback = callback;
860
861         *ret_req = req;
862
863         return LDB_SUCCESS;
864 }
865
866 int ldb_extended(struct ldb_context *ldb, 
867                  const char *oid,
868                  void *data,
869                  struct ldb_result **_res)
870 {
871         struct ldb_request *req;
872         int ret;
873         struct ldb_result *res;
874
875         *_res = NULL;
876
877         res = talloc_zero(ldb, struct ldb_result);
878         if (!res) {
879                 return LDB_ERR_OPERATIONS_ERROR;
880         }
881
882         ret = ldb_build_extended_req(&req, ldb, ldb,
883                                      oid, data, NULL,
884                                      res, ldb_extended_default_callback);
885         if (ret != LDB_SUCCESS) goto done;
886
887         ldb_set_timeout(ldb, req, 0); /* use default timeout */
888
889         ret = ldb_request(ldb, req);
890         
891         if (ret == LDB_SUCCESS) {
892                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
893         }
894
895         talloc_free(req);
896
897 done:
898         if (ret != LDB_SUCCESS) {
899                 talloc_free(res);
900         }
901
902         *_res = res;
903         return ret;
904 }
905
906 /*
907   note that ldb_search() will automatically replace a NULL 'base' value with the 
908   defaultNamingContext from the rootDSE if available.
909 */
910 int ldb_search(struct ldb_context *ldb, 
911                struct ldb_dn *base,
912                enum ldb_scope scope,
913                const char *expression,
914                const char * const *attrs, 
915                struct ldb_result **_res)
916 {
917         struct ldb_request *req;
918         int ret;
919         struct ldb_result *res;
920
921         *_res = NULL;
922
923         res = talloc_zero(ldb, struct ldb_result);
924         if (!res) {
925                 return LDB_ERR_OPERATIONS_ERROR;
926         }
927
928         ret = ldb_build_search_req(&req, ldb, ldb,
929                                         base?base:ldb_get_default_basedn(ldb),
930                                         scope,
931                                         expression,
932                                         attrs,
933                                         NULL,
934                                         res,
935                                         ldb_search_default_callback);
936
937         if (ret != LDB_SUCCESS) goto done;
938
939         ldb_set_timeout(ldb, req, 0); /* use default timeout */
940
941         ret = ldb_request(ldb, req);
942         
943         if (ret == LDB_SUCCESS) {
944                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
945         }
946
947         talloc_free(req);
948
949 done:
950         if (ret != LDB_SUCCESS) {
951                 talloc_free(res);
952         }
953
954         *_res = res;
955         return ret;
956 }
957
958 /*
959  a useful search function where you can easily define the expression and that
960  takes a memory context where results are allocated
961 */
962
963 int ldb_search_exp_fmt(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_result **result,
964                         struct ldb_dn *base, enum ldb_scope scope, const char * const *attrs,
965                         const char *exp_fmt, ...)
966 {
967         struct ldb_result *res;
968         char *expression;
969         va_list ap;
970         int ret;
971
972         res = NULL;
973         *result = NULL;
974
975         va_start(ap, exp_fmt);
976         expression = talloc_vasprintf(mem_ctx, exp_fmt, ap);
977         va_end(ap);
978
979         if ( ! expression) {
980                 return LDB_ERR_OPERATIONS_ERROR;
981         }
982
983         ret = ldb_search(ldb, base, scope, expression, attrs, &res);
984
985         if (ret == LDB_SUCCESS) {
986                 talloc_steal(mem_ctx, res);
987                 *result = res;
988         }
989
990         talloc_free(expression);
991
992         return ret;
993 }
994
995 /*
996   add a record to the database. Will fail if a record with the given class and key
997   already exists
998 */
999 int ldb_add(struct ldb_context *ldb, 
1000             const struct ldb_message *message)
1001 {
1002         struct ldb_request *req;
1003         int ret;
1004
1005         ret = ldb_msg_sanity_check(ldb, message);
1006         if (ret != LDB_SUCCESS) {
1007                 return ret;
1008         }
1009
1010         ret = ldb_build_add_req(&req, ldb, ldb,
1011                                         message,
1012                                         NULL,
1013                                         NULL,
1014                                         NULL);
1015
1016         if (ret != LDB_SUCCESS) return ret;
1017
1018         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1019
1020         /* do request and autostart a transaction */
1021         ret = ldb_autotransaction_request(ldb, req);
1022
1023         talloc_free(req);
1024         return ret;
1025 }
1026
1027 /*
1028   modify the specified attributes of a record
1029 */
1030 int ldb_modify(struct ldb_context *ldb, 
1031                const struct ldb_message *message)
1032 {
1033         struct ldb_request *req;
1034         int ret;
1035
1036         ret = ldb_msg_sanity_check(ldb, message);
1037         if (ret != LDB_SUCCESS) {
1038                 return ret;
1039         }
1040
1041         ret = ldb_build_mod_req(&req, ldb, ldb,
1042                                         message,
1043                                         NULL,
1044                                         NULL,
1045                                         NULL);
1046
1047         if (ret != LDB_SUCCESS) return ret;
1048
1049         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1050
1051         /* do request and autostart a transaction */
1052         ret = ldb_autotransaction_request(ldb, req);
1053
1054         talloc_free(req);
1055         return ret;
1056 }
1057
1058
1059 /*
1060   delete a record from the database
1061 */
1062 int ldb_delete(struct ldb_context *ldb, struct ldb_dn *dn)
1063 {
1064         struct ldb_request *req;
1065         int ret;
1066
1067         ret = ldb_build_del_req(&req, ldb, ldb,
1068                                         dn,
1069                                         NULL,
1070                                         NULL,
1071                                         NULL);
1072
1073         if (ret != LDB_SUCCESS) return ret;
1074
1075         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1076
1077         /* do request and autostart a transaction */
1078         ret = ldb_autotransaction_request(ldb, req);
1079
1080         talloc_free(req);
1081         return ret;
1082 }
1083
1084 /*
1085   rename a record in the database
1086 */
1087 int ldb_rename(struct ldb_context *ldb, struct ldb_dn *olddn, struct ldb_dn *newdn)
1088 {
1089         struct ldb_request *req;
1090         int ret;
1091
1092         ret = ldb_build_rename_req(&req, ldb, ldb,
1093                                         olddn,
1094                                         newdn,
1095                                         NULL,
1096                                         NULL,
1097                                         NULL);
1098
1099         if (ret != LDB_SUCCESS) return ret;
1100
1101         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1102
1103         /* do request and autostart a transaction */
1104         ret = ldb_autotransaction_request(ldb, req);
1105
1106         talloc_free(req);
1107         return ret;
1108 }
1109
1110
1111 /*
1112   return the global sequence number
1113 */
1114 int ldb_sequence_number(struct ldb_context *ldb, enum ldb_sequence_type type, uint64_t *seq_num)
1115 {
1116         struct ldb_request *req;
1117         int ret;
1118
1119         req = talloc(ldb, struct ldb_request);
1120         if (req == NULL) {
1121                 ldb_set_errstring(ldb, "Out of Memory");
1122                 return LDB_ERR_OPERATIONS_ERROR;
1123         }
1124
1125         req->operation = LDB_SEQUENCE_NUMBER;
1126         req->controls = NULL;
1127         req->context = NULL;
1128         req->callback = NULL;
1129         ldb_set_timeout(ldb, req, 0); /* use default timeout */
1130
1131         req->op.seq_num.type = type;
1132         /* do request and autostart a transaction */
1133         ret = ldb_request(ldb, req);
1134         
1135         if (ret == LDB_SUCCESS) {
1136                 *seq_num = req->op.seq_num.seq_num;
1137         }
1138
1139         talloc_free(req);
1140         return ret;
1141 }
1142
1143
1144
1145 /*
1146   return extended error information 
1147 */
1148 const char *ldb_errstring(struct ldb_context *ldb)
1149 {
1150         if (ldb->err_string) {
1151                 return ldb->err_string;
1152         }
1153
1154         return NULL;
1155 }
1156
1157 /*
1158   return a string explaining what a ldb error constant meancs
1159 */
1160 const char *ldb_strerror(int ldb_err)
1161 {
1162         switch (ldb_err) {
1163         case LDB_SUCCESS:
1164                 return "Success";
1165         case LDB_ERR_OPERATIONS_ERROR:
1166                 return "Operations error";
1167         case LDB_ERR_PROTOCOL_ERROR:
1168                 return "Protocol error";
1169         case LDB_ERR_TIME_LIMIT_EXCEEDED:
1170                 return "Time limit exceeded";
1171         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
1172                 return "Size limit exceeded";
1173         case LDB_ERR_COMPARE_FALSE:
1174                 return "Compare false";
1175         case LDB_ERR_COMPARE_TRUE:
1176                 return "Compare true";
1177         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
1178                 return "Auth method not supported";
1179         case LDB_ERR_STRONG_AUTH_REQUIRED:
1180                 return "Strong auth required";
1181 /* 9 RESERVED */
1182         case LDB_ERR_REFERRAL:
1183                 return "Referral error";
1184         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
1185                 return "Admin limit exceeded";
1186         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
1187                 return "Unsupported critical extension";
1188         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
1189                 return "Confidentiality required";
1190         case LDB_ERR_SASL_BIND_IN_PROGRESS:
1191                 return "SASL bind in progress";
1192         case LDB_ERR_NO_SUCH_ATTRIBUTE:
1193                 return "No such attribute";
1194         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
1195                 return "Undefined attribute type";
1196         case LDB_ERR_INAPPROPRIATE_MATCHING:
1197                 return "Inappropriate matching";
1198         case LDB_ERR_CONSTRAINT_VIOLATION:
1199                 return "Constraint violation";
1200         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
1201                 return "Attribute or value exists";
1202         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
1203                 return "Invalid attribute syntax";
1204 /* 22-31 unused */
1205         case LDB_ERR_NO_SUCH_OBJECT:
1206                 return "No such object";
1207         case LDB_ERR_ALIAS_PROBLEM:
1208                 return "Alias problem";
1209         case LDB_ERR_INVALID_DN_SYNTAX:
1210                 return "Invalid DN syntax";
1211 /* 35 RESERVED */
1212         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
1213                 return "Alias dereferencing problem";
1214 /* 37-47 unused */
1215         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
1216                 return "Inappropriate authentication";
1217         case LDB_ERR_INVALID_CREDENTIALS:
1218                 return "Invalid credentials";
1219         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
1220                 return "insufficient access rights";
1221         case LDB_ERR_BUSY:
1222                 return "Busy";
1223         case LDB_ERR_UNAVAILABLE:
1224                 return "Unavailable";
1225         case LDB_ERR_UNWILLING_TO_PERFORM:
1226                 return "Unwilling to perform";
1227         case LDB_ERR_LOOP_DETECT:
1228                 return "Loop detect";
1229 /* 55-63 unused */
1230         case LDB_ERR_NAMING_VIOLATION:
1231                 return "Naming violation";
1232         case LDB_ERR_OBJECT_CLASS_VIOLATION:
1233                 return "Object class violation";
1234         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
1235                 return "Not allowed on non-leaf";
1236         case LDB_ERR_NOT_ALLOWED_ON_RDN:
1237                 return "Not allowed on RDN";
1238         case LDB_ERR_ENTRY_ALREADY_EXISTS:
1239                 return "Entry already exists";
1240         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
1241                 return "Object class mods prohibited";
1242 /* 70 RESERVED FOR CLDAP */
1243         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
1244                 return "Affects multiple DSAs";
1245 /* 72-79 unused */
1246         case LDB_ERR_OTHER:
1247                 return "Other";
1248         }
1249
1250         return "Unknown error";
1251 }
1252
1253 /*
1254   set backend specific opaque parameters
1255 */
1256 int ldb_set_opaque(struct ldb_context *ldb, const char *name, void *value)
1257 {
1258         struct ldb_opaque *o;
1259
1260         /* allow updating an existing value */
1261         for (o=ldb->opaque;o;o=o->next) {
1262                 if (strcmp(o->name, name) == 0) {
1263                         o->value = value;
1264                         return LDB_SUCCESS;
1265                 }
1266         }
1267
1268         o = talloc(ldb, struct ldb_opaque);
1269         if (o == NULL) {
1270                 ldb_oom(ldb);
1271                 return LDB_ERR_OTHER;
1272         }
1273         o->next = ldb->opaque;
1274         o->name = name;
1275         o->value = value;
1276         ldb->opaque = o;
1277         return LDB_SUCCESS;
1278 }
1279
1280 /*
1281   get a previously set opaque value
1282 */
1283 void *ldb_get_opaque(struct ldb_context *ldb, const char *name)
1284 {
1285         struct ldb_opaque *o;
1286         for (o=ldb->opaque;o;o=o->next) {
1287                 if (strcmp(o->name, name) == 0) {
1288                         return o->value;
1289                 }
1290         }
1291         return NULL;
1292 }