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