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