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