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