r14163: Remove LDB_WAIT_ONCE, we can hardly guarante we
[ira/wip.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         h->module = module;
345
346         ildb_ac = talloc(h, struct ildb_async_context);
347         if (ildb_ac == NULL) {
348                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Out of Memory"));
349                 talloc_free(h);
350                 return LDB_ERR_OPERATIONS_ERROR;
351         }
352
353         h->private_data = (void *)ildb_ac;
354
355         h->state = LDB_ASYNC_INIT;
356         h->status = LDB_SUCCESS;
357
358         req = ldap_request_send(ildb->ldap, msg);
359         if (req == NULL) {
360                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "async send request failed"));
361                 return LDB_ERR_OPERATIONS_ERROR;
362         }
363
364         ildb_ac->req = talloc_steal(ildb_ac, req);
365         ildb_ac->module = module;
366         ildb_ac->context = context;
367         ildb_ac->callback = callback;
368
369         req->async.fn = ildb_async_callback;
370         req->async.private_data = (void *)h;
371
372         talloc_free(req->time_event);
373         req->time_event = NULL;
374         if (timeout) {
375                 req->time_event = event_add_timed(req->conn->event.event_ctx, h, 
376                                                   timeval_current_ofs(timeout, 0),
377                                                   ildb_request_timeout, ildb_ac);
378         }
379
380         *handle = h;
381
382         return LDB_SUCCESS;
383
384 }
385
386 /*
387   search for matching records using an asynchronous function
388  */
389 static int ildb_search_async(struct ldb_module *module, const struct ldb_dn *base,
390                               enum ldb_scope scope, struct ldb_parse_tree *tree,
391                               const char * const *attrs,
392                               struct ldb_control **control_req,
393                               void *context,
394                               int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
395                               int timeout,
396                               struct ldb_async_handle **handle)
397 {
398         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
399         struct ldap_message *msg;
400         int n;
401
402         *handle = NULL;
403
404         if (!callback || !context) {
405                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Async interface called with NULL callback function or NULL context"));
406                 return LDB_ERR_OPERATIONS_ERROR;
407         }
408         
409         if (tree == NULL) {
410                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Invalid expression parse tree"));
411                 return LDB_ERR_OPERATIONS_ERROR;
412         }
413
414         msg = new_ldap_message(ildb);
415         if (msg == NULL) {
416                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Out of Memory"));
417                 return LDB_ERR_OPERATIONS_ERROR;
418         }
419
420         msg->type = LDAP_TAG_SearchRequest;
421
422         if (base == NULL) {
423                 if (ildb->rootDSE != NULL) {
424                         msg->r.SearchRequest.basedn =
425                                 talloc_strdup(msg, ldb_msg_find_string(ildb->rootDSE, "defaultNamingContext", ""));
426                 } else {
427                         msg->r.SearchRequest.basedn = talloc_strdup(msg, "");
428                 }
429         } else {
430                 msg->r.SearchRequest.basedn  = ldb_dn_linearize(msg, base);
431         }
432         if (msg->r.SearchRequest.basedn == NULL) {
433                 ldb_set_errstring(module->ldb, talloc_asprintf(module, "Unable to determine baseDN"));
434                 talloc_free(msg);
435                 return LDB_ERR_OPERATIONS_ERROR;
436         }
437
438         if (scope == LDB_SCOPE_DEFAULT) {
439                 msg->r.SearchRequest.scope = LDB_SCOPE_SUBTREE;
440         } else {
441                 msg->r.SearchRequest.scope = scope;
442         }
443         
444         msg->r.SearchRequest.deref  = LDAP_DEREFERENCE_NEVER;
445         msg->r.SearchRequest.timelimit = 0;
446         msg->r.SearchRequest.sizelimit = 0;
447         msg->r.SearchRequest.attributesonly = 0;
448         msg->r.SearchRequest.tree = tree;
449         
450         for (n = 0; attrs && attrs[n]; n++) /* noop */ ;
451         msg->r.SearchRequest.num_attributes = n;
452         msg->r.SearchRequest.attributes = discard_const(attrs);
453         msg->controls = control_req;
454
455         return ildb_request_send(module, msg, context, callback, timeout, handle);
456 }
457
458 static int ildb_search_sync_callback(struct ldb_context *ldb, void *context, struct ldb_async_result *ares)
459 {
460         struct ldb_result *res;
461         int n;
462         
463         if (!context) {
464                 ldb_set_errstring(ldb, talloc_asprintf(ldb, "NULL Context in callback"));
465                 return LDB_ERR_OPERATIONS_ERROR;
466         }       
467
468         res = *((struct ldb_result **)context);
469
470         if (!res || !ares) {
471                 goto error;
472         }
473
474         if (ares->type == LDB_REPLY_ENTRY) {
475                 res->msgs = talloc_realloc(res, res->msgs, struct ldb_message *, res->count + 2);
476                 if (! res->msgs) {
477                         goto error;
478                 }
479
480                 res->msgs[res->count + 1] = NULL;
481
482                 res->msgs[res->count] = talloc_steal(res->msgs, ares->message);
483                 if (! res->msgs[res->count]) {
484                         goto error;
485                 }
486
487                 res->count++;
488         }
489
490         if (ares->type == LDB_REPLY_REFERRAL) {
491                 if (res->refs) {
492                         for (n = 0; res->refs[n]; n++) /*noop*/ ;
493                 } else {
494                         n = 0;
495                 }
496
497                 res->refs = talloc_realloc(res, res->refs, char *, n + 2);
498                 if (! res->refs) {
499                         goto error;
500                 }
501
502                 res->refs[n] = talloc_steal(res->refs, ares->referral);
503                 res->refs[n + 1] = NULL;
504         }
505
506         if (ares->controls) {
507                 res->controls = talloc_steal(res, ares->controls);
508                 if (! res->controls) {
509                         goto error;
510                 }
511         }
512
513         talloc_free(ares);
514         return LDB_SUCCESS;
515
516 error:
517         talloc_free(ares);
518         talloc_free(res);
519         *((struct ldb_result **)context) = NULL;
520         return LDB_ERR_OPERATIONS_ERROR;
521 }
522
523 /*
524   search for matching records using a synchronous function
525  */
526 static int ildb_search_bytree(struct ldb_module *module, const struct ldb_dn *base,
527                               enum ldb_scope scope, struct ldb_parse_tree *tree,
528                               const char * const *attrs,
529                               struct ldb_control **control_req,
530                               struct ldb_result **res)
531 {
532         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
533         struct ldb_async_handle *handle;
534         int ret;
535
536         *res = talloc_zero(ildb, struct ldb_result);
537         if (! *res) {
538                 return LDB_ERR_OPERATIONS_ERROR;
539         }
540
541         ret = ildb_search_async(module, base, scope, tree, attrs, control_req,
542                                 res, &ildb_search_sync_callback, ildb->ldap->timeout, &handle);
543
544         if (ret == LDB_SUCCESS) {
545                 ret = ldb_async_wait(handle, LDB_WAIT_ALL);
546                 talloc_free(handle);
547         }
548
549         if (ret != LDB_SUCCESS) {
550                 talloc_free(*res);
551         }
552
553         return ret;
554 }
555
556 /*
557   add a record
558 */
559 static int ildb_add_async(struct ldb_module *module, const struct ldb_message *ldb_msg,
560                           void *context,
561                           int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
562                           int timeout,
563                           struct ldb_async_handle **handle)
564 {
565         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
566         struct ldap_message *msg;
567         struct ldap_mod **mods;
568         int i,n;
569
570         *handle = NULL;
571
572         /* ignore ltdb specials */
573         if (ldb_dn_is_special(ldb_msg->dn)) {
574                 return LDB_SUCCESS;
575         }
576
577         msg = new_ldap_message(ildb->ldap);
578         if (msg == NULL) {
579                 return LDB_ERR_OPERATIONS_ERROR;
580         }
581
582         msg->type = LDAP_TAG_AddRequest;
583
584         msg->r.AddRequest.dn = ldb_dn_linearize(msg, ldb_msg->dn);
585         if (msg->r.AddRequest.dn == NULL) {
586                 talloc_free(msg);
587                 return LDB_ERR_INVALID_DN_SYNTAX;
588         }
589
590         mods = ildb_msg_to_mods(msg, &n, ldb_msg, 0);
591         if (mods == NULL) {
592                 talloc_free(msg);
593                 return LDB_ERR_OPERATIONS_ERROR;
594         }
595
596         msg->r.AddRequest.num_attributes = n;
597         msg->r.AddRequest.attributes = talloc_array(msg, struct ldb_message_element, n);
598         if (msg->r.AddRequest.attributes == NULL) {
599                 talloc_free(msg);
600                 return LDB_ERR_OPERATIONS_ERROR;
601         }
602
603         for (i = 0; i < n; i++) {
604                 msg->r.AddRequest.attributes[i] = mods[i]->attrib;
605         }
606
607         return ildb_request_send(module, msg, context, callback, timeout, handle);
608 }
609
610 static int ildb_add(struct ldb_module *module, const struct ldb_message *msg)
611 {
612         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
613         struct ldb_async_handle *handle;
614         int ret;
615
616         ret = ildb_add_async(module, msg,
617                                 NULL, NULL, ildb->ldap->timeout, &handle);
618
619         if (ret != LDB_SUCCESS)
620                 return ret;
621
622         ret = ldb_async_wait(handle, LDB_WAIT_ALL);
623
624         talloc_free(handle);
625         return ret;
626 }
627
628 /*
629   modify a record
630 */
631 static int ildb_modify_async(struct ldb_module *module, const struct ldb_message *ldb_msg,
632                              void *context,
633                              int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
634                              int timeout,
635                              struct ldb_async_handle **handle)
636 {
637         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
638         struct ldap_message *msg;
639         struct ldap_mod **mods;
640         int i,n;
641
642         *handle = NULL;
643
644         /* ignore ltdb specials */
645         if (ldb_dn_is_special(ldb_msg->dn)) {
646                 return LDB_SUCCESS;
647         }
648
649         msg = new_ldap_message(ildb->ldap);
650         if (msg == NULL) {
651                 return LDB_ERR_OPERATIONS_ERROR;
652         }
653
654         msg->type = LDAP_TAG_ModifyRequest;
655
656         msg->r.ModifyRequest.dn = ldb_dn_linearize(msg, ldb_msg->dn);
657         if (msg->r.ModifyRequest.dn == NULL) {
658                 talloc_free(msg);
659                 return LDB_ERR_INVALID_DN_SYNTAX;
660         }
661
662         mods = ildb_msg_to_mods(msg, &n, ldb_msg, 1);
663         if (mods == NULL) {
664                 talloc_free(msg);
665                 return LDB_ERR_OPERATIONS_ERROR;
666         }
667
668         msg->r.ModifyRequest.num_mods = n;
669         msg->r.ModifyRequest.mods = talloc_array(msg, struct ldap_mod, n);
670         if (msg->r.ModifyRequest.mods == NULL) {
671                 talloc_free(msg);
672                 return LDB_ERR_OPERATIONS_ERROR;
673         }
674
675         for (i = 0; i < n; i++) {
676                 msg->r.ModifyRequest.mods[i] = *mods[i];
677         }
678
679         return ildb_request_send(module, msg, context, callback, timeout, handle);
680 }
681
682 static int ildb_modify(struct ldb_module *module, const struct ldb_message *msg)
683 {
684         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
685         struct ldb_async_handle *handle;
686         int ret;
687
688         ret = ildb_modify_async(module, msg,
689                                 NULL, NULL, ildb->ldap->timeout, &handle);
690
691         if (ret != LDB_SUCCESS)
692                 return ret;
693
694         ret = ldb_async_wait(handle, LDB_WAIT_ALL);
695
696         talloc_free(handle);
697         return ret;
698 }
699
700 /*
701   delete a record
702 */
703 static int ildb_delete_async(struct ldb_module *module, const struct ldb_dn *dn,
704                              void *context,
705                              int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
706                              int timeout,
707                              struct ldb_async_handle **handle)
708 {
709         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
710         struct ldap_message *msg;
711
712         *handle = NULL;
713
714         /* ignore ltdb specials */
715         if (ldb_dn_is_special(dn)) {
716                 return LDB_SUCCESS;
717         }
718
719         msg = new_ldap_message(ildb->ldap);
720         if (msg == NULL) {
721                 return LDB_ERR_OPERATIONS_ERROR;
722         }
723
724         msg->type = LDAP_TAG_DelRequest;
725         
726         msg->r.DelRequest.dn = ldb_dn_linearize(msg, dn);
727         if (msg->r.DelRequest.dn == NULL) {
728                 talloc_free(msg);
729                 return LDB_ERR_INVALID_DN_SYNTAX;
730         }
731
732         return ildb_request_send(module, msg, context, callback, timeout, handle);
733 }
734
735 static int ildb_delete(struct ldb_module *module, const struct ldb_dn *dn)
736 {
737         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
738         struct ldb_async_handle *handle;
739         int ret;
740
741         ret = ildb_delete_async(module, dn,
742                                 NULL, NULL, ildb->ldap->timeout, &handle);
743
744         if (ret != LDB_SUCCESS)
745                 return ret;
746
747         ret = ldb_async_wait(handle, LDB_WAIT_ALL);
748
749         talloc_free(handle);
750         return ret;
751 }
752
753 /*
754   rename a record
755 */
756 static int ildb_rename_async(struct ldb_module *module,
757                              const struct ldb_dn *olddn, const struct ldb_dn *newdn,
758                              void *context,
759                              int (*callback)(struct ldb_context *, void *, struct ldb_async_result *),
760                              int timeout,
761                              struct ldb_async_handle **handle)
762 {
763         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
764         struct ldap_message *msg;
765
766         *handle = NULL;
767
768         /* ignore ltdb specials */
769         if (ldb_dn_is_special(olddn) || ldb_dn_is_special(newdn)) {
770                 return LDB_SUCCESS;
771         }
772
773         msg = new_ldap_message(ildb->ldap);
774         if (msg == NULL) {
775                 return LDB_ERR_OPERATIONS_ERROR;
776         }
777
778         msg->type = LDAP_TAG_ModifyDNRequest;
779         msg->r.ModifyDNRequest.dn = ldb_dn_linearize(msg, olddn);
780         if (msg->r.ModifyDNRequest.dn == NULL) {
781                 talloc_free(msg);
782                 return LDB_ERR_INVALID_DN_SYNTAX;
783         }
784
785         msg->r.ModifyDNRequest.newrdn = 
786                 talloc_asprintf(msg, "%s=%s",
787                                 newdn->components[0].name,
788                                 ldb_dn_escape_value(msg, newdn->components[0].value));
789         if (msg->r.ModifyDNRequest.newrdn == NULL) {
790                 talloc_free(msg);
791                 return LDB_ERR_OPERATIONS_ERROR;
792         }
793
794         msg->r.ModifyDNRequest.newsuperior =
795                 ldb_dn_linearize(msg,
796                                  ldb_dn_get_parent(msg, newdn));
797         if (msg->r.ModifyDNRequest.newsuperior == NULL) {
798                 talloc_free(msg);
799                 return LDB_ERR_INVALID_DN_SYNTAX;
800         }
801
802         msg->r.ModifyDNRequest.deleteolddn = True;
803
804         return ildb_request_send(module, msg, context, callback, timeout, handle);
805 }
806
807 static int ildb_rename(struct ldb_module *module, const struct ldb_dn *olddn, const struct ldb_dn *newdn)
808 {
809         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
810         struct ldb_async_handle *handle;
811         int ret;
812
813         ret = ildb_rename_async(module, olddn, newdn,
814                                 NULL, NULL, ildb->ldap->timeout, &handle);
815
816         if (ret != LDB_SUCCESS)
817                 return ret;
818
819         ret = ldb_async_wait(handle, LDB_WAIT_ALL);
820
821         talloc_free(handle);
822         return ret;
823 }
824
825 static int ildb_start_trans(struct ldb_module *module)
826 {
827         /* TODO implement a local locking mechanism here */
828
829         return 0;
830 }
831
832 static int ildb_end_trans(struct ldb_module *module)
833 {
834         /* TODO implement a local transaction mechanism here */
835
836         return 0;
837 }
838
839 static int ildb_del_trans(struct ldb_module *module)
840 {
841         /* TODO implement a local locking mechanism here */
842
843         return 0;
844 }
845
846 static int ildb_request(struct ldb_module *module, struct ldb_request *req)
847 {
848         switch (req->operation) {
849
850         case LDB_REQ_SEARCH:
851                 return ildb_search_bytree(module,
852                                           req->op.search.base,
853                                           req->op.search.scope, 
854                                           req->op.search.tree, 
855                                           req->op.search.attrs, 
856                                           req->controls,
857                                           &req->op.search.res);
858
859         case LDB_REQ_ADD:
860                 return ildb_add(module, req->op.add.message);
861
862         case LDB_REQ_MODIFY:
863                 return ildb_modify(module, req->op.mod.message);
864
865         case LDB_REQ_DELETE:
866                 return ildb_delete(module, req->op.del.dn);
867
868         case LDB_REQ_RENAME:
869                 return ildb_rename(module,
870                                         req->op.rename.olddn,
871                                         req->op.rename.newdn);
872
873         case LDB_ASYNC_SEARCH:
874                 return ildb_search_async(module,
875                                         req->op.search.base,
876                                         req->op.search.scope, 
877                                         req->op.search.tree, 
878                                         req->op.search.attrs,
879                                         req->controls,
880                                         req->async.context,
881                                         req->async.callback,
882                                         req->async.timeout,
883                                         &req->async.handle);
884
885         case LDB_ASYNC_ADD:
886                 return ildb_add_async(module,
887                                         req->op.add.message,
888                                         req->async.context,
889                                         req->async.callback,
890                                         req->async.timeout,
891                                         &req->async.handle);
892
893         case LDB_ASYNC_MODIFY:
894                 return ildb_modify_async(module,
895                                         req->op.mod.message,
896                                         req->async.context,
897                                         req->async.callback,
898                                         req->async.timeout,
899                                         &req->async.handle);
900
901         case LDB_ASYNC_DELETE:
902                 return ildb_delete_async(module,
903                                         req->op.del.dn,
904                                         req->async.context,
905                                         req->async.callback,
906                                         req->async.timeout,
907                                         &req->async.handle);
908
909         case LDB_ASYNC_RENAME:
910                 return ildb_rename_async(module,
911                                         req->op.rename.olddn,
912                                         req->op.rename.newdn,
913                                         req->async.context,
914                                         req->async.callback,
915                                         req->async.timeout,
916                                         &req->async.handle);
917
918         default:
919                 return -1;
920
921         }
922 }
923
924 static int ildb_async_wait(struct ldb_async_handle *handle, enum ldb_async_wait_type type)
925 {
926         struct ildb_async_context *ac = talloc_get_type(handle->private_data, struct ildb_async_context);
927
928         if (handle->state == LDB_ASYNC_DONE) {
929                 return handle->status;
930         }
931
932         if (!ac) {
933                 return LDB_ERR_OPERATIONS_ERROR;
934         }
935
936         handle->state = LDB_ASYNC_INIT;
937
938         switch(type) {
939         case LDB_WAIT_NONE:
940                 if (event_loop_once(ac->req->conn->event.event_ctx) != 0) {
941                         return LDB_ERR_OTHER;
942                 }
943                 break;
944         case LDB_WAIT_ALL:
945                 while (handle->status == LDB_SUCCESS && handle->state != LDB_ASYNC_DONE) {
946                         if (event_loop_once(ac->req->conn->event.event_ctx) != 0) {
947                                 return LDB_ERR_OTHER;
948                         }
949                 }
950                 break;
951         default:
952                 return LDB_ERR_OPERATIONS_ERROR;
953         }
954         
955         return handle->status;
956 }
957
958 /*
959   fetch the rootDSE for later use
960 */
961 static int ildb_init(struct ldb_module *module)
962 {
963         struct ildb_private *ildb = talloc_get_type(module->private_data, struct ildb_private);
964         struct ldb_result *res = NULL;
965         struct ldb_dn *empty_dn = ldb_dn_new(ildb);
966         int ret;
967         ret = ildb_search_bytree(module, empty_dn, LDB_SCOPE_BASE, 
968                                  ldb_parse_tree(empty_dn, "dn=dc=rootDSE"), 
969                                  NULL, NULL, &res);
970         if (ret == LDB_SUCCESS && res->count == 1) {
971                 ildb->rootDSE = talloc_steal(ildb, res->msgs[0]);
972         }
973         if (ret == LDB_SUCCESS) talloc_free(res);
974         talloc_free(empty_dn);
975
976         return LDB_SUCCESS;
977 }
978
979 static const struct ldb_module_ops ildb_ops = {
980         .name              = "ldap",
981         .request           = ildb_request,
982         .start_transaction = ildb_start_trans,
983         .end_transaction   = ildb_end_trans,
984         .del_transaction   = ildb_del_trans,
985         .async_wait        = ildb_async_wait,
986         .init_context      = ildb_init
987 };
988
989 /*
990   connect to the database
991 */
992 static int ildb_connect(struct ldb_context *ldb, const char *url, 
993                  unsigned int flags, const char *options[])
994 {
995         struct ildb_private *ildb = NULL;
996         NTSTATUS status;
997         struct cli_credentials *creds;
998
999         ildb = talloc(ldb, struct ildb_private);
1000         if (!ildb) {
1001                 ldb_oom(ldb);
1002                 goto failed;
1003         }
1004
1005         ildb->rootDSE = NULL;
1006         ildb->ldb     = ldb;
1007
1008         ildb->ldap = ldap_new_connection(ildb, ldb_get_opaque(ldb, "EventContext"));
1009         if (!ildb->ldap) {
1010                 ldb_oom(ldb);
1011                 goto failed;
1012         }
1013
1014         status = ldap_connect(ildb->ldap, url);
1015         if (!NT_STATUS_IS_OK(status)) {
1016                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to connect to ldap URL '%s' - %s\n",
1017                           url, ldap_errstr(ildb->ldap, status));
1018                 goto failed;
1019         }
1020
1021         ldb->modules = talloc(ldb, struct ldb_module);
1022         if (!ldb->modules) {
1023                 ldb_oom(ldb);
1024                 goto failed;
1025         }
1026         ldb->modules->ldb = ldb;
1027         ldb->modules->prev = ldb->modules->next = NULL;
1028         ldb->modules->private_data = ildb;
1029         ldb->modules->ops = &ildb_ops;
1030
1031         /* caller can optionally setup credentials using the opaque token 'credentials' */
1032         creds = talloc_get_type(ldb_get_opaque(ldb, "credentials"), struct cli_credentials);
1033         if (creds == NULL) {
1034                 struct auth_session_info *session_info = talloc_get_type(ldb_get_opaque(ldb, "sessionInfo"), struct auth_session_info);
1035                 if (session_info) {
1036                         creds = session_info->credentials;
1037                 }
1038         }
1039
1040         if (creds != NULL && cli_credentials_authentication_requested(creds)) {
1041                 const char *bind_dn = cli_credentials_get_bind_dn(creds);
1042                 if (bind_dn) {
1043                         const char *password = cli_credentials_get_password(creds);
1044                         status = ldap_bind_simple(ildb->ldap, bind_dn, password);
1045                         if (!NT_STATUS_IS_OK(status)) {
1046                                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to bind - %s\n",
1047                                           ldap_errstr(ildb->ldap, status));
1048                                 goto failed;
1049                         }
1050                 } else {
1051                         status = ldap_bind_sasl(ildb->ldap, creds);
1052                         if (!NT_STATUS_IS_OK(status)) {
1053                                 ldb_debug(ldb, LDB_DEBUG_ERROR, "Failed to bind - %s\n",
1054                                           ldap_errstr(ildb->ldap, status));
1055                                 goto failed;
1056                         }
1057                 }
1058         }
1059
1060         return 0;
1061
1062 failed:
1063         if (ldb->modules) {
1064                 ldb->modules->private_data = NULL;
1065         }
1066         talloc_free(ildb);
1067         return -1;
1068 }
1069
1070 int ldb_ildap_init(void)
1071 {
1072         return ldb_register_backend("ldap", ildb_connect);
1073 }