libsocket: Add "mem_ctx" to socket_create()
[bbaumbach/samba-autobuild/.git] / source4 / libcli / ldap / ldap_client.c
1 /* 
2    Unix SMB/CIFS implementation.
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 <tevent.h>
27 #include "lib/socket/socket.h"
28 #include "lib/tsocket/tsocket.h"
29 #include "libcli/util/tstream.h"
30 #include "../lib/util/asn1.h"
31 #include "../lib/util/dlinklist.h"
32 #include "libcli/ldap/libcli_ldap.h"
33 #include "libcli/ldap/ldap_proto.h"
34 #include "libcli/ldap/ldap_client.h"
35 #include "libcli/composite/composite.h"
36 #include "lib/tls/tls.h"
37 #include "auth/gensec/gensec.h"
38 #include "system/time.h"
39 #include "param/param.h"
40 #include "libcli/resolve/resolve.h"
41
42 static void ldap_connection_dead(struct ldap_connection *conn, NTSTATUS status);
43
44 static int ldap_connection_destructor(struct ldap_connection *conn)
45 {
46         /*
47          * NT_STATUS_OK means that callbacks of pending requests are not
48          * triggered
49          */
50         ldap_connection_dead(conn, NT_STATUS_OK);
51         return 0;
52 }
53
54 /**
55   create a new ldap_connection stucture. The event context is optional
56 */
57
58 _PUBLIC_ struct ldap_connection *ldap4_new_connection(TALLOC_CTX *mem_ctx, 
59                                              struct loadparm_context *lp_ctx,
60                                              struct tevent_context *ev)
61 {
62         struct ldap_connection *conn;
63
64         if (ev == NULL) {
65                 return NULL;
66         }
67
68         conn = talloc_zero(mem_ctx, struct ldap_connection);
69         if (conn == NULL) {
70                 return NULL;
71         }
72
73         conn->next_messageid  = 1;
74         conn->event.event_ctx = ev;
75
76         conn->sockets.send_queue = tevent_queue_create(conn,
77                                         "ldap_connection send_queue");
78         if (conn->sockets.send_queue == NULL) {
79                 TALLOC_FREE(conn);
80                 return NULL;
81         }
82
83         conn->lp_ctx = lp_ctx;
84
85         /* set a reasonable request timeout */
86         conn->timeout = 60;
87
88         /* explicitly avoid reconnections by default */
89         conn->reconnect.max_retries = 0;
90
91         talloc_set_destructor(conn, ldap_connection_destructor);
92         return conn;
93 }
94
95 /*
96   the connection is dead
97 */
98 static void ldap_connection_dead(struct ldap_connection *conn, NTSTATUS status)
99 {
100         struct ldap_request *req;
101
102         tevent_queue_stop(conn->sockets.send_queue);
103         TALLOC_FREE(conn->sockets.recv_subreq);
104         conn->sockets.active = NULL;
105         TALLOC_FREE(conn->sockets.sasl);
106         TALLOC_FREE(conn->sockets.tls);
107         TALLOC_FREE(conn->sockets.raw);
108
109         /* return an error for any pending request ... */
110         while (conn->pending) {
111                 req = conn->pending;
112                 DLIST_REMOVE(req->conn->pending, req);
113                 req->conn = NULL;
114                 req->state = LDAP_REQUEST_DONE;
115                 if (NT_STATUS_IS_OK(status)) {
116                         continue;
117                 }
118                 req->status = status;
119                 if (req->async.fn) {
120                         req->async.fn(req);
121                 }
122         }
123 }
124
125 static void ldap_reconnect(struct ldap_connection *conn);
126
127 /*
128   handle packet errors
129 */
130 static void ldap_error_handler(struct ldap_connection *conn, NTSTATUS status)
131 {
132         ldap_connection_dead(conn, status);
133
134         /* but try to reconnect so that the ldb client can go on */
135         ldap_reconnect(conn);
136 }
137
138
139 /*
140   match up with a pending message, adding to the replies list
141 */
142 static void ldap_match_message(struct ldap_connection *conn, struct ldap_message *msg)
143 {
144         struct ldap_request *req;
145         int i;
146
147         for (req=conn->pending; req; req=req->next) {
148                 if (req->messageid == msg->messageid) break;
149         }
150         /* match a zero message id to the last request sent.
151            It seems that servers send 0 if unable to parse */
152         if (req == NULL && msg->messageid == 0) {
153                 req = conn->pending;
154         }
155         if (req == NULL) {
156                 DEBUG(0,("ldap: no matching message id for %u\n",
157                          msg->messageid));
158                 TALLOC_FREE(msg);
159                 return;
160         }
161
162         /* Check for undecoded critical extensions */
163         for (i=0; msg->controls && msg->controls[i]; i++) {
164                 if (!msg->controls_decoded[i] && 
165                     msg->controls[i]->critical) {
166                         TALLOC_FREE(msg);
167                         req->status = NT_STATUS_LDAP(LDAP_UNAVAILABLE_CRITICAL_EXTENSION);
168                         req->state = LDAP_REQUEST_DONE;
169                         DLIST_REMOVE(conn->pending, req);
170                         if (req->async.fn) {
171                                 req->async.fn(req);
172                         }
173                         return;
174                 }
175         }
176
177         /* add to the list of replies received */
178         req->replies = talloc_realloc(req, req->replies, 
179                                       struct ldap_message *, req->num_replies+1);
180         if (req->replies == NULL) {
181                 TALLOC_FREE(msg);
182                 req->status = NT_STATUS_NO_MEMORY;
183                 req->state = LDAP_REQUEST_DONE;
184                 DLIST_REMOVE(conn->pending, req);
185                 if (req->async.fn) {
186                         req->async.fn(req);
187                 }
188                 return;
189         }
190
191         req->replies[req->num_replies] = talloc_steal(req->replies, msg);
192         req->num_replies++;
193
194         if (msg->type != LDAP_TAG_SearchResultEntry &&
195             msg->type != LDAP_TAG_SearchResultReference) {
196                 /* currently only search results expect multiple
197                    replies */
198                 req->state = LDAP_REQUEST_DONE;
199                 DLIST_REMOVE(conn->pending, req);
200         }
201
202         if (req->async.fn) {
203                 req->async.fn(req);
204         }
205 }
206
207 static void ldap_connection_recv_done(struct tevent_req *subreq);
208
209 static void ldap_connection_recv_next(struct ldap_connection *conn)
210 {
211         struct tevent_req *subreq = NULL;
212
213         if (conn->sockets.recv_subreq != NULL) {
214                 return;
215         }
216
217         if (conn->sockets.active == NULL) {
218                 return;
219         }
220
221         if (conn->pending == NULL) {
222                 return;
223         }
224
225         /*
226          * The minimum size of a LDAP pdu is 7 bytes
227          *
228          * dumpasn1 -hh ldap-unbind-min.dat
229          *
230          *     <30 05 02 01 09 42 00>
231          *    0    5: SEQUENCE {
232          *     <02 01 09>
233          *    2    1:   INTEGER 9
234          *     <42 00>
235          *    5    0:   [APPLICATION 2]
236          *          :     Error: Object has zero length.
237          *          :   }
238          *
239          * dumpasn1 -hh ldap-unbind-windows.dat
240          *
241          *     <30 84 00 00 00 05 02 01 09 42 00>
242          *    0    5: SEQUENCE {
243          *     <02 01 09>
244          *    6    1:   INTEGER 9
245          *     <42 00>
246          *    9    0:   [APPLICATION 2]
247          *          :     Error: Object has zero length.
248          *          :   }
249          *
250          * This means using an initial read size
251          * of 7 is ok.
252          */
253         subreq = tstream_read_pdu_blob_send(conn,
254                                             conn->event.event_ctx,
255                                             conn->sockets.active,
256                                             7, /* initial_read_size */
257                                             ldap_full_packet,
258                                             conn);
259         if (subreq == NULL) {
260                 ldap_error_handler(conn, NT_STATUS_NO_MEMORY);
261                 return;
262         }
263         tevent_req_set_callback(subreq, ldap_connection_recv_done, conn);
264         conn->sockets.recv_subreq = subreq;
265         return;
266 }
267
268 /*
269   decode/process LDAP data
270 */
271 static void ldap_connection_recv_done(struct tevent_req *subreq)
272 {
273         NTSTATUS status;
274         struct ldap_connection *conn =
275                 tevent_req_callback_data(subreq,
276                 struct ldap_connection);
277         struct ldap_message *msg;
278         struct asn1_data *asn1;
279         DATA_BLOB blob;
280
281         msg = talloc_zero(conn, struct ldap_message);
282         if (msg == NULL) {
283                 ldap_error_handler(conn, NT_STATUS_NO_MEMORY);
284                 return;
285         }
286
287         asn1 = asn1_init(conn);
288         if (asn1 == NULL) {
289                 TALLOC_FREE(msg);
290                 ldap_error_handler(conn, NT_STATUS_NO_MEMORY);
291                 return;
292         }
293
294         conn->sockets.recv_subreq = NULL;
295
296         status = tstream_read_pdu_blob_recv(subreq,
297                                             asn1,
298                                             &blob);
299         TALLOC_FREE(subreq);
300         if (!NT_STATUS_IS_OK(status)) {
301                 TALLOC_FREE(msg);
302                 asn1_free(asn1);
303                 ldap_error_handler(conn, status);
304                 return;
305         }
306
307         asn1_load_nocopy(asn1, blob.data, blob.length);
308
309         status = ldap_decode(asn1, samba_ldap_control_handlers(), msg);
310         asn1_free(asn1);
311         if (!NT_STATUS_IS_OK(status)) {
312                 TALLOC_FREE(msg);
313                 ldap_error_handler(conn, status);
314                 return;
315         }
316
317         ldap_match_message(conn, msg);
318         ldap_connection_recv_next(conn);
319
320         return;
321 }
322
323 /*
324   parse a ldap URL
325 */
326 static NTSTATUS ldap_parse_basic_url(TALLOC_CTX *mem_ctx, const char *url,
327                                      char **host, uint16_t *port, bool *ldaps)
328 {
329         int tmp_port = 0;
330         char protocol[11];
331         char tmp_host[1025];
332         int ret;
333
334         /* Paranoia check */
335         SMB_ASSERT(sizeof(protocol)>10 && sizeof(tmp_host)>254);
336                 
337         ret = sscanf(url, "%10[^:]://%254[^:/]:%d", protocol, tmp_host, &tmp_port);
338         if (ret < 2) {
339                 return NT_STATUS_INVALID_PARAMETER;
340         }
341
342         if (strequal(protocol, "ldap")) {
343                 *port = 389;
344                 *ldaps = false;
345         } else if (strequal(protocol, "ldaps")) {
346                 *port = 636;
347                 *ldaps = true;
348         } else {
349                 DEBUG(0, ("unrecognised ldap protocol (%s)!\n", protocol));
350                 return NT_STATUS_PROTOCOL_UNREACHABLE;
351         }
352
353         if (tmp_port != 0)
354                 *port = tmp_port;
355
356         *host = talloc_strdup(mem_ctx, tmp_host);
357         NT_STATUS_HAVE_NO_MEMORY(*host);
358
359         return NT_STATUS_OK;
360 }
361
362 /*
363   connect to a ldap server
364 */
365
366 struct ldap_connect_state {
367         struct composite_context *ctx;
368         struct ldap_connection *conn;
369         struct socket_context *sock;
370         struct tstream_context *raw;
371         struct tstream_tls_params *tls_params;
372         struct tstream_context *tls;
373 };
374
375 static void ldap_connect_recv_unix_conn(struct composite_context *ctx);
376 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx);
377
378 _PUBLIC_ struct composite_context *ldap_connect_send(struct ldap_connection *conn,
379                                             const char *url)
380 {
381         struct composite_context *result, *ctx;
382         struct ldap_connect_state *state;
383         char protocol[11];
384         int ret;
385
386         result = talloc_zero(conn, struct composite_context);
387         if (result == NULL) goto failed;
388         result->state = COMPOSITE_STATE_IN_PROGRESS;
389         result->async.fn = NULL;
390         result->event_ctx = conn->event.event_ctx;
391
392         state = talloc(result, struct ldap_connect_state);
393         if (state == NULL) goto failed;
394         state->ctx = result;
395         result->private_data = state;
396
397         state->conn = conn;
398
399         if (conn->reconnect.url == NULL) {
400                 conn->reconnect.url = talloc_strdup(conn, url);
401                 if (conn->reconnect.url == NULL) goto failed;
402         }
403
404         /* Paranoia check */
405         SMB_ASSERT(sizeof(protocol)>10);
406
407         ret = sscanf(url, "%10[^:]://", protocol);
408         if (ret < 1) {
409                 return NULL;
410         }
411
412         if (strequal(protocol, "ldapi")) {
413                 struct socket_address *unix_addr;
414                 char path[1025];
415                 char *end = NULL;
416                 NTSTATUS status = socket_create(state, "unix",
417                                                 SOCKET_TYPE_STREAM,
418                                                 &state->sock, 0);
419                 if (!NT_STATUS_IS_OK(status)) {
420                         return NULL;
421                 }
422                 SMB_ASSERT(sizeof(protocol)>10);
423                 SMB_ASSERT(sizeof(path)>1024);
424         
425                 /* LDAPI connections are to localhost, so give the
426                  * local host name as the target for gensec's
427                  * DIGEST-MD5 mechanism */
428                 conn->host = talloc_asprintf(conn, "%s.%s",
429                                              lpcfg_netbios_name(conn->lp_ctx),
430                                              lpcfg_dnsdomain(conn->lp_ctx));
431                 if (composite_nomem(conn->host, state->ctx)) {
432                         return result;
433                 }
434
435                 /* The %c specifier doesn't null terminate :-( */
436                 ZERO_STRUCT(path);
437                 ret = sscanf(url, "%10[^:]://%1025c", protocol, path);
438                 if (ret < 2) {
439                         composite_error(state->ctx, NT_STATUS_INVALID_PARAMETER);
440                         return result;
441                 }
442
443                 end = rfc1738_unescape(path);
444                 if (end == NULL) {
445                         composite_error(state->ctx,
446                                         NT_STATUS_INVALID_PARAMETER);
447                         return result;
448                 }       
449                 unix_addr = socket_address_from_strings(state, state->sock->backend_name,
450                                                         path, 0);
451                 if (composite_nomem(unix_addr, result)) {
452                         return result;
453                 }
454
455                 ctx = socket_connect_send(state->sock, NULL, unix_addr,
456                                           0, result->event_ctx);
457                 ctx->async.fn = ldap_connect_recv_unix_conn;
458                 ctx->async.private_data = state;
459                 return result;
460         } else {
461                 NTSTATUS status = ldap_parse_basic_url(conn, url, &conn->host,
462                                                           &conn->port, &conn->ldaps);
463                 if (!NT_STATUS_IS_OK(status)) {
464                         composite_error(result, status);
465                         return result;
466                 }
467
468                 if (conn->ldaps) {
469                         char *ca_file = lpcfg_tls_cafile(state, conn->lp_ctx);
470                         char *crl_file = lpcfg_tls_crlfile(state, conn->lp_ctx);
471                         const char *tls_priority = lpcfg_tls_priority(conn->lp_ctx);
472                         enum tls_verify_peer_state verify_peer =
473                                 lpcfg_tls_verify_peer(conn->lp_ctx);
474
475                         status = tstream_tls_params_client(state,
476                                                            ca_file,
477                                                            crl_file,
478                                                            tls_priority,
479                                                            verify_peer,
480                                                            conn->host,
481                                                            &state->tls_params);
482                         if (!NT_STATUS_IS_OK(status)) {
483                                 composite_error(result, status);
484                                 return result;
485                         }
486                 }
487
488                 ctx = socket_connect_multi_send(state, conn->host, 1, &conn->port,
489                                                 lpcfg_resolve_context(conn->lp_ctx),
490                                                 result->event_ctx);
491                 if (composite_nomem(ctx, result)) {
492                         return result;
493                 }
494
495                 ctx->async.fn = ldap_connect_recv_tcp_conn;
496                 ctx->async.private_data = state;
497                 return result;
498         }
499  failed:
500         talloc_free(result);
501         return NULL;
502 }
503
504 static void ldap_connect_got_tls(struct tevent_req *subreq);
505
506 static void ldap_connect_got_sock(struct composite_context *ctx, 
507                                   struct ldap_connection *conn)
508 {
509         struct ldap_connect_state *state =
510                 talloc_get_type_abort(ctx->private_data,
511                 struct ldap_connect_state);
512         struct tevent_req *subreq = NULL;
513         int fd;
514         int ret;
515
516         socket_set_flags(state->sock, SOCKET_FLAG_NOCLOSE);
517         fd = socket_get_fd(state->sock);
518         TALLOC_FREE(state->sock);
519
520         smb_set_close_on_exec(fd);
521
522         ret = set_blocking(fd, false);
523         if (ret == -1) {
524                 NTSTATUS status = map_nt_error_from_unix_common(errno);
525                 composite_error(state->ctx, status);
526                 return;
527         }
528
529         ret = tstream_bsd_existing_socket(state, fd, &state->raw);
530         if (ret == -1) {
531                 NTSTATUS status = map_nt_error_from_unix_common(errno);
532                 composite_error(state->ctx, status);
533                 return;
534         }
535
536         if (!conn->ldaps) {
537                 conn->sockets.raw = talloc_move(conn, &state->raw);
538                 conn->sockets.active = conn->sockets.raw;
539                 composite_done(state->ctx);
540                 return;
541         }
542
543         subreq = tstream_tls_connect_send(state, state->ctx->event_ctx,
544                                           state->raw, state->tls_params);
545         if (composite_nomem(subreq, state->ctx)) {
546                 return;
547         }
548         tevent_req_set_callback(subreq, ldap_connect_got_tls, state);
549 }
550
551 static void ldap_connect_got_tls(struct tevent_req *subreq)
552 {
553         struct ldap_connect_state *state =
554                 tevent_req_callback_data(subreq,
555                 struct ldap_connect_state);
556         int err;
557         int ret;
558
559         ret = tstream_tls_connect_recv(subreq, &err, state, &state->tls);
560         TALLOC_FREE(subreq);
561         if (ret == -1) {
562                 NTSTATUS status = map_nt_error_from_unix_common(err);
563                 composite_error(state->ctx, status);
564                 return;
565         }
566
567         talloc_steal(state->tls, state->tls_params);
568
569         state->conn->sockets.raw = talloc_move(state->conn, &state->raw);
570         state->conn->sockets.tls = talloc_move(state->conn->sockets.raw,
571                                                &state->tls);
572         state->conn->sockets.active = state->conn->sockets.tls;
573         composite_done(state->ctx);
574 }
575
576 static void ldap_connect_recv_tcp_conn(struct composite_context *ctx)
577 {
578         struct ldap_connect_state *state =
579                 talloc_get_type_abort(ctx->async.private_data,
580                 struct ldap_connect_state);
581         struct ldap_connection *conn = state->conn;
582         uint16_t port;
583         NTSTATUS status = socket_connect_multi_recv(ctx, state, &state->sock,
584                                                        &port);
585         if (!NT_STATUS_IS_OK(status)) {
586                 composite_error(state->ctx, status);
587                 return;
588         }
589
590         ldap_connect_got_sock(state->ctx, conn);
591 }
592
593 static void ldap_connect_recv_unix_conn(struct composite_context *ctx)
594 {
595         struct ldap_connect_state *state =
596                 talloc_get_type_abort(ctx->async.private_data,
597                 struct ldap_connect_state);
598         struct ldap_connection *conn = state->conn;
599
600         NTSTATUS status = socket_connect_recv(ctx);
601
602         if (!NT_STATUS_IS_OK(state->ctx->status)) {
603                 composite_error(state->ctx, status);
604                 return;
605         }
606
607         ldap_connect_got_sock(state->ctx, conn);
608 }
609
610 _PUBLIC_ NTSTATUS ldap_connect_recv(struct composite_context *ctx)
611 {
612         NTSTATUS status = composite_wait(ctx);
613         talloc_free(ctx);
614         return status;
615 }
616
617 _PUBLIC_ NTSTATUS ldap_connect(struct ldap_connection *conn, const char *url)
618 {
619         struct composite_context *ctx = ldap_connect_send(conn, url);
620         return ldap_connect_recv(ctx);
621 }
622
623 /* set reconnect parameters */
624
625 _PUBLIC_ void ldap_set_reconn_params(struct ldap_connection *conn, int max_retries)
626 {
627         if (conn) {
628                 conn->reconnect.max_retries = max_retries;
629                 conn->reconnect.retries = 0;
630                 conn->reconnect.previous = time_mono(NULL);
631         }
632 }
633
634 /* Actually this function is NOT ASYNC safe, FIXME? */
635 static void ldap_reconnect(struct ldap_connection *conn)
636 {
637         NTSTATUS status;
638         time_t now = time_mono(NULL);
639
640         /* do we have set up reconnect ? */
641         if (conn->reconnect.max_retries == 0) return;
642
643         /* is the retry time expired ? */
644         if (now > conn->reconnect.previous + 30) {
645                 conn->reconnect.retries = 0;
646                 conn->reconnect.previous = now;
647         }
648
649         /* are we reconnectind too often and too fast? */
650         if (conn->reconnect.retries > conn->reconnect.max_retries) return;
651
652         /* keep track of the number of reconnections */
653         conn->reconnect.retries++;
654
655         /* reconnect */
656         status = ldap_connect(conn, conn->reconnect.url);
657         if ( ! NT_STATUS_IS_OK(status)) {
658                 return;
659         }
660
661         /* rebind */
662         status = ldap_rebind(conn);
663         if ( ! NT_STATUS_IS_OK(status)) {
664                 ldap_connection_dead(conn, status);
665         }
666 }
667
668 static void ldap_request_destructor_abandon(struct ldap_request *abandon)
669 {
670         TALLOC_FREE(abandon);
671 }
672
673 /* destroy an open ldap request */
674 static int ldap_request_destructor(struct ldap_request *req)
675 {
676         if (req->state == LDAP_REQUEST_PENDING) {
677                 struct ldap_message msg = {
678                         .type = LDAP_TAG_AbandonRequest,
679                         .r.AbandonRequest.messageid = req->messageid,
680                 };
681                 struct ldap_request *abandon = NULL;
682
683                 DLIST_REMOVE(req->conn->pending, req);
684
685                 abandon = ldap_request_send(req->conn, &msg);
686                 if (abandon == NULL) {
687                         ldap_error_handler(req->conn, NT_STATUS_NO_MEMORY);
688                         return 0;
689                 }
690                 abandon->async.fn = ldap_request_destructor_abandon;
691                 abandon->async.private_data = NULL;
692         }
693
694         return 0;
695 }
696
697 static void ldap_request_timeout_abandon(struct ldap_request *abandon)
698 {
699         struct ldap_request *req =
700                 talloc_get_type_abort(abandon->async.private_data,
701                 struct ldap_request);
702
703         if (req->state == LDAP_REQUEST_PENDING) {
704                 DLIST_REMOVE(req->conn->pending, req);
705         }
706         req->state = LDAP_REQUEST_DONE;
707         if (req->async.fn) {
708                 req->async.fn(req);
709         }
710 }
711
712 /*
713   called on timeout of a ldap request
714 */
715 static void ldap_request_timeout(struct tevent_context *ev, struct tevent_timer *te, 
716                                       struct timeval t, void *private_data)
717 {
718         struct ldap_request *req =
719                 talloc_get_type_abort(private_data,
720                 struct ldap_request);
721
722         req->status = NT_STATUS_IO_TIMEOUT;
723         if (req->state == LDAP_REQUEST_PENDING) {
724                 struct ldap_message msg = {
725                         .type = LDAP_TAG_AbandonRequest,
726                         .r.AbandonRequest.messageid = req->messageid,
727                 };
728                 struct ldap_request *abandon = NULL;
729
730                 abandon = ldap_request_send(req->conn, &msg);
731                 if (abandon == NULL) {
732                         ldap_error_handler(req->conn, NT_STATUS_NO_MEMORY);
733                         return;
734                 }
735                 talloc_reparent(req->conn, req, abandon);
736                 abandon->async.fn = ldap_request_timeout_abandon;
737                 abandon->async.private_data = req;
738                 DLIST_REMOVE(req->conn->pending, req);
739                 return;
740         }
741         req->state = LDAP_REQUEST_DONE;
742         if (req->async.fn) {
743                 req->async.fn(req);
744         }
745 }
746
747
748 /*
749   called on completion of a failed ldap request
750 */
751 static void ldap_request_failed_complete(struct tevent_context *ev, struct tevent_timer *te,
752                                       struct timeval t, void *private_data)
753 {
754         struct ldap_request *req =
755                 talloc_get_type_abort(private_data,
756                 struct ldap_request);
757
758         if (req->async.fn) {
759                 req->async.fn(req);
760         }
761 }
762
763 static void ldap_request_written(struct tevent_req *subreq);
764
765 /*
766   send a ldap message - async interface
767 */
768 _PUBLIC_ struct ldap_request *ldap_request_send(struct ldap_connection *conn,
769                                        struct ldap_message *msg)
770 {
771         struct ldap_request *req;
772         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
773         struct tevent_req *subreq = NULL;
774
775         req = talloc_zero(conn, struct ldap_request);
776         if (req == NULL) return NULL;
777
778         if (conn->sockets.active == NULL) {
779                 status = NT_STATUS_INVALID_CONNECTION;
780                 goto failed;
781         }
782
783         req->state       = LDAP_REQUEST_SEND;
784         req->conn        = conn;
785         req->messageid   = conn->next_messageid++;
786         if (conn->next_messageid == 0) {
787                 conn->next_messageid = 1;
788         }
789         req->type        = msg->type;
790         if (req->messageid == -1) {
791                 goto failed;
792         }
793
794         talloc_set_destructor(req, ldap_request_destructor);
795
796         msg->messageid = req->messageid;
797
798         if (!ldap_encode(msg, samba_ldap_control_handlers(), &req->data, req)) {
799                 status = NT_STATUS_INTERNAL_ERROR;
800                 goto failed;            
801         }
802
803         /* put a timeout on the request */
804         req->time_event = tevent_add_timer(conn->event.event_ctx, req,
805                                            timeval_current_ofs(conn->timeout, 0),
806                                            ldap_request_timeout, req);
807         if (req->time_event == NULL) {
808                 status = NT_STATUS_NO_MEMORY;
809                 goto failed;
810         }
811
812         req->write_iov.iov_base = req->data.data;
813         req->write_iov.iov_len = req->data.length;
814
815         subreq = tstream_writev_queue_send(req, conn->event.event_ctx,
816                                            conn->sockets.active,
817                                            conn->sockets.send_queue,
818                                            &req->write_iov, 1);
819         if (subreq == NULL) {
820                 status = NT_STATUS_NO_MEMORY;
821                 goto failed;
822         }
823         tevent_req_set_callback(subreq, ldap_request_written, req);
824
825         req->state = LDAP_REQUEST_PENDING;
826         DLIST_ADD(conn->pending, req);
827
828         return req;
829
830 failed:
831         req->status = status;
832         req->state = LDAP_REQUEST_ERROR;
833         tevent_add_timer(conn->event.event_ctx, req, timeval_zero(),
834                          ldap_request_failed_complete, req);
835
836         return req;
837 }
838
839 static void ldap_request_written(struct tevent_req *subreq)
840 {
841         struct ldap_request *req =
842                 tevent_req_callback_data(subreq,
843                 struct ldap_request);
844         int err;
845         ssize_t ret;
846
847         ret = tstream_writev_queue_recv(subreq, &err);
848         TALLOC_FREE(subreq);
849         if (ret == -1) {
850                 NTSTATUS error = map_nt_error_from_unix_common(err);
851                 ldap_error_handler(req->conn, error);
852                 return;
853         }
854
855         if (req->type == LDAP_TAG_AbandonRequest ||
856             req->type == LDAP_TAG_UnbindRequest)
857         {
858                 if (req->state == LDAP_REQUEST_PENDING) {
859                         DLIST_REMOVE(req->conn->pending, req);
860                 }
861                 req->state = LDAP_REQUEST_DONE;
862                 if (req->async.fn) {
863                         req->async.fn(req);
864                 }
865                 return;
866         }
867
868         ldap_connection_recv_next(req->conn);
869 }
870
871
872 /*
873   wait for a request to complete
874   note that this does not destroy the request
875 */
876 _PUBLIC_ NTSTATUS ldap_request_wait(struct ldap_request *req)
877 {
878         while (req->state < LDAP_REQUEST_DONE) {
879                 if (tevent_loop_once(req->conn->event.event_ctx) != 0) {
880                         req->state = LDAP_REQUEST_ERROR;
881                         req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
882                         break;
883                 }
884         }
885         return req->status;
886 }
887
888
889 /*
890   a mapping of ldap response code to strings
891 */
892 static const struct {
893         enum ldap_result_code code;
894         const char *str;
895 } ldap_code_map[] = {
896 #define _LDAP_MAP_CODE(c) { c, #c }
897         _LDAP_MAP_CODE(LDAP_SUCCESS),
898         _LDAP_MAP_CODE(LDAP_OPERATIONS_ERROR),
899         _LDAP_MAP_CODE(LDAP_PROTOCOL_ERROR),
900         _LDAP_MAP_CODE(LDAP_TIME_LIMIT_EXCEEDED),
901         _LDAP_MAP_CODE(LDAP_SIZE_LIMIT_EXCEEDED),
902         _LDAP_MAP_CODE(LDAP_COMPARE_FALSE),
903         _LDAP_MAP_CODE(LDAP_COMPARE_TRUE),
904         _LDAP_MAP_CODE(LDAP_AUTH_METHOD_NOT_SUPPORTED),
905         _LDAP_MAP_CODE(LDAP_STRONG_AUTH_REQUIRED),
906         _LDAP_MAP_CODE(LDAP_REFERRAL),
907         _LDAP_MAP_CODE(LDAP_ADMIN_LIMIT_EXCEEDED),
908         _LDAP_MAP_CODE(LDAP_UNAVAILABLE_CRITICAL_EXTENSION),
909         _LDAP_MAP_CODE(LDAP_CONFIDENTIALITY_REQUIRED),
910         _LDAP_MAP_CODE(LDAP_SASL_BIND_IN_PROGRESS),
911         _LDAP_MAP_CODE(LDAP_NO_SUCH_ATTRIBUTE),
912         _LDAP_MAP_CODE(LDAP_UNDEFINED_ATTRIBUTE_TYPE),
913         _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_MATCHING),
914         _LDAP_MAP_CODE(LDAP_CONSTRAINT_VIOLATION),
915         _LDAP_MAP_CODE(LDAP_ATTRIBUTE_OR_VALUE_EXISTS),
916         _LDAP_MAP_CODE(LDAP_INVALID_ATTRIBUTE_SYNTAX),
917         _LDAP_MAP_CODE(LDAP_NO_SUCH_OBJECT),
918         _LDAP_MAP_CODE(LDAP_ALIAS_PROBLEM),
919         _LDAP_MAP_CODE(LDAP_INVALID_DN_SYNTAX),
920         _LDAP_MAP_CODE(LDAP_ALIAS_DEREFERENCING_PROBLEM),
921         _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_AUTHENTICATION),
922         _LDAP_MAP_CODE(LDAP_INVALID_CREDENTIALS),
923         _LDAP_MAP_CODE(LDAP_INSUFFICIENT_ACCESS_RIGHTS),
924         _LDAP_MAP_CODE(LDAP_BUSY),
925         _LDAP_MAP_CODE(LDAP_UNAVAILABLE),
926         _LDAP_MAP_CODE(LDAP_UNWILLING_TO_PERFORM),
927         _LDAP_MAP_CODE(LDAP_LOOP_DETECT),
928         _LDAP_MAP_CODE(LDAP_NAMING_VIOLATION),
929         _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_VIOLATION),
930         _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_NON_LEAF),
931         _LDAP_MAP_CODE(LDAP_NOT_ALLOWED_ON_RDN),
932         _LDAP_MAP_CODE(LDAP_ENTRY_ALREADY_EXISTS),
933         _LDAP_MAP_CODE(LDAP_OBJECT_CLASS_MODS_PROHIBITED),
934         _LDAP_MAP_CODE(LDAP_AFFECTS_MULTIPLE_DSAS),
935         _LDAP_MAP_CODE(LDAP_OTHER)
936 };
937
938 /*
939   used to setup the status code from a ldap response
940 */
941 _PUBLIC_ NTSTATUS ldap_check_response(struct ldap_connection *conn, struct ldap_Result *r)
942 {
943         int i;
944         const char *codename = "unknown";
945
946         if (r->resultcode == LDAP_SUCCESS) {
947                 return NT_STATUS_OK;
948         }
949
950         if (conn->last_error) {
951                 talloc_free(conn->last_error);
952         }
953
954         for (i=0;i<ARRAY_SIZE(ldap_code_map);i++) {
955                 if (r->resultcode == ldap_code_map[i].code) {
956                         codename = ldap_code_map[i].str;
957                         break;
958                 }
959         }
960
961         conn->last_error = talloc_asprintf(conn, "LDAP error %u %s - %s <%s> <%s>", 
962                                            r->resultcode,
963                                            codename,
964                                            r->dn?r->dn:"(NULL)", 
965                                            r->errormessage?r->errormessage:"", 
966                                            r->referral?r->referral:"");
967         
968         return NT_STATUS_LDAP(r->resultcode);
969 }
970
971 /*
972   return error string representing the last error
973 */
974 _PUBLIC_ const char *ldap_errstr(struct ldap_connection *conn, 
975                         TALLOC_CTX *mem_ctx, 
976                         NTSTATUS status)
977 {
978         if (NT_STATUS_IS_LDAP(status) && conn->last_error != NULL) {
979                 return talloc_strdup(mem_ctx, conn->last_error);
980         }
981         return talloc_asprintf(mem_ctx, "LDAP client internal error: %s", nt_errstr(status));
982 }
983
984
985 /*
986   return the Nth result message, waiting if necessary
987 */
988 _PUBLIC_ NTSTATUS ldap_result_n(struct ldap_request *req, int n, struct ldap_message **msg)
989 {
990         *msg = NULL;
991
992         NT_STATUS_HAVE_NO_MEMORY(req);
993
994         while (req->state < LDAP_REQUEST_DONE && n >= req->num_replies) {
995                 if (tevent_loop_once(req->conn->event.event_ctx) != 0) {
996                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
997                 }
998         }
999
1000         if (n < req->num_replies) {
1001                 *msg = req->replies[n];
1002                 return NT_STATUS_OK;
1003         }
1004
1005         if (!NT_STATUS_IS_OK(req->status)) {
1006                 return req->status;
1007         }
1008
1009         return NT_STATUS_NO_MORE_ENTRIES;
1010 }
1011
1012
1013 /*
1014   return a single result message, checking if it is of the expected LDAP type
1015 */
1016 _PUBLIC_ NTSTATUS ldap_result_one(struct ldap_request *req, struct ldap_message **msg, int type)
1017 {
1018         NTSTATUS status;
1019         status = ldap_result_n(req, 0, msg);
1020         if (!NT_STATUS_IS_OK(status)) {
1021                 return status;
1022         }
1023         if ((*msg)->type != type) {
1024                 *msg = NULL;
1025                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
1026         }
1027         return status;
1028 }
1029
1030 /*
1031   a simple ldap transaction, for single result requests that only need a status code
1032   this relies on single valued requests having the response type == request type + 1
1033 */
1034 _PUBLIC_ NTSTATUS ldap_transaction(struct ldap_connection *conn, struct ldap_message *msg)
1035 {
1036         struct ldap_request *req = ldap_request_send(conn, msg);
1037         struct ldap_message *res;
1038         NTSTATUS status;
1039         status = ldap_result_n(req, 0, &res);
1040         if (!NT_STATUS_IS_OK(status)) {
1041                 talloc_free(req);
1042                 return status;
1043         }
1044         if (res->type != msg->type + 1) {
1045                 talloc_free(req);
1046                 return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
1047         }
1048         status = ldap_check_response(conn, &res->r.GeneralResult);
1049         talloc_free(req);
1050         return status;
1051 }