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