r15964: fix error handling in ldb_ildap backend
[kai/samba.git] / source4 / lib / ldb / ldb_ildap / ldb_ildap.c
1 /* 
2    ldb database library - ildap backend
3
4    Copyright (C) Andrew Tridgell  2005
5    Copyright (C) Simo Sorce       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_ildap
28  *
29  *  Component: ldb ildap backend
30  *
31  *  Description: This is a ldb backend for the internal ldap
32  *  client library in Samba4. By using this backend we are
33  *  independent of a system ldap library
34  *
35  *  Author: Andrew Tridgell
36  *
37  *  Modifications:
38  *
39  *  - description: make the module use asyncronous calls
40  *    date: Feb 2006
41  *    author: Simo Sorce
42  */
43
44
45 #include "includes.h"
46 #include "ldb/include/includes.h"
47
48 #include "lib/events/events.h"
49 #include "libcli/ldap/ldap.h"
50 #include "libcli/ldap/ldap_client.h"
51 #include "auth/auth.h"
52
53 struct ildb_private {
54         struct ldap_connection *ldap;
55         struct ldb_message *rootDSE;
56         struct ldb_context *ldb;
57 };
58
59 struct ildb_async_context {
60         struct ldb_module *module;
61         struct ldap_request *req;
62         void *context;
63         int (*callback)(struct ldb_context *, void *, struct ldb_async_result *);
64 };
65
66 /*
67   convert a ldb_message structure to a list of ldap_mod structures
68   ready for ildap_add() or ildap_modify()
69 */
70 static struct ldap_mod **ildb_msg_to_mods(void *mem_ctx, int *num_mods,
71                                           const struct ldb_message *msg, int use_flags)
72 {
73         struct ldap_mod **mods;
74         unsigned int i;
75         int n = 0;
76
77         /* allocate maximum number of elements needed */
78         mods = talloc_array(mem_ctx, struct ldap_mod *, msg->num_elements+1);
79         if (!mods) {
80                 errno = ENOMEM;
81                 return NULL;
82         }
83         mods[0] = NULL;
84
85         for (i = 0; i < msg->num_elements; i++) {
86                 const struct ldb_message_element *el = &msg->elements[i];
87
88                 mods[n] = talloc(mods, struct ldap_mod);
89                 if (!mods[n]) {
90                         goto failed;
91                 }
92                 mods[n + 1] = NULL;
93                 mods[n]->type = 0;
94                 mods[n]->attrib = *el;
95                 if (use_flags) {
96                         switch (el->flags & LDB_FLAG_MOD_MASK) {
97                         case LDB_FLAG_MOD_ADD:
98                                 mods[n]->type = LDAP_MODIFY_ADD;
99                                 break;
100                         case LDB_FLAG_MOD_DELETE:
101                                 mods[n]->type = LDAP_MODIFY_DELETE;
102                                 break;
103                         case LDB_FLAG_MOD_REPLACE:
104                                 mods[n]->type = LDAP_MODIFY_REPLACE;
105                                 break;
106                         }
107                 }
108                 n++;
109         }
110
111         *num_mods = n;
112         return mods;
113
114 failed:
115         talloc_free(mods);
116         return NULL;
117 }
118
119
120 /*
121   map an ildap NTSTATUS to a ldb error code
122 */
123 static int ildb_map_error(struct ildb_private *ildb, NTSTATUS status)
124 {
125         if (NT_STATUS_IS_OK(status)) {
126                 return LDB_SUCCESS;
127         }
128         talloc_free(ildb->ldb->err_string);
129         ildb->ldb->err_string = talloc_strdup(ildb, ldap_errstr(ildb->ldap, status));
130         if (NT_STATUS_IS_LDAP(status)) {
131                 return NT_STATUS_LDAP_CODE(status);
132         }
133         return LDB_ERR_OPERATIONS_ERROR;
134 }
135
136 static void ildb_request_timeout(struct event_context *ev, struct timed_event *te,
137                                  struct timeval t, void *private_data)
138 {
139         struct ldb_async_handle *handle = talloc_get_type(private_data, struct ldb_async_handle);
140         struct ildb_async_context *ac = talloc_get_type(handle->private_data, struct ildb_async_context);
141
142         if (ac->req->state == LDAP_REQUEST_PENDING) {
143                 DLIST_REMOVE(ac->req->conn->pending, ac->req);
144         }
145
146         handle->status = LDB_ERR_OPERATIONS_ERROR;
147
148         return;
149 }
150
151 static void ildb_callback(struct ldap_request *req)
152 {
153         struct ldb_async_handle *handle = talloc_get_type(req->async.private_data, struct ldb_async_handle);
154         struct ildb_async_context *ac = talloc_get_type(handle->private_data, struct ildb_async_context);
155         struct ildb_private *ildb = talloc_get_type(ac->module->private_data, struct ildb_private);
156         NTSTATUS status;
157         int i;
158
159         handle->status = LDB_SUCCESS;
160
161         if (!NT_STATUS_IS_OK(req->status)) {
162                 handle->status = ildb_map_error(ildb, req->status);
163                 return;
164         }
165
166         if (req->num_replies < 1) {
167                 handle->status = LDB_ERR_OPERATIONS_ERROR;
168                 return;
169         } 
170                 
171         switch (req->type) {
172
173         case LDAP_TAG_ModifyRequest:
174                 if (req->replies[0]->type != LDAP_TAG_ModifyResponse) {
175                         handle->status = LDB_ERR_PROTOCOL_ERROR;
176                         return;
177                 }
178                 status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
179                 handle->status = ildb_map_error(ildb, status);
180                 if (ac->callback && handle->status == LDB_SUCCESS) {
181                         /* FIXME: build a corresponding ares to pass on */
182                         handle->status = ac->callback(ac->module->ldb, ac->context, NULL);
183                 }
184                 handle->state = LDB_ASYNC_DONE;
185                 break;
186
187         case LDAP_TAG_AddRequest:
188                 if (req->replies[0]->type != LDAP_TAG_AddResponse) {
189                         handle->status = LDB_ERR_PROTOCOL_ERROR;
190                         return;
191                 }
192                 status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
193                 handle->status = ildb_map_error(ildb, status);
194                 if (ac->callback && handle->status == LDB_SUCCESS) {
195                         /* FIXME: build a corresponding ares to pass on */
196                         handle->status = ac->callback(ac->module->ldb, ac->context, NULL);
197                 }
198                 handle->state = LDB_ASYNC_DONE;
199                 break;
200
201         case LDAP_TAG_DelRequest:
202                 if (req->replies[0]->type != LDAP_TAG_DelResponse) {
203                         handle->status = LDB_ERR_PROTOCOL_ERROR;
204                         return;
205                 }
206                 status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
207                 handle->status = ildb_map_error(ildb, status);
208                 if (ac->callback && handle->status == LDB_SUCCESS) {
209                         /* FIXME: build a corresponding ares to pass on */
210                         handle->status = ac->callback(ac->module->ldb, ac->context, NULL);
211                 }
212                 handle->state = LDB_ASYNC_DONE;
213                 break;
214
215         case LDAP_TAG_ModifyDNRequest:
216                 if (req->replies[0]->type != LDAP_TAG_ModifyDNResponse) {
217                         handle->status = LDB_ERR_PROTOCOL_ERROR;
218                         return;
219                 }
220                 status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
221                 handle->status = ildb_map_error(ildb, status);
222                 if (ac->callback && handle->status == LDB_SUCCESS) {
223                         /* FIXME: build a corresponding ares to pass on */
224                         handle->status = ac->callback(ac->module->ldb, ac->context, NULL);
225                 }
226                 handle->state = LDB_ASYNC_DONE;
227                 break;
228
229         case LDAP_TAG_SearchRequest:
230                 /* loop over all messages */
231                 for (i = 0; i < req->num_replies; i++) {
232                         struct ldap_SearchResEntry *search;
233                         struct ldb_async_result *ares = NULL;
234                         struct ldap_message *msg;
235                         int ret;
236
237                         ares = talloc_zero(ac, struct ldb_async_result);
238                         if (!ares) {
239                                 handle->status = LDB_ERR_OPERATIONS_ERROR;
240                                 return;
241                         }
242
243                         msg = req->replies[i];
244                         switch (msg->type) {
245
246                         case LDAP_TAG_SearchResultDone:
247
248                                 status = ldap_check_response(req->conn, &msg->r.GeneralResult);
249                                 if (!NT_STATUS_IS_OK(status)) {
250                                         ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Error: %s\n" ,ldap_errstr(req->conn, status));
251                                         handle->status = ildb_map_error(ildb, status);
252                                         return;
253                                 }
254                                 
255                                 if (msg->controls) {
256                                         ares->controls = talloc_steal(ares, msg->controls);
257                                 }
258                                 if (msg->r.SearchResultDone.resultcode) {
259                                         if (msg->r.SearchResultDone.errormessage) {
260                                                 ldb_set_errstring(ac->module->ldb, talloc_strdup(ac->module, msg->r.SearchResultDone.errormessage));
261                                         }
262                                 }
263
264                                 handle->status = msg->r.SearchResultDone.resultcode;
265                                 handle->state = LDB_ASYNC_DONE;
266                                 ares->type = LDB_REPLY_DONE;
267                                 break;
268
269                         case LDAP_TAG_SearchResultEntry:
270
271
272                                 ares->message = ldb_msg_new(ares);
273                                 if (!ares->message) {
274                                         handle->status = LDB_ERR_OPERATIONS_ERROR;
275                                         return;
276                                 }
277
278                                 search = &(msg->r.SearchResultEntry);
279                 
280                                 ares->message->dn = ldb_dn_explode_or_special(ares->message, search->dn);
281                                 if (ares->message->dn == NULL) {
282                                         handle->status = LDB_ERR_OPERATIONS_ERROR;
283                                         return;
284                                 }
285                                 ares->message->num_elements = search->num_attributes;
286                                 ares->message->elements = talloc_steal(ares->message, search->attributes);
287
288                                 handle->status = LDB_SUCCESS;
289                                 handle->state = LDB_ASYNC_PENDING;
290                                 ares->type = LDB_REPLY_ENTRY;
291                                 break;
292
293                         case LDAP_TAG_SearchResultReference:
294
295                                 ares->referral = talloc_strdup(ares, msg->r.SearchResultReference.referral);
296                                 
297                                 handle->status = LDB_SUCCESS;
298                                 handle->state = LDB_ASYNC_PENDING;
299                                 ares->type = LDB_REPLY_REFERRAL;
300                                 break;
301
302                         default:
303                                 /* TAG not handled, fail ! */
304                                 handle->status = LDB_ERR_PROTOCOL_ERROR;
305                                 return;
306                         }
307
308                         ret = ac->callback(ac->module->ldb, ac->context, ares);
309                         if (ret) {
310                                 handle->status = ret;
311                         }
312                 }
313
314                 talloc_free(req->replies);
315                 req->replies = NULL;
316                 req->num_replies = 0;
317
318                 break;
319                 
320         default:
321                 handle->status = LDB_ERR_PROTOCOL_ERROR;
322                 return;
323         }
324 }
325
326 static int ildb_request_send(struct ldb_module *module, struct ldap_message *msg,
327                              void *context,
328                              int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
329                              int timeout,
330                              struct ldb_async_handle **handle)
331 {
332         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
333         struct ildb_async_context *ildb_ac;
334         struct ldb_async_handle *h;
335         struct ldap_request *req;
336
337         h = talloc_zero(ildb->ldap, struct ldb_async_handle);
338         if (h == NULL) {
339                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Out of Memory"));
340                 return LDB_ERR_OPERATIONS_ERROR;
341         }
342
343         h->module = module;
344
345         ildb_ac = talloc(h, struct ildb_async_context);
346         if (ildb_ac == NULL) {
347                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Out of Memory"));
348                 talloc_free(h);
349                 return LDB_ERR_OPERATIONS_ERROR;
350         }
351
352         h->private_data = (void *)ildb_ac;
353
354         h->state = LDB_ASYNC_INIT;
355         h->status = LDB_SUCCESS;
356
357         req = ldap_request_send(ildb->ldap, msg);
358         if (req == NULL) {
359                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "async send request failed"));
360                 return LDB_ERR_OPERATIONS_ERROR;
361         }
362
363         ildb_ac->req = talloc_steal(ildb_ac, req);
364         ildb_ac->module = module;
365         ildb_ac->context = context;
366         ildb_ac->callback = callback;
367
368         req->async.fn = ildb_callback;
369         req->async.private_data = (void *)h;
370
371         talloc_free(req->time_event);
372         req->time_event = NULL;
373         if (timeout) {
374                 req->time_event = event_add_timed(req->conn->event.event_ctx, h, 
375                                                   timeval_current_ofs(timeout, 0),
376                                                   ildb_request_timeout, h);
377         }
378
379         *handle = h;
380
381         return LDB_SUCCESS;
382
383 }
384
385 /*
386   search for matching records using an asynchronous function
387  */
388 static int ildb_search(struct ldb_module *module, struct ldb_request *req)
389 {
390         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
391         struct ldap_message *msg;
392         int n;
393
394         req->async.handle = NULL;
395
396         if (!req->async.callback || !req->async.context) {
397                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Async interface called with NULL callback function or NULL context"));
398                 return LDB_ERR_OPERATIONS_ERROR;
399         }
400         
401         if (req->op.search.tree == NULL) {
402                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Invalid expression parse tree"));
403                 return LDB_ERR_OPERATIONS_ERROR;
404         }
405
406         msg = new_ldap_message(ildb);
407         if (msg == NULL) {
408                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Out of Memory"));
409                 return LDB_ERR_OPERATIONS_ERROR;
410         }
411
412         msg->type = LDAP_TAG_SearchRequest;
413
414         if (req->op.search.base == NULL) {
415                 if (ildb->rootDSE != NULL) {
416                         msg->r.SearchRequest.basedn =
417                                 talloc_strdup(msg, ldb_msg_find_string(ildb->rootDSE, "defaultNamingContext", ""));
418                 } else {
419                         msg->r.SearchRequest.basedn = talloc_strdup(msg, "");
420                 }
421         } else {
422                 msg->r.SearchRequest.basedn  = ldb_dn_linearize(msg, req->op.search.base);
423         }
424         if (msg->r.SearchRequest.basedn == NULL) {
425                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Unable to determine baseDN"));
426                 talloc_free(msg);
427                 return LDB_ERR_OPERATIONS_ERROR;
428         }
429
430         if (req->op.search.scope == LDB_SCOPE_DEFAULT) {
431                 msg->r.SearchRequest.scope = LDB_SCOPE_SUBTREE;
432         } else {
433                 msg->r.SearchRequest.scope = req->op.search.scope;
434         }
435         
436         msg->r.SearchRequest.deref  = LDAP_DEREFERENCE_NEVER;
437         msg->r.SearchRequest.timelimit = 0;
438         msg->r.SearchRequest.sizelimit = 0;
439         msg->r.SearchRequest.attributesonly = 0;
440         msg->r.SearchRequest.tree = discard_const(req->op.search.tree);
441         
442         for (n = 0; req->op.search.attrs && req->op.search.attrs[n]; n++) /* noop */ ;
443         msg->r.SearchRequest.num_attributes = n;
444         msg->r.SearchRequest.attributes = discard_const(req->op.search.attrs);
445         msg->controls = req->controls;
446
447         return ildb_request_send(module, msg, req->async.context, req->async.callback, req->async.timeout, &(req->async.handle));
448 }
449
450 /*
451   add a record
452 */
453 static int ildb_add(struct ldb_module *module, struct ldb_request *req)
454 {
455         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
456         struct ldap_message *msg;
457         struct ldap_mod **mods;
458         int i,n;
459
460         req->async.handle = NULL;
461
462         /* ignore ltdb specials */
463         if (ldb_dn_is_special(req->op.add.message->dn)) {
464                 return LDB_SUCCESS;
465         }
466
467         msg = new_ldap_message(ildb->ldap);
468         if (msg == NULL) {
469                 return LDB_ERR_OPERATIONS_ERROR;
470         }
471
472         msg->type = LDAP_TAG_AddRequest;
473
474         msg->r.AddRequest.dn = ldb_dn_linearize(msg, req->op.add.message->dn);
475         if (msg->r.AddRequest.dn == NULL) {
476                 talloc_free(msg);
477                 return LDB_ERR_INVALID_DN_SYNTAX;
478         }
479
480         mods = ildb_msg_to_mods(msg, &n, req->op.add.message, 0);
481         if (mods == NULL) {
482                 talloc_free(msg);
483                 return LDB_ERR_OPERATIONS_ERROR;
484         }
485
486         msg->r.AddRequest.num_attributes = n;
487         msg->r.AddRequest.attributes = talloc_array(msg, struct ldb_message_element, n);
488         if (msg->r.AddRequest.attributes == NULL) {
489                 talloc_free(msg);
490                 return LDB_ERR_OPERATIONS_ERROR;
491         }
492
493         for (i = 0; i < n; i++) {
494                 msg->r.AddRequest.attributes[i] = mods[i]->attrib;
495         }
496
497         return ildb_request_send(module, msg, req->async.context, req->async.callback, req->async.timeout, &(req->async.handle));
498 }
499
500 /*
501   modify a record
502 */
503 static int ildb_modify(struct ldb_module *module, struct ldb_request *req)
504 {
505         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
506         struct ldap_message *msg;
507         struct ldap_mod **mods;
508         int i,n;
509
510         req->async.handle = NULL;
511
512         /* ignore ltdb specials */
513         if (ldb_dn_is_special(req->op.mod.message->dn)) {
514                 return LDB_SUCCESS;
515         }
516
517         msg = new_ldap_message(ildb->ldap);
518         if (msg == NULL) {
519                 return LDB_ERR_OPERATIONS_ERROR;
520         }
521
522         msg->type = LDAP_TAG_ModifyRequest;
523
524         msg->r.ModifyRequest.dn = ldb_dn_linearize(msg, req->op.mod.message->dn);
525         if (msg->r.ModifyRequest.dn == NULL) {
526                 talloc_free(msg);
527                 return LDB_ERR_INVALID_DN_SYNTAX;
528         }
529
530         mods = ildb_msg_to_mods(msg, &n, req->op.mod.message, 1);
531         if (mods == NULL) {
532                 talloc_free(msg);
533                 return LDB_ERR_OPERATIONS_ERROR;
534         }
535
536         msg->r.ModifyRequest.num_mods = n;
537         msg->r.ModifyRequest.mods = talloc_array(msg, struct ldap_mod, n);
538         if (msg->r.ModifyRequest.mods == NULL) {
539                 talloc_free(msg);
540                 return LDB_ERR_OPERATIONS_ERROR;
541         }
542
543         for (i = 0; i < n; i++) {
544                 msg->r.ModifyRequest.mods[i] = *mods[i];
545         }
546
547         return ildb_request_send(module, msg,
548                                 req->async.context,
549                                 req->async.callback,
550                                 req->async.timeout,
551                                 &(req->async.handle));
552 }
553
554 /*
555   delete a record
556 */
557 static int ildb_delete(struct ldb_module *module, struct ldb_request *req)
558 {
559         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
560         struct ldap_message *msg;
561
562         req->async.handle = NULL;
563
564         /* ignore ltdb specials */
565         if (ldb_dn_is_special(req->op.del.dn)) {
566                 return LDB_SUCCESS;
567         }
568
569         msg = new_ldap_message(ildb->ldap);
570         if (msg == NULL) {
571                 return LDB_ERR_OPERATIONS_ERROR;
572         }
573
574         msg->type = LDAP_TAG_DelRequest;
575         
576         msg->r.DelRequest.dn = ldb_dn_linearize(msg, req->op.del.dn);
577         if (msg->r.DelRequest.dn == NULL) {
578                 talloc_free(msg);
579                 return LDB_ERR_INVALID_DN_SYNTAX;
580         }
581
582         return ildb_request_send(module, msg,
583                                 req->async.context,
584                                 req->async.callback,
585                                 req->async.timeout,
586                                 &(req->async.handle));
587 }
588
589 /*
590   rename a record
591 */
592 static int ildb_rename(struct ldb_module *module, struct ldb_request *req)
593 {
594         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
595         struct ldap_message *msg;
596
597         req->async.handle = NULL;
598
599         /* ignore ltdb specials */
600         if (ldb_dn_is_special(req->op.rename.olddn) || ldb_dn_is_special(req->op.rename.newdn)) {
601                 return LDB_SUCCESS;
602         }
603
604         msg = new_ldap_message(ildb->ldap);
605         if (msg == NULL) {
606                 return LDB_ERR_OPERATIONS_ERROR;
607         }
608
609         msg->type = LDAP_TAG_ModifyDNRequest;
610         msg->r.ModifyDNRequest.dn = ldb_dn_linearize(msg, req->op.rename.olddn);
611         if (msg->r.ModifyDNRequest.dn == NULL) {
612                 talloc_free(msg);
613                 return LDB_ERR_INVALID_DN_SYNTAX;
614         }
615
616         msg->r.ModifyDNRequest.newrdn = 
617                 talloc_asprintf(msg, "%s=%s",
618                                 req->op.rename.newdn->components[0].name,
619                                 ldb_dn_escape_value(msg, req->op.rename.newdn->components[0].value));
620         if (msg->r.ModifyDNRequest.newrdn == NULL) {
621                 talloc_free(msg);
622                 return LDB_ERR_OPERATIONS_ERROR;
623         }
624
625         msg->r.ModifyDNRequest.newsuperior =
626                 ldb_dn_linearize(msg,
627                                  ldb_dn_get_parent(msg, req->op.rename.newdn));
628         if (msg->r.ModifyDNRequest.newsuperior == NULL) {
629                 talloc_free(msg);
630                 return LDB_ERR_INVALID_DN_SYNTAX;
631         }
632
633         msg->r.ModifyDNRequest.deleteolddn = True;
634
635         return ildb_request_send(module, msg,
636                                 req->async.context,
637                                 req->async.callback,
638                                 req->async.timeout,
639                                 &(req->async.handle));
640 }
641
642 static int ildb_start_trans(struct ldb_module *module)
643 {
644         /* TODO implement a local locking mechanism here */
645
646         return LDB_SUCCESS;
647 }
648
649 static int ildb_end_trans(struct ldb_module *module)
650 {
651         /* TODO implement a local transaction mechanism here */
652
653         return LDB_SUCCESS;
654 }
655
656 static int ildb_del_trans(struct ldb_module *module)
657 {
658         /* TODO implement a local locking mechanism here */
659
660         return LDB_SUCCESS;
661 }
662
663 static int ildb_request(struct ldb_module *module, struct ldb_request *req)
664 {
665         return LDB_ERR_OPERATIONS_ERROR;
666 }
667
668 static int ildb_async_wait(struct ldb_async_handle *handle, enum ldb_async_wait_type type)
669 {
670         struct ildb_async_context *ac = talloc_get_type(handle->private_data, struct ildb_async_context);
671
672         if (handle->state == LDB_ASYNC_DONE) {
673                 return handle->status;
674         }
675
676         if (!ac) {
677                 return LDB_ERR_OPERATIONS_ERROR;
678         }
679
680         handle->state = LDB_ASYNC_INIT;
681
682         switch(type) {
683         case LDB_WAIT_NONE:
684                 if (event_loop_once(ac->req->conn->event.event_ctx) != 0) {
685                         return LDB_ERR_OTHER;
686                 }
687                 break;
688         case LDB_WAIT_ALL:
689                 while (handle->status == LDB_SUCCESS && handle->state != LDB_ASYNC_DONE) {
690                         if (event_loop_once(ac->req->conn->event.event_ctx) != 0) {
691                                 return LDB_ERR_OTHER;
692                         }
693                 }
694                 break;
695         default:
696                 return LDB_ERR_OPERATIONS_ERROR;
697         }
698         
699         return handle->status;
700 }
701
702 static int ildb_rootdse_callback(struct ldb_context *ldb, void *context, struct ldb_async_result *ares)
703 {
704         struct ildb_private *ildb;
705
706         if (!context || !ares) {
707                 ldb_set_errstring(ldb, talloc_asprintf(ldb, "NULL Context or Result in callback"));
708                 goto error;
709         }
710
711         ildb = talloc_get_type(context, struct ildb_private);
712
713         /* we are interested only in the single reply (rootdse) we receive here */
714         switch (ares->type) {
715         case LDB_REPLY_ENTRY:
716                 if (ildb->rootDSE != NULL) {
717                         /* what ? more than one rootdse entry ?! */
718                         goto error;
719                 }
720                 ildb->rootDSE = talloc_steal(ildb, ares->message);
721                 break;
722
723         case LDB_REPLY_REFERRAL:
724                 goto error;
725
726         case LDB_REPLY_DONE:
727                 break;
728         }
729         
730         talloc_free(ares);
731         return LDB_SUCCESS;
732
733 error:
734         talloc_free(ares);
735         return LDB_ERR_OPERATIONS_ERROR;
736 }
737
738 /*
739   fetch the rootDSE for later use
740 */
741 static int ildb_init(struct ldb_module *module)
742 {
743         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
744         struct ldb_request *req;
745         int ret;
746
747         req = talloc(ildb, struct ldb_request);
748         if (req == NULL) {
749                 return LDB_ERR_OPERATIONS_ERROR;
750         }
751
752         ildb->rootDSE = NULL;
753
754         req->operation = LDB_SEARCH;
755         req->op.search.base = ldb_dn_new(req);
756         req->op.search.scope = LDB_SCOPE_BASE;
757         req->op.search.tree = ldb_parse_tree(req, "dn=dc=rootDSE");
758         req->op.search.attrs = NULL;
759         req->controls = NULL;
760         req->async.context = ildb;
761         req->async.callback = ildb_rootdse_callback;
762         req->async.timeout = 60;
763
764         ret = ildb_search(module, req);
765         if (ret != LDB_SUCCESS) {
766                 talloc_free(req);
767                 return ret;
768         }
769
770         ret = ildb_async_wait(req->async.handle, LDB_WAIT_ALL);
771         
772         talloc_free(req);
773         return ret;
774 }
775
776 static const struct ldb_module_ops ildb_ops = {
777         .name              = "ldap",
778         .search            = ildb_search,
779         .add               = ildb_add,
780         .modify            = ildb_modify,
781         .del               = ildb_delete,
782         .rename            = ildb_rename,
783         .request           = ildb_request,
784         .start_transaction = ildb_start_trans,
785         .end_transaction   = ildb_end_trans,
786         .del_transaction   = ildb_del_trans,
787         .async_wait        = ildb_async_wait,
788         .init_context      = ildb_init
789 };
790
791 /*
792   connect to the database
793 */
794 static int ildb_connect(struct ldb_context *ldb, const char *url, 
795                  unsigned int flags, const char *options[])
796 {
797         struct ildb_private *ildb = NULL;
798         NTSTATUS status;
799         struct cli_credentials *creds;
800
801         ildb = talloc(ldb, struct ildb_private);
802         if (!ildb) {
803                 ldb_oom(ldb);
804                 goto failed;
805         }
806
807         ildb->rootDSE = NULL;
808         ildb->ldb     = ldb;
809
810         ildb->ldap = ldap_new_connection(ildb, ldb_get_opaque(ldb, "EventContext"));
811         if (!ildb->ldap) {
812                 ldb_oom(ldb);
813                 goto failed;
814         }
815
816         if (flags == LDB_FLG_RECONNECT) {
817                 ldap_set_reconn_params(ildb->ldap, 10);
818         }
819
820         status = ldap_connect(ildb->ldap, url);
821         if (!NT_STATUS_IS_OK(status)) {
822                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to connect to ldap URL '%s' - %s\n",
823                           url, ldap_errstr(ildb->ldap, status));
824                 goto failed;
825         }
826
827         ldb->modules = talloc(ldb, struct ldb_module);
828         if (!ldb->modules) {
829                 ldb_oom(ldb);
830                 goto failed;
831         }
832         ldb->modules->ldb = ldb;
833         ldb->modules->prev = ldb->modules->next = NULL;
834         ldb->modules->private_data = ildb;
835         ldb->modules->ops = &ildb_ops;
836
837         /* caller can optionally setup credentials using the opaque token 'credentials' */
838         creds = talloc_get_type(ldb_get_opaque(ldb, "credentials"), struct cli_credentials);
839         if (creds == NULL) {
840                 struct auth_session_info *session_info = talloc_get_type(ldb_get_opaque(ldb, "sessionInfo"), struct auth_session_info);
841                 if (session_info) {
842                         creds = session_info->credentials;
843                 }
844         }
845
846         if (creds != NULL && cli_credentials_authentication_requested(creds)) {
847                 const char *bind_dn = cli_credentials_get_bind_dn(creds);
848                 if (bind_dn) {
849                         const char *password = cli_credentials_get_password(creds);
850                         status = ldap_bind_simple(ildb->ldap, bind_dn, password);
851                         if (!NT_STATUS_IS_OK(status)) {
852                                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to bind - %s\n",
853                                           ldap_errstr(ildb->ldap, status));
854                                 goto failed;
855                         }
856                 } else {
857                         status = ldap_bind_sasl(ildb->ldap, creds);
858                         if (!NT_STATUS_IS_OK(status)) {
859                                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to bind - %s\n",
860                                           ldap_errstr(ildb->ldap, status));
861                                 goto failed;
862                         }
863                 }
864         }
865
866         return 0;
867
868 failed:
869         if (ldb->modules) {
870                 ldb->modules->private_data = NULL;
871         }
872         talloc_free(ildb);
873         return -1;
874 }
875
876 int ldb_ildap_init(void)
877 {
878         return ldb_register_backend("ldap", ildb_connect) + 
879                    ldb_register_backend("ldapi", ildb_connect) + 
880                    ldb_register_backend("ldaps", ildb_connect);
881 }