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