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