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