r13823: make async_wait part of the modules ops
[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 "lib/cmdline/popt_common.h"
52 #include "auth/auth.h"
53
54 struct ildb_private {
55         struct ldap_connection *ldap;
56         struct ldb_message *rootDSE;
57         struct ldb_context *ldb;
58 };
59
60 struct ildb_async_context {
61         struct ldb_module *module;
62         struct ldap_request *req;
63         void *context;
64         int (*callback)(struct ldb_context *, void *, struct ldb_async_result *);
65 };
66
67 /*
68   convert a ldb_message structure to a list of ldap_mod structures
69   ready for ildap_add() or ildap_modify()
70 */
71 static struct ldap_mod **ildb_msg_to_mods(void *mem_ctx, int *num_mods,
72                                           const struct ldb_message *msg, int use_flags)
73 {
74         struct ldap_mod **mods;
75         unsigned int i;
76         int n = 0;
77
78         /* allocate maximum number of elements needed */
79         mods = talloc_array(mem_ctx, struct ldap_mod *, msg->num_elements+1);
80         if (!mods) {
81                 errno = ENOMEM;
82                 return NULL;
83         }
84         mods[0] = NULL;
85
86         for (i = 0; i < msg->num_elements; i++) {
87                 const struct ldb_message_element *el = &msg->elements[i];
88
89                 mods[n] = talloc(mods, struct ldap_mod);
90                 if (!mods[n]) {
91                         goto failed;
92                 }
93                 mods[n + 1] = NULL;
94                 mods[n]->type = 0;
95                 mods[n]->attrib = *el;
96                 if (use_flags) {
97                         switch (el->flags & LDB_FLAG_MOD_MASK) {
98                         case LDB_FLAG_MOD_ADD:
99                                 mods[n]->type = LDAP_MODIFY_ADD;
100                                 break;
101                         case LDB_FLAG_MOD_DELETE:
102                                 mods[n]->type = LDAP_MODIFY_DELETE;
103                                 break;
104                         case LDB_FLAG_MOD_REPLACE:
105                                 mods[n]->type = LDAP_MODIFY_REPLACE;
106                                 break;
107                         }
108                 }
109                 n++;
110         }
111
112         *num_mods = n;
113         return mods;
114
115 failed:
116         talloc_free(mods);
117         return NULL;
118 }
119
120
121 /*
122   map an ildap NTSTATUS to a ldb error code
123 */
124 static int ildb_map_error(struct ildb_private *ildb, NTSTATUS status)
125 {
126         if (NT_STATUS_IS_OK(status)) {
127                 return LDB_SUCCESS;
128         }
129         talloc_free(ildb->ldb->err_string);
130         ildb->ldb->err_string = talloc_strdup(ildb, ldap_errstr(ildb->ldap, status));
131         if (NT_STATUS_IS_LDAP(status)) {
132                 return NT_STATUS_LDAP_CODE(status);
133         }
134         return LDB_ERR_OPERATIONS_ERROR;
135 }
136
137 static void ildb_request_timeout(struct event_context *ev, struct timed_event *te,
138                                  struct timeval t, void *private_data)
139 {
140         struct ldb_async_handle *handle = talloc_get_type(private_data, struct ldb_async_handle);
141         struct ildb_async_context *ac = talloc_get_type(handle->private_data, struct ildb_async_context);
142
143         if (ac->req->state == LDAP_REQUEST_PENDING) {
144                 DLIST_REMOVE(ac->req->conn->pending, ac->req);
145         }
146
147         handle->status = LDB_ERR_OPERATIONS_ERROR;
148
149         return;
150 }
151
152 static void ildb_async_callback(struct ldap_request *req)
153 {
154         struct ldb_async_handle *handle = talloc_get_type(req->async.private_data, struct ldb_async_handle);
155         struct ildb_async_context *ac = talloc_get_type(handle->private_data, struct ildb_async_context);
156         struct ildb_private *ildb = talloc_get_type(ac->module->private_data, struct ildb_private);
157         NTSTATUS status;
158         int i;
159
160         handle->status = LDB_SUCCESS;
161
162         if (!NT_STATUS_IS_OK(req->status)) {
163                 handle->status = ildb_map_error(ildb, req->status);
164                 return;
165         }
166
167         if (req->num_replies < 1) {
168                 handle->status = LDB_ERR_OPERATIONS_ERROR;
169                 return;
170         } 
171                 
172         switch (req->type) {
173
174         case LDAP_TAG_ModifyRequest:
175                 if (req->replies[0]->type != LDAP_TAG_ModifyResponse) {
176                         handle->status = LDB_ERR_PROTOCOL_ERROR;
177                         return;
178                 }
179                 status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
180                 handle->status = ildb_map_error(ildb, status);
181                 if (ac->callback && handle->status == LDB_SUCCESS) {
182                         /* FIXME: build a corresponding ares to pass on */
183                         handle->status = ac->callback(ac->module->ldb, ac->context, NULL);
184                 }
185                 handle->state = LDB_ASYNC_DONE;
186                 break;
187
188         case LDAP_TAG_AddRequest:
189                 if (req->replies[0]->type != LDAP_TAG_AddResponse) {
190                         handle->status = LDB_ERR_PROTOCOL_ERROR;
191                         return;
192                 }
193                 status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
194                 handle->status = ildb_map_error(ildb, status);
195                 if (ac->callback && handle->status == LDB_SUCCESS) {
196                         /* FIXME: build a corresponding ares to pass on */
197                         handle->status = ac->callback(ac->module->ldb, ac->context, NULL);
198                 }
199                 handle->state = LDB_ASYNC_DONE;
200                 break;
201
202         case LDAP_TAG_DelRequest:
203                 if (req->replies[0]->type != LDAP_TAG_DelResponse) {
204                         handle->status = LDB_ERR_PROTOCOL_ERROR;
205                         return;
206                 }
207                 status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
208                 handle->status = ildb_map_error(ildb, status);
209                 if (ac->callback && handle->status == LDB_SUCCESS) {
210                         /* FIXME: build a corresponding ares to pass on */
211                         handle->status = ac->callback(ac->module->ldb, ac->context, NULL);
212                 }
213                 handle->state = LDB_ASYNC_DONE;
214                 break;
215
216         case LDAP_TAG_ModifyDNRequest:
217                 if (req->replies[0]->type != LDAP_TAG_ModifyDNResponse) {
218                         handle->status = LDB_ERR_PROTOCOL_ERROR;
219                         return;
220                 }
221                 status = ldap_check_response(req->conn, &req->replies[0]->r.GeneralResult);
222                 handle->status = ildb_map_error(ildb, status);
223                 if (ac->callback && handle->status == LDB_SUCCESS) {
224                         /* FIXME: build a corresponding ares to pass on */
225                         handle->status = ac->callback(ac->module->ldb, ac->context, NULL);
226                 }
227                 handle->state = LDB_ASYNC_DONE;
228                 break;
229
230         case LDAP_TAG_SearchRequest:
231                 /* loop over all messages */
232                 for (i = 0; i < req->num_replies; i++) {
233                         struct ldap_SearchResEntry *search;
234                         struct ldb_async_result *ares = NULL;
235                         struct ldap_message *msg;
236                         int ret;
237
238                         ares = talloc_zero(ac, struct ldb_async_result);
239                         if (!ares) {
240                                 handle->status = LDB_ERR_OPERATIONS_ERROR;
241                                 return;
242                         }
243
244                         msg = req->replies[i];
245                         switch (msg->type) {
246
247                         case LDAP_TAG_SearchResultDone:
248
249                                 status = ldap_check_response(req->conn, &msg->r.GeneralResult);
250                                 if (!NT_STATUS_IS_OK(status)) {
251                                         ldb_debug(ac->module->ldb, LDB_DEBUG_ERROR, "Error: %s\n" ,ldap_errstr(req->conn, status));
252                                         handle->status = ildb_map_error(ildb, status);
253                                         return;
254                                 }
255                                 
256                                 if (msg->controls) {
257                                         ares->controls = talloc_steal(ares, msg->controls);
258                                 }
259                                 if (msg->r.SearchResultDone.resultcode) {
260                                         if (msg->r.SearchResultDone.errormessage) {
261                                                 ldb_set_errstring(ac->module->ldb, talloc_strdup(ac->module, msg->r.SearchResultDone.errormessage));
262                                         }
263                                 }
264
265                                 handle->status = msg->r.SearchResultDone.resultcode;
266                                 handle->state = LDB_ASYNC_DONE;
267                                 ares->type = LDB_REPLY_DONE;
268                                 break;
269
270                         case LDAP_TAG_SearchResultEntry:
271
272
273                                 ares->message = ldb_msg_new(ares);
274                                 if (!ares->message) {
275                                         handle->status = LDB_ERR_OPERATIONS_ERROR;;
276                                         return;
277                                 }
278
279                                 search = &(msg->r.SearchResultEntry);
280                 
281                                 ares->message->dn = ldb_dn_explode_or_special(ares->message, search->dn);
282                                 if (ares->message->dn == NULL) {
283                                         handle->status = LDB_ERR_OPERATIONS_ERROR;
284                                         return;
285                                 }
286                                 ares->message->num_elements = search->num_attributes;
287                                 ares->message->elements = talloc_steal(ares->message, search->attributes);
288
289                                 handle->status = LDB_SUCCESS;
290                                 handle->state = LDB_ASYNC_PENDING;
291                                 ares->type = LDB_REPLY_ENTRY;
292                                 break;
293
294                         case LDAP_TAG_SearchResultReference:
295
296                                 ares->referral = talloc_strdup(ares, msg->r.SearchResultReference.referral);
297                                 
298                                 handle->status = LDB_SUCCESS;
299                                 handle->state = LDB_ASYNC_PENDING;
300                                 ares->type = LDB_REPLY_REFERRAL;
301                                 break;
302
303                         default:
304                                 /* TAG not handled, fail ! */
305                                 handle->status = LDB_ERR_PROTOCOL_ERROR;
306                                 return;
307                         }
308
309                         ret = ac->callback(ac->module->ldb, ac->context, ares);
310                         if (ret) {
311                                 handle->status = ret;
312                         }
313                 }
314
315                 talloc_free(req->replies);
316                 req->replies = NULL;
317                 req->num_replies = 0;
318
319                 break;
320                 
321         default:
322                 handle->status = LDB_ERR_PROTOCOL_ERROR;
323                 return;
324         }
325 }
326
327 static int ildb_request_send(struct ldb_module *module, struct ldap_message *msg,
328                              void *context,
329                              int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
330                              int timeout,
331                              struct ldb_async_handle **handle)
332 {
333         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
334         struct ildb_async_context *ildb_ac;
335         struct ldb_async_handle *h;
336         struct ldap_request *req;
337
338         h = talloc_zero(ildb->ldap, struct ldb_async_handle);
339         if (h == NULL) {
340                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Out of Memory"));
341                 return LDB_ERR_OPERATIONS_ERROR;
342         }
343
344         ildb_ac = talloc(h, struct ildb_async_context);
345         if (ildb_ac == NULL) {
346                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Out of Memory"));
347                 talloc_free(h);
348                 return LDB_ERR_OPERATIONS_ERROR;
349         }
350
351         h->private_data = (void *)ildb_ac;
352
353         req = ldap_request_send(ildb->ldap, msg);
354         if (req == NULL) {
355                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "async send request failed"));
356                 return LDB_ERR_OPERATIONS_ERROR;
357         }
358
359         ildb_ac->req = talloc_steal(ildb_ac, req);
360         ildb_ac->module = module;
361         ildb_ac->context = context;
362         ildb_ac->callback = callback;
363
364         req->async.fn = ildb_async_callback;
365         req->async.private_data = (void *)h;
366
367         talloc_free(req->time_event);
368         req->time_event = NULL;
369         if (timeout) {
370                 req->time_event = event_add_timed(req->conn->event.event_ctx, h, 
371                                                   timeval_current_ofs(timeout, 0),
372                                                   ildb_request_timeout, ildb_ac);
373         }
374
375         *handle = h;
376
377         return LDB_SUCCESS;
378
379 }
380
381 /*
382   search for matching records using an asynchronous function
383  */
384 static int ildb_search_async(struct ldb_module *module, const struct ldb_dn *base,
385                               enum ldb_scope scope, struct ldb_parse_tree *tree,
386                               const char * const *attrs,
387                               struct ldb_control **control_req,
388                               void *context,
389                               int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
390                               int timeout,
391                               struct ldb_async_handle **handle)
392 {
393         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
394         struct ldap_message *msg;
395         int n;
396
397         *handle = NULL;
398
399         if (!callback || !context) {
400                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Async interface called with NULL callback function or NULL context"));
401                 return LDB_ERR_OPERATIONS_ERROR;
402         }
403         
404         if (tree == NULL) {
405                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Invalid expression parse tree"));
406                 return LDB_ERR_OPERATIONS_ERROR;
407         }
408
409         msg = new_ldap_message(ildb);
410         if (msg == NULL) {
411                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Out of Memory"));
412                 return LDB_ERR_OPERATIONS_ERROR;
413         }
414
415         msg->type = LDAP_TAG_SearchRequest;
416
417         if (base == NULL) {
418                 if (ildb->rootDSE != NULL) {
419                         msg->r.SearchRequest.basedn =
420                                 talloc_strdup(msg, ldb_msg_find_string(ildb->rootDSE, "defaultNamingContext", ""));
421                 } else {
422                         msg->r.SearchRequest.basedn = talloc_strdup(msg, "");
423                 }
424         } else {
425                 msg->r.SearchRequest.basedn  = ldb_dn_linearize(msg, base);
426         }
427         if (msg->r.SearchRequest.basedn == NULL) {
428                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Unable to determine baseDN"));
429                 talloc_free(msg);
430                 return LDB_ERR_OPERATIONS_ERROR;
431         }
432
433         if (scope == LDB_SCOPE_DEFAULT) {
434                 msg->r.SearchRequest.scope = LDB_SCOPE_SUBTREE;
435         } else {
436                 msg->r.SearchRequest.scope = scope;
437         }
438         
439         msg->r.SearchRequest.deref  = LDAP_DEREFERENCE_NEVER;
440         msg->r.SearchRequest.timelimit = 0;
441         msg->r.SearchRequest.sizelimit = 0;
442         msg->r.SearchRequest.attributesonly = 0;
443         msg->r.SearchRequest.tree = tree;
444         
445         for (n = 0; attrs && attrs[n]; n++) /* noop */ ;
446         msg->r.SearchRequest.num_attributes = n;
447         msg->r.SearchRequest.attributes = discard_const(attrs);
448         msg->controls = control_req;
449
450         return ildb_request_send(module, msg, context, callback, timeout, handle);
451 }
452
453 static int ildb_search_sync_callback(struct ldb_context *ldb, void *context, struct ldb_async_result *ares)
454 {
455         struct ldb_result *res;
456         int n;
457         
458         if (!context) {
459                 ldb_set_errstring(ldb, talloc_asprintf(ldb, "NULL Context in callback"));
460                 return LDB_ERR_OPERATIONS_ERROR;
461         }       
462
463         res = *((struct ldb_result **)context);
464
465         if (!res || !ares) {
466                 goto error;
467         }
468
469         if (ares->type == LDB_REPLY_ENTRY) {
470                 res->msgs = talloc_realloc(res, res->msgs, struct ldb_message *, res->count + 2);
471                 if (! res->msgs) {
472                         goto error;
473                 }
474
475                 res->msgs[res->count + 1] = NULL;
476
477                 res->msgs[res->count] = talloc_steal(res->msgs, ares->message);
478                 if (! res->msgs[res->count]) {
479                         goto error;
480                 }
481
482                 res->count++;
483         }
484
485         if (ares->type == LDB_REPLY_REFERRAL) {
486                 if (res->refs) {
487                         for (n = 0; res->refs[n]; n++) /*noop*/ ;
488                 } else {
489                         n = 0;
490                 }
491
492                 res->refs = talloc_realloc(res, res->refs, char *, n + 2);
493                 if (! res->refs) {
494                         goto error;
495                 }
496
497                 res->refs[n] = talloc_steal(res->refs, ares->referral);
498                 res->refs[n + 1] = NULL;
499         }
500
501         if (ares->controls) {
502                 res->controls = talloc_steal(res, ares->controls);
503                 if (! res->controls) {
504                         goto error;
505                 }
506         }
507
508         talloc_free(ares);
509         return LDB_SUCCESS;
510
511 error:
512         talloc_free(ares);
513         talloc_free(res);
514         *((struct ldb_result **)context) = NULL;
515         return LDB_ERR_OPERATIONS_ERROR;
516 }
517
518 /*
519   search for matching records using a synchronous function
520  */
521 static int ildb_search_bytree(struct ldb_module *module, const struct ldb_dn *base,
522                               enum ldb_scope scope, struct ldb_parse_tree *tree,
523                               const char * const *attrs,
524                               struct ldb_control **control_req,
525                               struct ldb_result **res)
526 {
527         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
528         struct ldb_async_handle *handle;
529         int ret;
530
531         *res = talloc_zero(ildb, struct ldb_result);
532         if (! *res) {
533                 return LDB_ERR_OPERATIONS_ERROR;
534         }
535
536         ret = ildb_search_async(module, base, scope, tree, attrs, control_req,
537                                 res, &ildb_search_sync_callback, ildb->ldap->timeout, &handle);
538
539         if (ret != LDB_SUCCESS)
540                 return ret;
541
542         ret = ldb_async_wait(module->ldb, handle, LDB_WAIT_ALL);
543
544         talloc_free(handle);
545         return ret;
546 }
547
548 /*
549   add a record
550 */
551 static int ildb_add_async(struct ldb_module *module, const struct ldb_message *ldb_msg,
552                           void *context,
553                           int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
554                           int timeout,
555                           struct ldb_async_handle **handle)
556 {
557         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
558         struct ldap_message *msg;
559         struct ldap_mod **mods;
560         int i,n;
561
562         *handle = NULL;
563
564         /* ignore ltdb specials */
565         if (ldb_dn_is_special(ldb_msg->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_AddRequest;
575
576         msg->r.AddRequest.dn = ldb_dn_linearize(msg, ldb_msg->dn);
577         if (msg->r.AddRequest.dn == NULL) {
578                 talloc_free(msg);
579                 return LDB_ERR_INVALID_DN_SYNTAX;
580         }
581
582         mods = ildb_msg_to_mods(msg, &n, ldb_msg, 0);
583         if (mods == NULL) {
584                 talloc_free(msg);
585                 return LDB_ERR_OPERATIONS_ERROR;
586         }
587
588         msg->r.AddRequest.num_attributes = n;
589         msg->r.AddRequest.attributes = talloc_array(msg, struct ldb_message_element, n);
590         if (msg->r.AddRequest.attributes == NULL) {
591                 talloc_free(msg);
592                 return LDB_ERR_OPERATIONS_ERROR;
593         }
594
595         for (i = 0; i < n; i++) {
596                 msg->r.AddRequest.attributes[i] = mods[i]->attrib;
597         }
598
599         return ildb_request_send(module, msg, context, callback, timeout, handle);
600 }
601
602 static int ildb_add(struct ldb_module *module, const struct ldb_message *msg)
603 {
604         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
605         struct ldb_async_handle *handle;
606         int ret;
607
608         ret = ildb_add_async(module, msg,
609                                 NULL, NULL, ildb->ldap->timeout, &handle);
610
611         if (ret != LDB_SUCCESS)
612                 return ret;
613
614         ret = ldb_async_wait(module->ldb, handle, LDB_WAIT_ALL);
615
616         talloc_free(handle);
617         return ret;
618 }
619
620 /*
621   modify a record
622 */
623 static int ildb_modify_async(struct ldb_module *module, const struct ldb_message *ldb_msg,
624                              void *context,
625                              int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
626                              int timeout,
627                              struct ldb_async_handle **handle)
628 {
629         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
630         struct ldap_message *msg;
631         struct ldap_mod **mods;
632         int i,n;
633
634         *handle = NULL;
635
636         /* ignore ltdb specials */
637         if (ldb_dn_is_special(ldb_msg->dn)) {
638                 return LDB_SUCCESS;
639         }
640
641         msg = new_ldap_message(ildb->ldap);
642         if (msg == NULL) {
643                 return LDB_ERR_OPERATIONS_ERROR;
644         }
645
646         msg->type = LDAP_TAG_ModifyRequest;
647
648         msg->r.ModifyRequest.dn = ldb_dn_linearize(msg, ldb_msg->dn);
649         if (msg->r.ModifyRequest.dn == NULL) {
650                 talloc_free(msg);
651                 return LDB_ERR_INVALID_DN_SYNTAX;
652         }
653
654         mods = ildb_msg_to_mods(msg, &n, ldb_msg, 1);
655         if (mods == NULL) {
656                 talloc_free(msg);
657                 return LDB_ERR_OPERATIONS_ERROR;
658         }
659
660         msg->r.ModifyRequest.num_mods = n;
661         msg->r.ModifyRequest.mods = talloc_array(msg, struct ldap_mod, n);
662         if (msg->r.ModifyRequest.mods == NULL) {
663                 talloc_free(msg);
664                 return LDB_ERR_OPERATIONS_ERROR;
665         }
666
667         for (i = 0; i < n; i++) {
668                 msg->r.ModifyRequest.mods[i] = *mods[i];
669         }
670
671         return ildb_request_send(module, msg, context, callback, timeout, handle);
672 }
673
674 static int ildb_modify(struct ldb_module *module, const struct ldb_message *msg)
675 {
676         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
677         struct ldb_async_handle *handle;
678         int ret;
679
680         ret = ildb_modify_async(module, msg,
681                                 NULL, NULL, ildb->ldap->timeout, &handle);
682
683         if (ret != LDB_SUCCESS)
684                 return ret;
685
686         ret = ldb_async_wait(module->ldb, handle, LDB_WAIT_ALL);
687
688         talloc_free(handle);
689         return ret;
690 }
691
692 /*
693   delete a record
694 */
695 static int ildb_delete_async(struct ldb_module *module, const struct ldb_dn *dn,
696                              void *context,
697                              int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
698                              int timeout,
699                              struct ldb_async_handle **handle)
700 {
701         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
702         struct ldap_message *msg;
703
704         *handle = NULL;
705
706         /* ignore ltdb specials */
707         if (ldb_dn_is_special(dn)) {
708                 return LDB_SUCCESS;
709         }
710
711         msg = new_ldap_message(ildb->ldap);
712         if (msg == NULL) {
713                 return LDB_ERR_OPERATIONS_ERROR;
714         }
715
716         msg->type = LDAP_TAG_DelRequest;
717         
718         msg->r.DelRequest.dn = ldb_dn_linearize(msg, dn);
719         if (msg->r.DelRequest.dn == NULL) {
720                 talloc_free(msg);
721                 return LDB_ERR_INVALID_DN_SYNTAX;
722         }
723
724         return ildb_request_send(module, msg, context, callback, timeout, handle);
725 }
726
727 static int ildb_delete(struct ldb_module *module, const struct ldb_dn *dn)
728 {
729         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
730         struct ldb_async_handle *handle;
731         int ret;
732
733         ret = ildb_delete_async(module, dn,
734                                 NULL, NULL, ildb->ldap->timeout, &handle);
735
736         if (ret != LDB_SUCCESS)
737                 return ret;
738
739         ret = ldb_async_wait(module->ldb, handle, LDB_WAIT_ALL);
740
741         talloc_free(handle);
742         return ret;
743 }
744
745 /*
746   rename a record
747 */
748 static int ildb_rename_async(struct ldb_module *module,
749                              const struct ldb_dn *olddn, const struct ldb_dn *newdn,
750                              void *context,
751                              int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
752                              int timeout,
753                              struct ldb_async_handle **handle)
754 {
755         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
756         struct ldap_message *msg;
757
758         *handle = NULL;
759
760         /* ignore ltdb specials */
761         if (ldb_dn_is_special(olddn) || ldb_dn_is_special(newdn)) {
762                 return LDB_SUCCESS;
763         }
764
765         msg = new_ldap_message(ildb->ldap);
766         if (msg == NULL) {
767                 return LDB_ERR_OPERATIONS_ERROR;
768         }
769
770         msg->type = LDAP_TAG_ModifyDNRequest;
771         msg->r.ModifyDNRequest.dn = ldb_dn_linearize(msg, olddn);
772         if (msg->r.ModifyDNRequest.dn == NULL) {
773                 talloc_free(msg);
774                 return LDB_ERR_INVALID_DN_SYNTAX;
775         }
776
777         msg->r.ModifyDNRequest.newrdn = 
778                 talloc_asprintf(msg, "%s=%s",
779                                 newdn->components[0].name,
780                                 ldb_dn_escape_value(msg, newdn->components[0].value));
781         if (msg->r.ModifyDNRequest.newrdn == NULL) {
782                 talloc_free(msg);
783                 return LDB_ERR_OPERATIONS_ERROR;
784         }
785
786         msg->r.ModifyDNRequest.newsuperior =
787                 ldb_dn_linearize(msg,
788                                  ldb_dn_get_parent(msg, newdn));
789         if (msg->r.ModifyDNRequest.newsuperior == NULL) {
790                 talloc_free(msg);
791                 return LDB_ERR_INVALID_DN_SYNTAX;
792         }
793
794         msg->r.ModifyDNRequest.deleteolddn = True;
795
796         return ildb_request_send(module, msg, context, callback, timeout, handle);
797 }
798
799 static int ildb_rename(struct ldb_module *module, const struct ldb_dn *olddn, const struct ldb_dn *newdn)
800 {
801         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
802         struct ldb_async_handle *handle;
803         int ret;
804
805         ret = ildb_rename_async(module, olddn, newdn,
806                                 NULL, NULL, ildb->ldap->timeout, &handle);
807
808         if (ret != LDB_SUCCESS)
809                 return ret;
810
811         ret = ldb_async_wait(module->ldb, handle, LDB_WAIT_ALL);
812
813         talloc_free(handle);
814         return ret;
815 }
816
817 static int ildb_start_trans(struct ldb_module *module)
818 {
819         /* TODO implement a local locking mechanism here */
820
821         return 0;
822 }
823
824 static int ildb_end_trans(struct ldb_module *module)
825 {
826         /* TODO implement a local transaction mechanism here */
827
828         return 0;
829 }
830
831 static int ildb_del_trans(struct ldb_module *module)
832 {
833         /* TODO implement a local locking mechanism here */
834
835         return 0;
836 }
837
838 static int ildb_request(struct ldb_module *module, struct ldb_request *req)
839 {
840         switch (req->operation) {
841
842         case LDB_REQ_SEARCH:
843                 return ildb_search_bytree(module,
844                                           req->op.search.base,
845                                           req->op.search.scope, 
846                                           req->op.search.tree, 
847                                           req->op.search.attrs, 
848                                           req->controls,
849                                           &req->op.search.res);
850
851         case LDB_REQ_ADD:
852                 return ildb_add(module, req->op.add.message);
853
854         case LDB_REQ_MODIFY:
855                 return ildb_modify(module, req->op.mod.message);
856
857         case LDB_REQ_DELETE:
858                 return ildb_delete(module, req->op.del.dn);
859
860         case LDB_REQ_RENAME:
861                 return ildb_rename(module,
862                                         req->op.rename.olddn,
863                                         req->op.rename.newdn);
864
865         case LDB_ASYNC_SEARCH:
866                 return ildb_search_async(module,
867                                         req->op.search.base,
868                                         req->op.search.scope, 
869                                         req->op.search.tree, 
870                                         req->op.search.attrs,
871                                         req->controls,
872                                         req->async.context,
873                                         req->async.callback,
874                                         req->async.timeout,
875                                         &req->async.handle);
876
877         case LDB_ASYNC_ADD:
878                 return ildb_add_async(module,
879                                         req->op.add.message,
880                                         req->async.context,
881                                         req->async.callback,
882                                         req->async.timeout,
883                                         &req->async.handle);
884
885         case LDB_ASYNC_MODIFY:
886                 return ildb_modify_async(module,
887                                         req->op.mod.message,
888                                         req->async.context,
889                                         req->async.callback,
890                                         req->async.timeout,
891                                         &req->async.handle);
892
893         case LDB_ASYNC_DELETE:
894                 return ildb_delete_async(module,
895                                         req->op.del.dn,
896                                         req->async.context,
897                                         req->async.callback,
898                                         req->async.timeout,
899                                         &req->async.handle);
900
901         case LDB_ASYNC_RENAME:
902                 return ildb_rename_async(module,
903                                         req->op.rename.olddn,
904                                         req->op.rename.newdn,
905                                         req->async.context,
906                                         req->async.callback,
907                                         req->async.timeout,
908                                         &req->async.handle);
909
910         default:
911                 return -1;
912
913         }
914 }
915
916 static int ildb_async_wait(struct ldb_module *module, struct ldb_async_handle *handle, enum ldb_async_wait_type type)
917 {
918         struct ildb_async_context *ac = talloc_get_type(handle->private_data, struct ildb_async_context);
919
920         if (!ac) {
921                 return LDB_ERR_OPERATIONS_ERROR;
922         }
923
924         handle->state = LDB_ASYNC_INIT;
925
926         switch(type) {
927         case LDB_WAIT_NONE:
928                 if (event_loop_once(ac->req->conn->event.event_ctx) != 0) {
929                         return LDB_ERR_OTHER;
930                 }
931                 break;
932         case LDB_WAIT_ONCE:
933                 while (handle->status == LDB_SUCCESS && handle->state == LDB_ASYNC_INIT) {
934                        if (event_loop_once(ac->req->conn->event.event_ctx) != 0) {
935                                 return LDB_ERR_OTHER;
936                         }
937                 }
938                 break;
939         case LDB_WAIT_ALL:
940                 while (handle->status == LDB_SUCCESS && handle->state != LDB_ASYNC_DONE) {
941                         if (event_loop_once(ac->req->conn->event.event_ctx) != 0) {
942                                 return LDB_ERR_OTHER;
943                         }
944                 }
945                 break;
946         default:
947                 return LDB_ERR_OPERATIONS_ERROR;
948         }
949         
950         return handle->status;
951 }
952
953 /*
954   fetch the rootDSE for later use
955 */
956 static int ildb_init(struct ldb_module *module)
957 {
958         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
959         struct ldb_result *res = NULL;
960         struct ldb_dn *empty_dn = ldb_dn_new(ildb);
961         int ret;
962         ret = ildb_search_bytree(module, empty_dn, LDB_SCOPE_BASE, 
963                                  ldb_parse_tree(empty_dn, "dn=dc=rootDSE"), 
964                                  NULL, NULL, &res);
965         if (ret == LDB_SUCCESS && res->count == 1) {
966                 ildb->rootDSE = talloc_steal(ildb, res->msgs[0]);
967         }
968         if (ret == LDB_SUCCESS) talloc_free(res);
969         talloc_free(empty_dn);
970
971         return LDB_SUCCESS;
972 }
973
974 static const struct ldb_module_ops ildb_ops = {
975         .name              = "ldap",
976         .request           = ildb_request,
977         .start_transaction = ildb_start_trans,
978         .end_transaction   = ildb_end_trans,
979         .del_transaction   = ildb_del_trans,
980         .async_wait        = ildb_async_wait,
981         .init_context      = ildb_init
982 };
983
984 /*
985   connect to the database
986 */
987 int ildb_connect(struct ldb_context *ldb, const char *url, 
988                  unsigned int flags, const char *options[])
989 {
990         struct ildb_private *ildb = NULL;
991         NTSTATUS status;
992         struct cli_credentials *creds;
993
994         ildb = talloc(ldb, struct ildb_private);
995         if (!ildb) {
996                 ldb_oom(ldb);
997                 goto failed;
998         }
999
1000         ildb->rootDSE = NULL;
1001         ildb->ldb     = ldb;
1002
1003         ildb->ldap = ldap_new_connection(ildb, ldb_get_opaque(ldb, "EventContext"));
1004         if (!ildb->ldap) {
1005                 ldb_oom(ldb);
1006                 goto failed;
1007         }
1008
1009         status = ldap_connect(ildb->ldap, url);
1010         if (!NT_STATUS_IS_OK(status)) {
1011                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to connect to ldap URL '%s' - %s\n",
1012                           url, ldap_errstr(ildb->ldap, status));
1013                 goto failed;
1014         }
1015
1016         ldb->modules = talloc(ldb, struct ldb_module);
1017         if (!ldb->modules) {
1018                 ldb_oom(ldb);
1019                 goto failed;
1020         }
1021         ldb->modules->ldb = ldb;
1022         ldb->modules->prev = ldb->modules->next = NULL;
1023         ldb->modules->private_data = ildb;
1024         ldb->modules->ops = &ildb_ops;
1025
1026         /* caller can optionally setup credentials using the opaque token 'credentials' */
1027         creds = talloc_get_type(ldb_get_opaque(ldb, "credentials"), struct cli_credentials);
1028         if (creds == NULL) {
1029                 struct auth_session_info *session_info = talloc_get_type(ldb_get_opaque(ldb, "sessionInfo"), struct auth_session_info);
1030                 if (session_info) {
1031                         creds = session_info->credentials;
1032                 }
1033         }
1034
1035         if (creds != NULL && cli_credentials_authentication_requested(creds)) {
1036                 const char *bind_dn = cli_credentials_get_bind_dn(creds);
1037                 if (bind_dn) {
1038                         const char *password = cli_credentials_get_password(creds);
1039                         status = ldap_bind_simple(ildb->ldap, bind_dn, password);
1040                         if (!NT_STATUS_IS_OK(status)) {
1041                                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to bind - %s\n",
1042                                           ldap_errstr(ildb->ldap, status));
1043                                 goto failed;
1044                         }
1045                 } else {
1046                         status = ldap_bind_sasl(ildb->ldap, creds);
1047                         if (!NT_STATUS_IS_OK(status)) {
1048                                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to bind - %s\n",
1049                                           ldap_errstr(ildb->ldap, status));
1050                                 goto failed;
1051                         }
1052                 }
1053         }
1054
1055         return 0;
1056
1057 failed:
1058         if (ldb->modules) {
1059                 ldb->modules->private_data = NULL;
1060         }
1061         talloc_free(ildb);
1062         return -1;
1063 }
1064