r7230: use socket_pending() to get rid of the max packet size limits in the
[kai/samba.git] / source4 / libcli / cldap / cldap.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    cldap client library
5
6    Copyright (C) Andrew Tridgell 2005
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 /*
24   see RFC1798 for details of CLDAP
25
26   basic properties
27     - carried over UDP on port 389
28     - request and response matched by message ID
29     - request consists of only a single searchRequest element
30     - response can be in one of two forms
31        - a single searchResponse, followed by a searchResult
32        - a single searchResult
33 */
34
35 #include "includes.h"
36 #include "lib/events/events.h"
37 #include "dlinklist.h"
38 #include "libcli/ldap/ldap.h"
39 #include "libcli/cldap/cldap.h"
40 #include "lib/socket/socket.h"
41 #include "include/asn_1.h"
42
43 /*
44   destroy a pending request
45 */
46 static int cldap_request_destructor(void *ptr)
47 {
48         struct cldap_request *req = talloc_get_type(ptr, struct cldap_request);
49         if (req->state == CLDAP_REQUEST_SEND) {
50                 DLIST_REMOVE(req->cldap->send_queue, req);
51         }
52         if (!req->is_reply && req->message_id != 0) {
53                 idr_remove(req->cldap->idr, req->message_id);
54                 req->message_id = 0;
55         }
56         return 0;
57 }
58
59 /*
60   handle recv events on a cldap socket
61 */
62 static void cldap_socket_recv(struct cldap_socket *cldap)
63 {
64         TALLOC_CTX *tmp_ctx = talloc_new(cldap);
65         NTSTATUS status;
66         const char *src_addr;
67         int src_port;
68         DATA_BLOB blob;
69         size_t nread, dsize;
70         struct asn1_data asn1;
71         struct ldap_message ldap_msg;
72         struct cldap_request *req;
73
74         status = socket_pending(cldap->sock, &dsize);
75         if (!NT_STATUS_IS_OK(status)) {
76                 talloc_free(tmp_ctx);
77                 return;
78         }
79
80         blob = data_blob_talloc(tmp_ctx, NULL, dsize);
81         if (blob.data == NULL) {
82                 talloc_free(tmp_ctx);
83                 return;
84         }
85
86         status = socket_recvfrom(cldap->sock, blob.data, blob.length, &nread, 0,
87                                  &src_addr, &src_port);
88         if (!NT_STATUS_IS_OK(status)) {
89                 talloc_free(tmp_ctx);
90                 return;
91         }
92         talloc_steal(tmp_ctx, src_addr);
93         blob.length = nread;
94
95         DEBUG(2,("Received cldap packet of length %d from %s:%d\n", 
96                  blob.length, src_addr, src_port));
97
98         if (!asn1_load(&asn1, blob)) {
99                 DEBUG(2,("Failed to setup for asn.1 decode\n"));
100                 talloc_free(tmp_ctx);
101                 return;
102         }
103         talloc_steal(tmp_ctx, asn1.data);
104
105         ZERO_STRUCT(ldap_msg);
106         ldap_msg.mem_ctx = tmp_ctx;
107
108         /* this initial decode is used to find the message id */
109         if (!ldap_decode(&asn1, &ldap_msg)) {
110                 DEBUG(2,("Failed to decode ldap message\n"));
111                 talloc_free(tmp_ctx);
112                 return;
113         }
114
115         /* find the pending request */
116         req = idr_find(cldap->idr, ldap_msg.messageid);
117         if (req == NULL) {
118                 if (cldap->incoming.handler) {
119                         cldap->incoming.handler(cldap, &ldap_msg, src_addr, src_port);
120                 } else {
121                         DEBUG(2,("Mismatched cldap reply %u from %s:%d\n",
122                                  ldap_msg.messageid, src_addr, src_port));
123                 }
124                 talloc_free(tmp_ctx);
125                 return;
126         }
127
128         req->asn1 = asn1;
129         talloc_steal(req, asn1.data);
130         req->asn1.ofs = 0;
131
132         req->state = CLDAP_REQUEST_DONE;
133         talloc_free(req->te);
134
135         talloc_free(tmp_ctx);
136
137         if (req->async.fn) {
138                 req->async.fn(req);
139         }
140 }
141
142 /*
143   handle request timeouts
144 */
145 static void cldap_request_timeout(struct event_context *event_ctx, 
146                                   struct timed_event *te, struct timeval t,
147                                   void *private)
148 {
149         struct cldap_request *req = talloc_get_type(private, struct cldap_request);
150
151         /* possibly try again */
152         if (req->num_retries != 0) {
153                 size_t len = req->encoded.length;
154
155                 req->num_retries--;
156
157                 socket_sendto(req->cldap->sock, &req->encoded, &len, 0, 
158                               req->dest_addr, req->dest_port);
159
160                 req->te = event_add_timed(req->cldap->event_ctx, req, 
161                                           timeval_current_ofs(req->timeout, 0),
162                                           cldap_request_timeout, req);
163                 return;
164         }
165
166         req->state = CLDAP_REQUEST_TIMEOUT;
167         if (req->async.fn) {
168                 req->async.fn(req);
169         }
170 }
171
172 /*
173   handle send events on a cldap socket
174 */
175 static void cldap_socket_send(struct cldap_socket *cldap)
176 {
177         struct cldap_request *req;
178         NTSTATUS status;
179
180         while ((req = cldap->send_queue)) {
181                 size_t len;
182                 
183                 len = req->encoded.length;
184                 status = socket_sendto(cldap->sock, &req->encoded, &len, 0, 
185                                        req->dest_addr, req->dest_port);
186                 if (NT_STATUS_IS_ERR(status)) {
187                         DEBUG(3,("Failed to send cldap request of length %u to %s:%d\n",
188                                  req->encoded.length, req->dest_addr, req->dest_port));
189                         DLIST_REMOVE(cldap->send_queue, req);
190                         talloc_free(req);
191                         continue;
192                 }
193
194                 if (!NT_STATUS_IS_OK(status)) return;
195
196                 DLIST_REMOVE(cldap->send_queue, req);
197
198                 if (req->is_reply) {
199                         talloc_free(req);
200                 } else {
201                         req->state = CLDAP_REQUEST_WAIT;
202
203                         req->te = event_add_timed(cldap->event_ctx, req, 
204                                                   timeval_current_ofs(req->timeout, 0),
205                                                   cldap_request_timeout, req);
206
207                         EVENT_FD_READABLE(cldap->fde);
208                 }
209         }
210
211         EVENT_FD_NOT_WRITEABLE(cldap->fde);
212         return;
213 }
214
215
216 /*
217   handle fd events on a cldap_socket
218 */
219 static void cldap_socket_handler(struct event_context *ev, struct fd_event *fde,
220                                  uint16_t flags, void *private)
221 {
222         struct cldap_socket *cldap = talloc_get_type(private, struct cldap_socket);
223         if (flags & EVENT_FD_WRITE) {
224                 cldap_socket_send(cldap);
225         } else if (flags & EVENT_FD_READ) {
226                 cldap_socket_recv(cldap);
227         }
228 }
229
230 /*
231   initialise a cldap_socket. The event_ctx is optional, if provided
232   then operations will use that event context
233 */
234 struct cldap_socket *cldap_socket_init(TALLOC_CTX *mem_ctx, 
235                                        struct event_context *event_ctx)
236 {
237         struct cldap_socket *cldap;
238         NTSTATUS status;
239
240         cldap = talloc(mem_ctx, struct cldap_socket);
241         if (cldap == NULL) goto failed;
242
243         if (event_ctx == NULL) {
244                 cldap->event_ctx = event_context_init(cldap);
245         } else {
246                 cldap->event_ctx = talloc_reference(cldap, event_ctx);
247         }
248         if (cldap->event_ctx == NULL) goto failed;
249
250         cldap->idr = idr_init(cldap);
251         if (cldap->idr == NULL) goto failed;
252
253         status = socket_create("ip", SOCKET_TYPE_DGRAM, &cldap->sock, 0);
254         if (!NT_STATUS_IS_OK(status)) goto failed;
255
256         talloc_steal(cldap, cldap->sock);
257
258         cldap->fde = event_add_fd(cldap->event_ctx, cldap, 
259                                       socket_get_fd(cldap->sock), 0,
260                                       cldap_socket_handler, cldap);
261
262         cldap->send_queue = NULL;
263         cldap->incoming.handler = NULL;
264         
265         return cldap;
266
267 failed:
268         talloc_free(cldap);
269         return NULL;
270 }
271
272
273 /*
274   setup a handler for incoming requests
275 */
276 NTSTATUS cldap_set_incoming_handler(struct cldap_socket *cldap,
277                                   void (*handler)(struct cldap_socket *, struct ldap_message *, 
278                                                   const char *, int ),
279                                   void *private)
280 {
281         cldap->incoming.handler = handler;
282         cldap->incoming.private = private;
283         EVENT_FD_READABLE(cldap->fde);
284         return NT_STATUS_OK;
285 }
286
287 /*
288   queue a cldap request for send
289 */
290 struct cldap_request *cldap_search_send(struct cldap_socket *cldap, 
291                                         struct cldap_search *io)
292 {
293         struct ldap_message msg;
294         struct cldap_request *req;
295         struct ldap_SearchRequest *search;
296
297         req = talloc_zero(cldap, struct cldap_request);
298         if (req == NULL) goto failed;
299
300         req->cldap       = cldap;
301         req->state       = CLDAP_REQUEST_SEND;
302         req->timeout     = io->in.timeout;
303         req->num_retries = io->in.retries;
304         req->is_reply    = False;
305
306         req->dest_addr = talloc_strdup(req, io->in.dest_address);
307         if (req->dest_addr == NULL) goto failed;
308         req->dest_port = lp_cldap_port();
309
310         req->message_id = idr_get_new_random(cldap->idr, req, UINT16_MAX);
311         if (req->message_id == -1) goto failed;
312
313         talloc_set_destructor(req, cldap_request_destructor);
314
315         msg.mem_ctx         = req;
316         msg.messageid       = req->message_id;
317         msg.type            = LDAP_TAG_SearchRequest;
318         msg.num_controls    = 0;
319         msg.controls        = NULL;
320         search = &msg.r.SearchRequest;
321
322         search->basedn         = "";
323         search->scope          = LDAP_SEARCH_SCOPE_BASE;
324         search->deref          = LDAP_DEREFERENCE_NEVER;
325         search->timelimit      = 0;
326         search->sizelimit      = 0;
327         search->attributesonly = False;
328         search->num_attributes = str_list_length(io->in.attributes);
329         search->attributes     = io->in.attributes;
330         search->filter         = io->in.filter;
331
332         if (!ldap_encode(&msg, &req->encoded)) {
333                 DEBUG(0,("Failed to encode cldap message to %s:%d\n",
334                          req->dest_addr, req->dest_port));
335                 goto failed;
336         }
337         talloc_steal(req, req->encoded.data);
338
339         DLIST_ADD_END(cldap->send_queue, req, struct cldap_request *);
340
341         EVENT_FD_WRITEABLE(cldap->fde);
342
343         return req;
344
345 failed:
346         talloc_free(req);
347         return NULL;
348 }
349
350
351 /*
352   queue a cldap reply for send
353 */
354 NTSTATUS cldap_reply_send(struct cldap_socket *cldap, struct cldap_reply *io)
355 {
356         struct ldap_message msg;
357         struct cldap_request *req;
358         DATA_BLOB blob1, blob2;
359         NTSTATUS status = NT_STATUS_NO_MEMORY;
360
361         req = talloc_zero(cldap, struct cldap_request);
362         if (req == NULL) goto failed;
363
364         req->cldap       = cldap;
365         req->state       = CLDAP_REQUEST_SEND;
366         req->is_reply    = True;
367
368         req->dest_addr = talloc_strdup(req, io->dest_address);
369         if (req->dest_addr == NULL) goto failed;
370         req->dest_port = io->dest_port;
371
372         talloc_set_destructor(req, cldap_request_destructor);
373
374         msg.mem_ctx         = req;
375         msg.messageid       = io->messageid;
376         msg.num_controls    = 0;
377         msg.controls        = NULL;
378         
379         if (io->response) {
380                 msg.type = LDAP_TAG_SearchResultEntry;
381                 msg.r.SearchResultEntry = *io->response;
382
383                 if (!ldap_encode(&msg, &blob1)) {
384                         DEBUG(0,("Failed to encode cldap message to %s:%d\n",
385                                  req->dest_addr, req->dest_port));
386                         status = NT_STATUS_INVALID_PARAMETER;
387                         goto failed;
388                 }
389                 talloc_steal(req, blob1.data);
390         } else {
391                 blob1 = data_blob(NULL, 0);
392         }
393
394         msg.type = LDAP_TAG_SearchResultDone;
395         msg.r.SearchResultDone = *io->result;
396
397         if (!ldap_encode(&msg, &blob2)) {
398                 DEBUG(0,("Failed to encode cldap message to %s:%d\n",
399                          req->dest_addr, req->dest_port));
400                 status = NT_STATUS_INVALID_PARAMETER;
401                 goto failed;
402         }
403         talloc_steal(req, blob2.data);
404
405         req->encoded = data_blob_talloc(req, NULL, blob1.length + blob2.length);
406         if (req->encoded.data == NULL) goto failed;
407
408         memcpy(req->encoded.data, blob1.data, blob1.length);
409         memcpy(req->encoded.data+blob1.length, blob2.data, blob2.length);
410
411         DLIST_ADD_END(cldap->send_queue, req, struct cldap_request *);
412
413         EVENT_FD_WRITEABLE(cldap->fde);
414
415         return NT_STATUS_OK;
416
417 failed:
418         talloc_free(req);
419         return status;
420 }
421
422 /*
423   receive a cldap reply
424 */
425 NTSTATUS cldap_search_recv(struct cldap_request *req, 
426                            TALLOC_CTX *mem_ctx, 
427                            struct cldap_search *io)
428 {
429         struct ldap_message ldap_msg;
430
431         if (req == NULL) {
432                 return NT_STATUS_NO_MEMORY;
433         }
434
435         while (req->state < CLDAP_REQUEST_DONE) {
436                 if (event_loop_once(req->cldap->event_ctx) != 0) {
437                         talloc_free(req);
438                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
439                 }
440         }
441
442         if (req->state == CLDAP_REQUEST_TIMEOUT) {
443                 talloc_free(req);
444                 return NT_STATUS_IO_TIMEOUT;
445         }
446
447         ZERO_STRUCT(ldap_msg);
448         ldap_msg.mem_ctx = mem_ctx;
449
450         if (!ldap_decode(&req->asn1, &ldap_msg)) {
451                 talloc_free(req);
452                 return NT_STATUS_INVALID_PARAMETER;
453         }
454
455         ZERO_STRUCT(io->out);
456
457         /* the first possible form has a search result in first place */
458         if (ldap_msg.type == LDAP_TAG_SearchResultEntry) {
459                 io->out.response = talloc(mem_ctx, struct ldap_SearchResEntry);
460                 NT_STATUS_HAVE_NO_MEMORY(io->out.response);
461                 *io->out.response = ldap_msg.r.SearchResultEntry;
462
463                 /* decode the 2nd part */
464                 if (!ldap_decode(&req->asn1, &ldap_msg)) {
465                         talloc_free(req);
466                         return NT_STATUS_INVALID_PARAMETER;
467                 }
468         }
469
470         if (ldap_msg.type != LDAP_TAG_SearchResultDone) {
471                 talloc_free(req);
472                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
473         }
474
475         io->out.result = talloc(mem_ctx, struct ldap_Result);
476         NT_STATUS_HAVE_NO_MEMORY(io->out.result);
477         *io->out.result = ldap_msg.r.SearchResultDone;
478
479         talloc_free(req);
480         return NT_STATUS_OK;
481 }
482
483
484 /*
485   synchronous cldap search
486 */
487 NTSTATUS cldap_search(struct cldap_socket *cldap, 
488                       TALLOC_CTX *mem_ctx, 
489                       struct cldap_search *io)
490 {
491         struct cldap_request *req = cldap_search_send(cldap, io);
492         return cldap_search_recv(req, mem_ctx, io);
493 }
494
495
496
497 /*
498   queue a cldap netlogon for send
499 */
500 struct cldap_request *cldap_netlogon_send(struct cldap_socket *cldap, 
501                                           struct cldap_netlogon *io)
502 {
503         struct cldap_search search;
504         char *filter;
505         struct cldap_request *req;
506         const char *attr[] = { "NetLogon", NULL };
507         TALLOC_CTX *tmp_ctx = talloc_new(cldap);
508
509         filter = talloc_asprintf(tmp_ctx, "(&(NtVer=%s)", 
510                                  ldap_encode_ndr_uint32(tmp_ctx, io->in.version));
511         if (filter == NULL) goto failed;
512         if (io->in.user) {
513                 filter = talloc_asprintf_append(filter, "(User=%s)", io->in.user);
514                 if (filter == NULL) goto failed;
515         }
516         if (io->in.host) {
517                 filter = talloc_asprintf_append(filter, "(Host=%s)", io->in.host);
518                 if (filter == NULL) goto failed;
519         }
520         if (io->in.realm) {
521                 filter = talloc_asprintf_append(filter, "(DnsDomain=%s)", io->in.realm);
522                 if (filter == NULL) goto failed;
523         }
524         if (io->in.acct_control != -1) {
525                 filter = talloc_asprintf_append(filter, "(AAC=%s)", 
526                                                 ldap_encode_ndr_uint32(tmp_ctx, io->in.acct_control));
527                 if (filter == NULL) goto failed;
528         }
529         if (io->in.domain_sid) {
530                 struct dom_sid *sid = dom_sid_parse_talloc(tmp_ctx, io->in.domain_sid);
531                 if (sid == NULL) goto failed;
532                 filter = talloc_asprintf_append(filter, "(domainSid=%s)",
533                                                 ldap_encode_ndr_dom_sid(tmp_ctx, sid));
534                 if (filter == NULL) goto failed;
535         }
536         if (io->in.domain_guid) {
537                 struct GUID guid;
538                 NTSTATUS status;
539                 status = GUID_from_string(io->in.domain_guid, &guid);
540                 if (!NT_STATUS_IS_OK(status)) goto failed;
541                 filter = talloc_asprintf_append(filter, "(DomainGuid=%s)",
542                                                 ldap_encode_ndr_GUID(tmp_ctx, &guid));
543                 if (filter == NULL) goto failed;
544         }
545         filter = talloc_asprintf_append(filter, ")");
546         if (filter == NULL) goto failed;
547
548         search.in.dest_address = io->in.dest_address;
549         search.in.filter       = filter;
550         search.in.attributes   = attr;
551         search.in.timeout      = 2;
552         search.in.retries      = 2;
553
554         req = cldap_search_send(cldap, &search);
555
556         talloc_free(tmp_ctx);
557         return req;
558 failed:
559         talloc_free(tmp_ctx);
560         return NULL;
561 }
562
563
564 /*
565   receive a cldap netlogon reply
566 */
567 NTSTATUS cldap_netlogon_recv(struct cldap_request *req, 
568                              TALLOC_CTX *mem_ctx, 
569                              struct cldap_netlogon *io)
570 {
571         NTSTATUS status;
572         struct cldap_search search;
573         DATA_BLOB *data;
574
575         status = cldap_search_recv(req, mem_ctx, &search);
576         if (!NT_STATUS_IS_OK(status)) {
577                 return status;
578         }
579         if (search.out.response == NULL) {
580                 return NT_STATUS_NOT_FOUND;
581         }
582
583         if (search.out.response->num_attributes != 1 ||
584             strcasecmp(search.out.response->attributes[0].name, "netlogon") != 0 ||
585             search.out.response->attributes[0].num_values != 1 ||
586             search.out.response->attributes[0].values->length < 2) {
587                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
588         }
589         data = search.out.response->attributes[0].values;
590
591         status = ndr_pull_union_blob(data, mem_ctx, &io->out.netlogon, 
592                                      io->in.version & 0xF,
593                                      (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon);
594         if (!NT_STATUS_IS_OK(status)) {
595                 DEBUG(2,("cldap failed to parse netlogon response of type 0x%02x\n",
596                          SVAL(data->data, 0)));
597                 dump_data(10, data->data, data->length);
598         }
599
600         return status;
601 }
602
603 /*
604   sync cldap netlogon search
605 */
606 NTSTATUS cldap_netlogon(struct cldap_socket *cldap, 
607                         TALLOC_CTX *mem_ctx, struct cldap_netlogon *io)
608 {
609         struct cldap_request *req = cldap_netlogon_send(cldap, io);
610         return cldap_netlogon_recv(req, mem_ctx, io);
611 }
612
613
614 /*
615   send an empty reply (used on any error, so the client doesn't keep waiting
616   or send the bad request again)
617 */
618 NTSTATUS cldap_empty_reply(struct cldap_socket *cldap, 
619                            uint32_t message_id,
620                            const char *src_address, int src_port)
621 {
622         NTSTATUS status;
623         struct cldap_reply reply;
624         struct ldap_Result result;
625
626         reply.messageid    = message_id;
627         reply.dest_address = src_address;
628         reply.dest_port    = src_port;
629         reply.response     = NULL;
630         reply.result       = &result;
631
632         ZERO_STRUCT(result);
633
634         status = cldap_reply_send(cldap, &reply);
635
636         return status;
637 }
638
639
640 /*
641   send a netlogon reply 
642 */
643 NTSTATUS cldap_netlogon_reply(struct cldap_socket *cldap, 
644                               uint32_t message_id,
645                               const char *src_address, int src_port,
646                               uint32_t version,
647                               union nbt_cldap_netlogon *netlogon)
648 {
649         NTSTATUS status;
650         struct cldap_reply reply;
651         struct ldap_SearchResEntry response;
652         struct ldap_Result result;
653         TALLOC_CTX *tmp_ctx = talloc_new(cldap);
654         DATA_BLOB blob;
655
656         status = ndr_push_union_blob(&blob, tmp_ctx, netlogon, version & 0xF, 
657                                      (ndr_push_flags_fn_t)ndr_push_nbt_cldap_netlogon);
658         if (!NT_STATUS_IS_OK(status)) {
659                 talloc_free(tmp_ctx);
660                 return status;
661         }
662
663         reply.messageid    = message_id;
664         reply.dest_address = src_address;
665         reply.dest_port    = src_port;
666         reply.response     = &response;
667         reply.result       = &result;
668
669         ZERO_STRUCT(result);
670
671         response.dn = "";
672         response.num_attributes = 1;
673         response.attributes = talloc(tmp_ctx, struct ldap_attribute);
674         NT_STATUS_HAVE_NO_MEMORY(response.attributes);
675         response.attributes->name = "netlogon";
676         response.attributes->num_values = 1;
677         response.attributes->values = &blob;
678
679         status = cldap_reply_send(cldap, &reply);
680
681         talloc_free(tmp_ctx);
682
683         return status;
684 }
685
686