Add context for libcli_resolve.
[samba-svnmirror.git] / source / libcli / ldap / ldap_client.c
1 /* 
2    Unix SMB/CIFS mplementation.
3    LDAP protocol helper functions for SAMBA
4    
5    Copyright (C) Andrew Tridgell  2004
6    Copyright (C) Volker Lendecke 2004
7    Copyright (C) Stefan Metzmacher 2004
8    Copyright (C) Simo Sorce 2004
9     
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22    
23 */
24
25 #include "includes.h"
26 #include "libcli/util/asn_1.h"
27 #include "lib/util/dlinklist.h"
28 #include "lib/events/events.h"
29 #include "lib/socket/socket.h"
30 #include "libcli/ldap/ldap.h"
31 #include "libcli/ldap/ldap_client.h"
32 #include "libcli/composite/composite.h"
33 #include "lib/stream/packet.h"
34 #include "lib/tls/tls.h"
35 #include "auth/gensec/gensec.h"
36 #include "system/time.h"
37 #include "param/param.h"
38 #include "libcli/resolve/resolve.h"
39
40
41 /**
42   create a new ldap_connection stucture. The event context is optional
43 */
44 struct ldap_connection *ldap4_new_connection(TALLOC_CTX *mem_ctx, 
45                                              struct loadparm_context *lp_ctx,
46                                              struct event_context *ev)
47 {
48         struct ldap_connection *conn;
49
50         conn = talloc_zero(mem_ctx, struct ldap_connection);
51         if (conn == NULL) {
52                 return NULL;
53         }
54
55         if (ev == NULL) {
56                 ev = event_context_init(conn);
57                 if (ev == NULL) {
58                         talloc_free(conn);
59                         return NULL;
60                 }
61         }
62
63         conn->next_messageid  = 1;
64         conn->event.event_ctx = ev;
65
66         conn->lp_ctx = lp_ctx;
67
68         /* set a reasonable request timeout */
69         conn->timeout = 60;
70
71         /* explicitly avoid reconnections by default */
72         conn->reconnect.max_retries = 0;
73         
74         return conn;
75 }
76
77 /*
78   the connection is dead
79 */
80 static void ldap_connection_dead(struct ldap_connection *conn)
81 {
82         struct ldap_request *req;
83
84         /* return an error for any pending request ... */
85         while (conn->pending) {
86                 req = conn->pending;
87                 DLIST_REMOVE(req->conn->pending, req);
88                 req->state = LDAP_REQUEST_DONE;
89                 req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
90                 if (req->async.fn) {
91                         req->async.fn(req);
92                 }
93         }
94
95         talloc_free(conn->sock);  /* this will also free event.fde */
96         talloc_free(conn->packet);
97         conn->sock = NULL;
98         conn->event.fde = NULL;
99         conn->packet = NULL;
100 }
101
102 static void ldap_reconnect(struct ldap_connection *conn);
103
104 /*
105   handle packet errors
106 */
107 static void ldap_error_handler(void *private_data, NTSTATUS status)
108 {
109         struct ldap_connection *conn = talloc_get_type(private_data, 
110                                                        struct ldap_connection);
111         ldap_connection_dead(conn);
112
113         /* but try to reconnect so that the ldb client can go on */
114         ldap_reconnect(conn);
115 }
116
117
118 /*
119   match up with a pending message, adding to the replies list
120 */
121 static void ldap_match_message(struct ldap_connection *conn, struct ldap_message *msg)
122 {
123         struct ldap_request *req;
124         int i;
125
126         for (req=conn->pending; req; req=req->next) {
127                 if (req->messageid == msg->messageid) break;
128         }
129         /* match a zero message id to the last request sent.
130            It seems that servers send 0 if unable to parse */
131         if (req == NULL && msg->messageid == 0) {
132                 req = conn->pending;
133         }
134         if (req == NULL) {
135                 DEBUG(0,("ldap: no matching message id for %u\n",
136                          msg->messageid));
137                 talloc_free(msg);
138                 return;
139         }
140
141         /* Check for undecoded critical extensions */
142         for (i=0; msg->controls && msg->controls[i]; i++) {
143                 if (!msg->controls_decoded[i] && 
144                     msg->controls[i]->critical) {
145                         req->status = NT_STATUS_LDAP(LDAP_UNAVAILABLE_CRITICAL_EXTENSION);
146                         req->state = LDAP_REQUEST_DONE;
147                         DLIST_REMOVE(conn->pending, req);
148                         if (req->async.fn) {
149                                 req->async.fn(req);
150                         }
151                         return;
152                 }
153         }
154
155         /* add to the list of replies received */
156         talloc_steal(req, msg);
157         req->replies = talloc_realloc(req, req->replies, 
158                                       struct ldap_message *, req->num_replies+1);
159         if (req->replies == NULL) {
160                 req->status = NT_STATUS_NO_MEMORY;
161                 req->state = LDAP_REQUEST_DONE;
162                 DLIST_REMOVE(conn->pending, req);
163                 if (req->async.fn) {
164                         req->async.fn(req);
165                 }
166                 return;
167         }
168
169         req->replies[req->num_replies] = talloc_steal(req->replies, msg);
170         req->num_replies++;
171
172         if (msg->type != LDAP_TAG_SearchResultEntry &&
173             msg->type != LDAP_TAG_SearchResultReference) {
174                 /* currently only search results expect multiple
175                    replies */
176                 req->state = LDAP_REQUEST_DONE;
177                 DLIST_REMOVE(conn->pending, req);
178         }
179
180         if (req->async.fn) {
181                 req->async.fn(req);
182         }
183 }
184
185
186 /*
187   decode/process LDAP data
188 */
189 static NTSTATUS ldap_recv_handler(void *private_data, DATA_BLOB blob)
190 {
191         NTSTATUS status;
192         struct ldap_connection *conn = talloc_get_type(private_data, 
193                                                        struct ldap_connection);
194         struct ldap_message *msg = talloc(conn, struct ldap_message);
195         struct asn1_data *asn1 = asn1_init(conn);
196
197         if (asn1 == NULL || msg == NULL) {
198                 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
199         }
200
201         if (!asn1_load(asn1, blob)) {
202                 talloc_free(msg);
203                 talloc_free(asn1);
204                 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
205         }
206         
207         status = ldap_decode(asn1, msg);
208         if (!NT_STATUS_IS_OK(status)) {
209                 asn1_free(asn1);
210                 return status;
211         }
212
213         ldap_match_message(conn, msg);
214
215         data_blob_free(&blob);
216         asn1_free(asn1);
217         return NT_STATUS_OK;
218 }
219
220 /* Handle read events, from the GENSEC socket callback, or real events */
221 void ldap_read_io_handler(void *private_data, uint16_t flags) 
222 {
223         struct ldap_connection *conn = talloc_get_type(private_data, 
224                                                        struct ldap_connection);
225         packet_recv(conn->packet);
226 }
227
228 /*
229   handle ldap socket events
230 */
231 static void ldap_io_handler(struct event_context *ev, struct fd_event *fde, 
232                             uint16_t flags, void *private_data)
233 {
234         struct ldap_connection *conn = talloc_get_type(private_data, 
235                                                        struct ldap_connection);
236         if (flags & EVENT_FD_WRITE) {
237                 packet_queue_run(conn->packet);
238                 if (!tls_enabled(conn->sock)) return;
239         }
240         if (flags & EVENT_FD_READ) {
241                 ldap_read_io_handler(private_data, flags);
242         }
243 }
244
245 /*
246   parse a ldap URL
247 */
248 static NTSTATUS ldap_parse_basic_url(TALLOC_CTX *mem_ctx, const char *url,
249                                      char **host, uint16_t *port, bool *ldaps)
250 {
251         int tmp_port = 0;
252         char protocol[11];
253         char tmp_host[1025];
254         int ret;
255
256         /* Paranoia check */
257         SMB_ASSERT(sizeof(protocol)>10 && sizeof(tmp_host)>254);
258                 
259         ret = sscanf(url, "%10[^:]://%254[^:/]:%d", protocol, tmp_host, &tmp_port);
260         if (ret < 2) {
261                 return NT_STATUS_INVALID_PARAMETER;
262         }
263
264         if (strequal(protocol, "ldap")) {
265                 *port = 389;
266                 *ldaps = false;
267         } else if (strequal(protocol, "ldaps")) {
268                 *port = 636;
269                 *ldaps = true;
270         } else {
271                 DEBUG(0, ("unrecognised ldap protocol (%s)!\n", protocol));
272                 return NT_STATUS_PROTOCOL_UNREACHABLE;
273         }
274
275         if (tmp_port != 0)
276                 *port = tmp_port;
277
278         *host = talloc_strdup(mem_ctx, tmp_host);
279         NT_STATUS_HAVE_NO_MEMORY(*host);
280
281         return NT_STATUS_OK;
282 }
283
284 /*
285   connect to a ldap server
286 */
287
288 struct ldap_connect_state {
289         struct composite_context *ctx;
290         struct ldap_connection *conn;
291 };
292
293 static void ldap_connect_recv_unix_conn(struct composite_context *ctx);
294 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx);
295
296 struct composite_context *ldap_connect_send(struct ldap_connection *conn,
297                                             const char *url)
298 {
299         struct composite_context *result, *ctx;
300         struct ldap_connect_state *state;
301         char protocol[11];
302         int ret;
303
304         result = talloc_zero(NULL, struct composite_context);
305         if (result == NULL) goto failed;
306         result->state = COMPOSITE_STATE_IN_PROGRESS;
307         result->async.fn = NULL;
308         result->event_ctx = conn->event.event_ctx;
309
310         state = talloc(result, struct ldap_connect_state);
311         if (state == NULL) goto failed;
312         state->ctx = result;
313         result->private_data = state;
314
315         state->conn = conn;
316
317         if (conn->reconnect.url == NULL) {
318                 conn->reconnect.url = talloc_strdup(conn, url);
319                 if (conn->reconnect.url == NULL) goto failed;
320         }
321
322         /* Paranoia check */
323         SMB_ASSERT(sizeof(protocol)>10);
324
325         ret = sscanf(url, "%10[^:]://", protocol);
326         if (ret < 1) {
327                 return NULL;
328         }
329
330         if (strequal(protocol, "ldapi")) {
331                 struct socket_address *unix_addr;
332                 char path[1025];
333         
334                 NTSTATUS status = socket_create("unix", SOCKET_TYPE_STREAM, &conn->sock, 0);
335                 if (!NT_STATUS_IS_OK(status)) {
336                         return NULL;
337                 }
338                 talloc_steal(conn, conn->sock);
339                 SMB_ASSERT(sizeof(protocol)>10);
340                 SMB_ASSERT(sizeof(path)>1024);
341         
342                 /* The %c specifier doesn't null terminate :-( */
343                 ZERO_STRUCT(path);
344                 ret = sscanf(url, "%10[^:]://%1025c", protocol, path);
345                 if (ret < 2) {
346                         composite_error(state->ctx, NT_STATUS_INVALID_PARAMETER);
347                         return result;
348                 }
349
350                 rfc1738_unescape(path);
351         
352                 unix_addr = socket_address_from_strings(conn, conn->sock->backend_name, 
353                                                         path, 0);
354                 if (!unix_addr) {
355                         return NULL;
356                 }
357
358                 ctx = socket_connect_send(conn->sock, NULL, unix_addr, 
359                                           0, lp_resolve_context(conn->lp_ctx), conn->event.event_ctx);
360                 ctx->async.fn = ldap_connect_recv_unix_conn;
361                 ctx->async.private_data = state;
362                 return result;
363         } else {
364                 NTSTATUS status = ldap_parse_basic_url(conn, url, &conn->host,
365                                                           &conn->port, &conn->ldaps);
366                 if (!NT_STATUS_IS_OK(state->ctx->status)) {
367                         composite_error(state->ctx, status);
368                         return result;
369                 }
370                 
371                 ctx = socket_connect_multi_send(state, conn->host, 1, &conn->port,
372                                                 lp_resolve_context(conn->lp_ctx), conn->event.event_ctx);
373                 if (ctx == NULL) goto failed;
374
375                 ctx->async.fn = ldap_connect_recv_tcp_conn;
376                 ctx->async.private_data = state;
377                 return result;
378         }
379  failed:
380         talloc_free(result);
381         return NULL;
382 }
383
384 static void ldap_connect_got_sock(struct composite_context *ctx, 
385                                   struct ldap_connection *conn) 
386 {
387         /* setup a handler for events on this socket */
388         conn->event.fde = event_add_fd(conn->event.event_ctx, conn->sock, 
389                                        socket_get_fd(conn->sock), 
390                                        EVENT_FD_READ | EVENT_FD_AUTOCLOSE, ldap_io_handler, conn);
391         if (conn->event.fde == NULL) {
392                 composite_error(ctx, NT_STATUS_INTERNAL_ERROR);
393                 return;
394         }
395
396         socket_set_flags(conn->sock, SOCKET_FLAG_NOCLOSE);
397
398         talloc_steal(conn, conn->sock);
399         if (conn->ldaps) {
400                 struct socket_context *tls_socket;
401                 char *cafile = private_path(conn->sock, conn->lp_ctx, lp_tls_cafile(conn->lp_ctx));
402
403                 if (!cafile || !*cafile) {
404                         talloc_free(conn->sock);
405                         return;
406                 }
407
408                 tls_socket = tls_init_client(conn->sock, conn->event.fde, cafile);
409                 talloc_free(cafile);
410
411                 if (tls_socket == NULL) {
412                         talloc_free(conn->sock);
413                         return;
414                 }
415                 talloc_unlink(conn, conn->sock);
416                 conn->sock = tls_socket;
417                 talloc_steal(conn, conn->sock);
418         }
419
420         conn->packet = packet_init(conn);
421         if (conn->packet == NULL) {
422                 talloc_free(conn->sock);
423                 return;
424         }
425
426         packet_set_private(conn->packet, conn);
427         packet_set_socket(conn->packet, conn->sock);
428         packet_set_callback(conn->packet, ldap_recv_handler);
429         packet_set_full_request(conn->packet, ldap_full_packet);
430         packet_set_error_handler(conn->packet, ldap_error_handler);
431         packet_set_event_context(conn->packet, conn->event.event_ctx);
432         packet_set_fde(conn->packet, conn->event.fde);
433         packet_set_serialise(conn->packet);
434
435         composite_done(ctx);
436 }
437
438 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx)
439 {
440         struct ldap_connect_state *state =
441                 talloc_get_type(ctx->async.private_data,
442                                 struct ldap_connect_state);
443         struct ldap_connection *conn = state->conn;
444         uint16_t port;
445         NTSTATUS status = socket_connect_multi_recv(ctx, state, &conn->sock,
446                                                        &port);
447         if (!NT_STATUS_IS_OK(status)) {
448                 composite_error(state->ctx, status);
449                 return;
450         }
451
452         ldap_connect_got_sock(state->ctx, conn);
453 }
454
455 static void ldap_connect_recv_unix_conn(struct composite_context *ctx)
456 {
457         struct ldap_connect_state *state =
458                 talloc_get_type(ctx->async.private_data,
459                                 struct ldap_connect_state);
460         struct ldap_connection *conn = state->conn;
461
462         NTSTATUS status = socket_connect_recv(ctx);
463
464         if (!NT_STATUS_IS_OK(state->ctx->status)) {
465                 composite_error(state->ctx, status);
466                 return;
467         }
468
469         ldap_connect_got_sock(state->ctx, conn);
470 }
471
472 _PUBLIC_ NTSTATUS ldap_connect_recv(struct composite_context *ctx)
473 {
474         NTSTATUS status = composite_wait(ctx);
475         talloc_free(ctx);
476         return status;
477 }
478
479 NTSTATUS ldap_connect(struct ldap_connection *conn, const char *url)
480 {
481         struct composite_context *ctx = ldap_connect_send(conn, url);
482         return ldap_connect_recv(ctx);
483 }
484
485 /* set reconnect parameters */
486
487 void ldap_set_reconn_params(struct ldap_connection *conn, int max_retries)
488 {
489         if (conn) {
490                 conn->reconnect.max_retries = max_retries;
491                 conn->reconnect.retries = 0;
492                 conn->reconnect.previous = time(NULL);
493         }
494 }
495
496 /* Actually this function is NOT ASYNC safe, FIXME? */
497 static void ldap_reconnect(struct ldap_connection *conn)
498 {
499         NTSTATUS status;
500         time_t now = time(NULL);
501
502         /* do we have set up reconnect ? */
503         if (conn->reconnect.max_retries == 0) return;
504
505         /* is the retry time expired ? */
506         if (now > conn->reconnect.previous + 30) {
507                 conn->reconnect.retries = 0;
508                 conn->reconnect.previous = now;
509         }
510
511         /* are we reconnectind too often and too fast? */
512         if (conn->reconnect.retries > conn->reconnect.max_retries) return;
513
514         /* keep track of the number of reconnections */
515         conn->reconnect.retries++;
516
517         /* reconnect */
518         status = ldap_connect(conn, conn->reconnect.url);
519         if ( ! NT_STATUS_IS_OK(status)) {
520                 return;
521         }
522
523         /* rebind */
524         status = ldap_rebind(conn);
525         if ( ! NT_STATUS_IS_OK(status)) {
526                 ldap_connection_dead(conn);
527         }
528 }
529
530 /* destroy an open ldap request */
531 static int ldap_request_destructor(struct ldap_request *req)
532 {
533         if (req->state == LDAP_REQUEST_PENDING) {
534                 DLIST_REMOVE(req->conn->pending, req);
535         }
536         return 0;
537 }
538
539 /*
540   called on timeout of a ldap request
541 */
542 static void ldap_request_timeout(struct event_context *ev, struct timed_event *te, 
543                                       struct timeval t, void *private_data)
544 {
545         struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
546         req->status = NT_STATUS_IO_TIMEOUT;
547         if (req->state == LDAP_REQUEST_PENDING) {
548                 DLIST_REMOVE(req->conn->pending, req);
549         }
550         req->state = LDAP_REQUEST_DONE;
551         if (req->async.fn) {
552                 req->async.fn(req);
553         }
554 }
555
556
557 /*
558   called on completion of a one-way ldap request
559 */
560 static void ldap_request_complete(struct event_context *ev, struct timed_event *te, 
561                                   struct timeval t, void *private_data)
562 {
563         struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
564         if (req->async.fn) {
565                 req->async.fn(req);
566         }
567 }
568
569 /*
570   send a ldap message - async interface
571 */
572 struct ldap_request *ldap_request_send(struct ldap_connection *conn,
573                                        struct ldap_message *msg)
574 {
575         struct ldap_request *req;
576         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
577
578         req = talloc_zero(conn, struct ldap_request);
579         if (req == NULL) return NULL;
580
581         if (conn->sock == NULL) {
582                 status = NT_STATUS_INVALID_CONNECTION;
583                 goto failed;
584         }
585
586         req->state       = LDAP_REQUEST_SEND;
587         req->conn        = conn;
588         req->messageid   = conn->next_messageid++;
589         if (conn->next_messageid == 0) {
590                 conn->next_messageid = 1;
591         }
592         req->type        = msg->type;
593         if (req->messageid == -1) {
594                 goto failed;
595         }
596
597         talloc_set_destructor(req, ldap_request_destructor);
598
599         msg->messageid = req->messageid;
600
601         if (!ldap_encode(msg, &req->data, req)) {
602                 status = NT_STATUS_INTERNAL_ERROR;
603                 goto failed;            
604         }
605
606         status = packet_send(conn->packet, req->data);
607         if (!NT_STATUS_IS_OK(status)) {
608                 goto failed;
609         }
610
611         /* some requests don't expect a reply, so don't add those to the
612            pending queue */
613         if (req->type == LDAP_TAG_AbandonRequest ||
614             req->type == LDAP_TAG_UnbindRequest) {
615                 req->status = NT_STATUS_OK;
616                 req->state = LDAP_REQUEST_DONE;
617                 /* we can't call the async callback now, as it isn't setup, so
618                    call it as next event */
619                 event_add_timed(conn->event.event_ctx, req, timeval_zero(),
620                                 ldap_request_complete, req);
621                 return req;
622         }
623
624         req->state = LDAP_REQUEST_PENDING;
625         DLIST_ADD(conn->pending, req);
626
627         /* put a timeout on the request */
628         req->time_event = event_add_timed(conn->event.event_ctx, req, 
629                                           timeval_current_ofs(conn->timeout, 0),
630                                           ldap_request_timeout, req);
631
632         return req;
633
634 failed:
635         req->status = status;
636         req->state = LDAP_REQUEST_ERROR;
637         event_add_timed(conn->event.event_ctx, req, timeval_zero(),
638                         ldap_request_complete, req);
639
640         return req;
641 }
642
643
644 /*
645   wait for a request to complete
646   note that this does not destroy the request
647 */
648 NTSTATUS ldap_request_wait(struct ldap_request *req)
649 {
650         while (req->state < LDAP_REQUEST_DONE) {
651                 if (event_loop_once(req->conn->event.event_ctx) != 0) {
652                         req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
653                         break;
654                 }
655         }
656         return req->status;
657 }
658
659
660 /*
661   a mapping of ldap response code to strings
662 */
663 static const struct {
664         enum ldap_result_code code;
665         const char *str;
666 } ldap_code_map[] = {
667 #define _LDAP_MAP_CODE(c) { c, #c }
668         _LDAP_MAP_CODE(LDAP_SUCCESS),
669         _LDAP_MAP_CODE(LDAP_OPERATIONS_ERROR),
670         _LDAP_MAP_CODE(LDAP_PROTOCOL_ERROR),
671         _LDAP_MAP_CODE(LDAP_TIME_LIMIT_EXCEEDED),
672         _LDAP_MAP_CODE(LDAP_SIZE_LIMIT_EXCEEDED),
673         _LDAP_MAP_CODE(LDAP_COMPARE_FALSE),
674         _LDAP_MAP_CODE(LDAP_COMPARE_TRUE),
675         _LDAP_MAP_CODE(LDAP_AUTH_METHOD_NOT_SUPPORTED),
676         _LDAP_MAP_CODE(LDAP_STRONG_AUTH_REQUIRED),
677         _LDAP_MAP_CODE(LDAP_REFERRAL),
678         _LDAP_MAP_CODE(LDAP_ADMIN_LIMIT_EXCEEDED),
679         _LDAP_MAP_CODE(LDAP_UNAVAILABLE_CRITICAL_EXTENSION),
680         _LDAP_MAP_CODE(LDAP_CONFIDENTIALITY_REQUIRED),
681         _LDAP_MAP_CODE(LDAP_SASL_BIND_IN_PROGRESS),
682         _LDAP_MAP_CODE(LDAP_NO_SUCH_ATTRIBUTE),
683         _LDAP_MAP_CODE(LDAP_UNDEFINED_ATTRIBUTE_TYPE),
684         _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_MATCHING),
685         _LDAP_MAP_CODE(LDAP_CONSTRAINT_VIOLATION),
686         _LDAP_MAP_CODE(LDAP_ATTRIBUTE_OR_VALUE_EXISTS),
687         _LDAP_MAP_CODE(LDAP_INVALID_ATTRIBUTE_SYNTAX),
688         _LDAP_MAP_CODE(LDAP_NO_SUCH_OBJECT),
689         _LDAP_MAP_CODE(LDAP_ALIAS_PROBLEM),
690         _LDAP_MAP_CODE(LDAP_INVALID_DN_SYNTAX),
691         _LDAP_MAP_CODE(LDAP_ALIAS_DEREFERENCING_PROBLEM),
692         _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_AUTHENTICATION),
693         _LDAP_MAP_CODE(LDAP_INVALID_CREDENTIALS),
694         _LDAP_MAP_CODE(LDAP_INSUFFICIENT_ACCESS_RIGHTS),
695         _LDAP_MAP_CODE(LDAP_BUSY),
696         _LDAP_MAP_CODE(LDAP_UNAVAILABLE),
697         _LDAP_MAP_CODE(LDAP_UNWILLING_TO_PERFORM),
698         _LDAP_MAP_CODE(LDAP_LOOP_DETECT),
699         _LDAP_MAP_CODE(LDAP_NAMING_VIOLATION),
700         _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_VIOLATION),
701         _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_NON_LEAF),
702         _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_RDN),
703         _LDAP_MAP_CODE(LDAP_ENTRY_ALREADY_EXISTS),
704         _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_MODS_PROHIBITED),
705         _LDAP_MAP_CODE(LDAP_AFFECTS_MULTIPLE_DSAS),
706         _LDAP_MAP_CODE(LDAP_OTHER)
707 };
708
709 /*
710   used to setup the status code from a ldap response
711 */
712 NTSTATUS ldap_check_response(struct ldap_connection *conn, struct ldap_Result *r)
713 {
714         int i;
715         const char *codename = "unknown";
716
717         if (r->resultcode == LDAP_SUCCESS) {
718                 return NT_STATUS_OK;
719         }
720
721         if (conn->last_error) {
722                 talloc_free(conn->last_error);
723         }
724
725         for (i=0;i<ARRAY_SIZE(ldap_code_map);i++) {
726                 if (r->resultcode == ldap_code_map[i].code) {
727                         codename = ldap_code_map[i].str;
728                         break;
729                 }
730         }
731
732         conn->last_error = talloc_asprintf(conn, "LDAP error %u %s - %s <%s> <%s>", 
733                                            r->resultcode,
734                                            codename,
735                                            r->dn?r->dn:"(NULL)", 
736                                            r->errormessage?r->errormessage:"", 
737                                            r->referral?r->referral:"");
738         
739         return NT_STATUS_LDAP(r->resultcode);
740 }
741
742 /*
743   return error string representing the last error
744 */
745 const char *ldap_errstr(struct ldap_connection *conn, 
746                         TALLOC_CTX *mem_ctx, 
747                         NTSTATUS status)
748 {
749         if (NT_STATUS_IS_LDAP(status) && conn->last_error != NULL) {
750                 return talloc_strdup(mem_ctx, conn->last_error);
751         }
752         return talloc_asprintf(mem_ctx, "LDAP client internal error: %s", nt_errstr(status));
753 }
754
755
756 /*
757   return the Nth result message, waiting if necessary
758 */
759 NTSTATUS ldap_result_n(struct ldap_request *req, int n, struct ldap_message **msg)
760 {
761         *msg = NULL;
762
763         NT_STATUS_HAVE_NO_MEMORY(req);
764
765         while (req->state < LDAP_REQUEST_DONE && n >= req->num_replies) {
766                 if (event_loop_once(req->conn->event.event_ctx) != 0) {
767                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
768                 }
769         }
770
771         if (n < req->num_replies) {
772                 *msg = req->replies[n];
773                 return NT_STATUS_OK;
774         }
775
776         if (!NT_STATUS_IS_OK(req->status)) {
777                 return req->status;
778         }
779
780         return NT_STATUS_NO_MORE_ENTRIES;
781 }
782
783
784 /*
785   return a single result message, checking if it is of the expected LDAP type
786 */
787 NTSTATUS ldap_result_one(struct ldap_request *req, struct ldap_message **msg, int type)
788 {
789         NTSTATUS status;
790         status = ldap_result_n(req, 0, msg);
791         if (!NT_STATUS_IS_OK(status)) {
792                 return status;
793         }
794         if ((*msg)->type != type) {
795                 *msg = NULL;
796                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
797         }
798         return status;
799 }
800
801 /*
802   a simple ldap transaction, for single result requests that only need a status code
803   this relies on single valued requests having the response type == request type + 1
804 */
805 NTSTATUS ldap_transaction(struct ldap_connection *conn, struct ldap_message *msg)
806 {
807         struct ldap_request *req = ldap_request_send(conn, msg);
808         struct ldap_message *res;
809         NTSTATUS status;
810         status = ldap_result_n(req, 0, &res);
811         if (!NT_STATUS_IS_OK(status)) {
812                 talloc_free(req);
813                 return status;
814         }
815         if (res->type != msg->type + 1) {
816                 talloc_free(req);
817                 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
818         }
819         status = ldap_check_response(conn, &res->r.GeneralResult);
820         talloc_free(req);
821         return status;
822 }