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