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