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