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