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