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