r13924: Split more prototypes out of include/proto.h + initial work on header
[sfrench/samba-autobuild/.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 "libcli/security/proto.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         struct socket_address *src;
67         DATA_BLOB blob;
68         size_t nread, dsize;
69         struct asn1_data asn1;
70         struct ldap_message *ldap_msg;
71         struct cldap_request *req;
72
73         status = socket_pending(cldap->sock, &dsize);
74         if (!NT_STATUS_IS_OK(status)) {
75                 talloc_free(tmp_ctx);
76                 return;
77         }
78
79         blob = data_blob_talloc(tmp_ctx, NULL, dsize);
80         if (blob.data == NULL) {
81                 talloc_free(tmp_ctx);
82                 return;
83         }
84
85         status = socket_recvfrom(cldap->sock, blob.data, blob.length, &nread, 0,
86                                  tmp_ctx, &src);
87         if (!NT_STATUS_IS_OK(status)) {
88                 talloc_free(tmp_ctx);
89                 return;
90         }
91         blob.length = nread;
92
93         DEBUG(2,("Received cldap packet of length %d from %s:%d\n", 
94                  (int)blob.length, src->addr, src->port));
95
96         if (!asn1_load(&asn1, blob)) {
97                 DEBUG(2,("Failed to setup for asn.1 decode\n"));
98                 talloc_free(tmp_ctx);
99                 return;
100         }
101         talloc_steal(tmp_ctx, asn1.data);
102
103         ldap_msg = talloc(tmp_ctx, struct ldap_message);
104         if (ldap_msg == NULL) {
105                 talloc_free(tmp_ctx);
106                 return;
107         }
108
109         /* this initial decode is used to find the message id */
110         if (!ldap_decode(&asn1, ldap_msg)) {
111                 DEBUG(2,("Failed to decode ldap message\n"));
112                 talloc_free(tmp_ctx);
113                 return;
114         }
115
116         /* find the pending request */
117         req = idr_find(cldap->idr, ldap_msg->messageid);
118         if (req == NULL) {
119                 if (cldap->incoming.handler) {
120                         cldap->incoming.handler(cldap, ldap_msg, src);
121                 } else {
122                         DEBUG(2,("Mismatched cldap reply %u from %s:%d\n",
123                                  ldap_msg->messageid, src->addr, src->port));
124                 }
125                 talloc_free(tmp_ctx);
126                 return;
127         }
128
129         req->asn1 = asn1;
130         talloc_steal(req, asn1.data);
131         req->asn1.ofs = 0;
132
133         req->state = CLDAP_REQUEST_DONE;
134         talloc_free(req->te);
135
136         talloc_free(tmp_ctx);
137
138         if (req->async.fn) {
139                 req->async.fn(req);
140         }
141 }
142
143 /*
144   handle request timeouts
145 */
146 static void cldap_request_timeout(struct event_context *event_ctx, 
147                                   struct timed_event *te, struct timeval t,
148                                   void *private)
149 {
150         struct cldap_request *req = talloc_get_type(private, struct cldap_request);
151
152         /* possibly try again */
153         if (req->num_retries != 0) {
154                 size_t len = req->encoded.length;
155
156                 req->num_retries--;
157
158                 socket_sendto(req->cldap->sock, &req->encoded, &len, 0, 
159                               req->dest);
160
161                 req->te = event_add_timed(req->cldap->event_ctx, req, 
162                                           timeval_current_ofs(req->timeout, 0),
163                                           cldap_request_timeout, req);
164                 return;
165         }
166
167         req->state = CLDAP_REQUEST_TIMEOUT;
168         if (req->async.fn) {
169                 req->async.fn(req);
170         }
171 }
172
173 /*
174   handle send events on a cldap socket
175 */
176 static void cldap_socket_send(struct cldap_socket *cldap)
177 {
178         struct cldap_request *req;
179         NTSTATUS status;
180
181         while ((req = cldap->send_queue)) {
182                 size_t len;
183                 
184                 len = req->encoded.length;
185                 status = socket_sendto(cldap->sock, &req->encoded, &len, 0, 
186                                        req->dest);
187                 if (NT_STATUS_IS_ERR(status)) {
188                         DEBUG(3,("Failed to send cldap request of length %u to %s:%d\n",
189                                  (unsigned)req->encoded.length, req->dest->addr, req->dest->port));
190                         DLIST_REMOVE(cldap->send_queue, req);
191                         talloc_free(req);
192                         continue;
193                 }
194
195                 if (!NT_STATUS_IS_OK(status)) return;
196
197                 DLIST_REMOVE(cldap->send_queue, req);
198
199                 if (req->is_reply) {
200                         talloc_free(req);
201                 } else {
202                         req->state = CLDAP_REQUEST_WAIT;
203
204                         req->te = event_add_timed(cldap->event_ctx, req, 
205                                                   timeval_current_ofs(req->timeout, 0),
206                                                   cldap_request_timeout, req);
207
208                         EVENT_FD_READABLE(cldap->fde);
209                 }
210         }
211
212         EVENT_FD_NOT_WRITEABLE(cldap->fde);
213         return;
214 }
215
216
217 /*
218   handle fd events on a cldap_socket
219 */
220 static void cldap_socket_handler(struct event_context *ev, struct fd_event *fde,
221                                  uint16_t flags, void *private)
222 {
223         struct cldap_socket *cldap = talloc_get_type(private, struct cldap_socket);
224         if (flags & EVENT_FD_WRITE) {
225                 cldap_socket_send(cldap);
226         } 
227         if (flags & EVENT_FD_READ) {
228                 cldap_socket_recv(cldap);
229         }
230 }
231
232 /*
233   initialise a cldap_socket. The event_ctx is optional, if provided
234   then operations will use that event context
235 */
236 struct cldap_socket *cldap_socket_init(TALLOC_CTX *mem_ctx, 
237                                        struct event_context *event_ctx)
238 {
239         struct cldap_socket *cldap;
240         NTSTATUS status;
241
242         cldap = talloc(mem_ctx, struct cldap_socket);
243         if (cldap == NULL) goto failed;
244
245         if (event_ctx == NULL) {
246                 cldap->event_ctx = event_context_init(cldap);
247         } else {
248                 cldap->event_ctx = talloc_reference(cldap, event_ctx);
249         }
250         if (cldap->event_ctx == NULL) goto failed;
251
252         cldap->idr = idr_init(cldap);
253         if (cldap->idr == NULL) goto failed;
254
255         status = socket_create("ip", SOCKET_TYPE_DGRAM, &cldap->sock, 0);
256         if (!NT_STATUS_IS_OK(status)) goto failed;
257
258         talloc_steal(cldap, cldap->sock);
259
260         cldap->fde = event_add_fd(cldap->event_ctx, cldap, 
261                                       socket_get_fd(cldap->sock), 0,
262                                       cldap_socket_handler, cldap);
263
264         cldap->send_queue = NULL;
265         cldap->incoming.handler = NULL;
266         
267         return cldap;
268
269 failed:
270         talloc_free(cldap);
271         return NULL;
272 }
273
274
275 /*
276   setup a handler for incoming requests
277 */
278 NTSTATUS cldap_set_incoming_handler(struct cldap_socket *cldap,
279                                   void (*handler)(struct cldap_socket *, struct ldap_message *, 
280                                                   struct socket_address *),
281                                   void *private)
282 {
283         cldap->incoming.handler = handler;
284         cldap->incoming.private = private;
285         EVENT_FD_READABLE(cldap->fde);
286         return NT_STATUS_OK;
287 }
288
289 /*
290   queue a cldap request for send
291 */
292 struct cldap_request *cldap_search_send(struct cldap_socket *cldap, 
293                                         struct cldap_search *io)
294 {
295         struct ldap_message *msg;
296         struct cldap_request *req;
297         struct ldap_SearchRequest *search;
298
299         req = talloc_zero(cldap, struct cldap_request);
300         if (req == NULL) goto failed;
301
302         req->cldap       = cldap;
303         req->state       = CLDAP_REQUEST_SEND;
304         req->timeout     = io->in.timeout;
305         req->num_retries = io->in.retries;
306         req->is_reply    = False;
307
308         req->dest = socket_address_from_strings(req, cldap->sock->backend_name,
309                                                 io->in.dest_address, lp_cldap_port());
310         if (!req->dest) goto failed;
311
312         req->message_id = idr_get_new_random(cldap->idr, req, UINT16_MAX);
313         if (req->message_id == -1) goto failed;
314
315         talloc_set_destructor(req, cldap_request_destructor);
316
317         msg = talloc(req, struct ldap_message);
318         if (msg == NULL) goto failed;
319         msg->messageid       = req->message_id;
320         msg->type            = LDAP_TAG_SearchRequest;
321         msg->controls        = NULL;
322         search = &msg->r.SearchRequest;
323
324         search->basedn         = "";
325         search->scope          = LDAP_SEARCH_SCOPE_BASE;
326         search->deref          = LDAP_DEREFERENCE_NEVER;
327         search->timelimit      = 0;
328         search->sizelimit      = 0;
329         search->attributesonly = False;
330         search->num_attributes = str_list_length(io->in.attributes);
331         search->attributes     = io->in.attributes;
332         search->tree           = ldb_parse_tree(req, io->in.filter);
333         if (search->tree == NULL) {
334                 goto failed;
335         }
336
337         if (!ldap_encode(msg, &req->encoded, req)) {
338                 DEBUG(0,("Failed to encode cldap message to %s:%d\n",
339                          req->dest->addr, req->dest->port));
340                 goto failed;
341         }
342
343         DLIST_ADD_END(cldap->send_queue, req, struct cldap_request *);
344
345         EVENT_FD_WRITEABLE(cldap->fde);
346
347         return req;
348
349 failed:
350         talloc_free(req);
351         return NULL;
352 }
353
354
355 /*
356   queue a cldap reply for send
357 */
358 NTSTATUS cldap_reply_send(struct cldap_socket *cldap, struct cldap_reply *io)
359 {
360         struct ldap_message *msg;
361         struct cldap_request *req;
362         DATA_BLOB blob1, blob2;
363         NTSTATUS status = NT_STATUS_NO_MEMORY;
364
365         req = talloc_zero(cldap, struct cldap_request);
366         if (req == NULL) goto failed;
367
368         req->cldap       = cldap;
369         req->state       = CLDAP_REQUEST_SEND;
370         req->is_reply    = True;
371
372         req->dest        = io->dest;
373         if (talloc_reference(req, io->dest) == NULL) goto failed;
374
375         talloc_set_destructor(req, cldap_request_destructor);
376
377         msg = talloc(req, struct ldap_message);
378         if (msg == NULL) goto failed;
379         msg->messageid       = io->messageid;
380         msg->controls        = NULL;
381         
382         if (io->response) {
383                 msg->type = LDAP_TAG_SearchResultEntry;
384                 msg->r.SearchResultEntry = *io->response;
385
386                 if (!ldap_encode(msg, &blob1, req)) {
387                         DEBUG(0,("Failed to encode cldap message to %s:%d\n",
388                                  req->dest->addr, req->dest->port));
389                         status = NT_STATUS_INVALID_PARAMETER;
390                         goto failed;
391                 }
392         } else {
393                 blob1 = data_blob(NULL, 0);
394         }
395
396         msg->type = LDAP_TAG_SearchResultDone;
397         msg->r.SearchResultDone = *io->result;
398
399         if (!ldap_encode(msg, &blob2, req)) {
400                 DEBUG(0,("Failed to encode cldap message to %s:%d\n",
401                          req->dest->addr, req->dest->port));
402                 status = NT_STATUS_INVALID_PARAMETER;
403                 goto failed;
404         }
405
406         req->encoded = data_blob_talloc(req, NULL, blob1.length + blob2.length);
407         if (req->encoded.data == NULL) goto failed;
408
409         memcpy(req->encoded.data, blob1.data, blob1.length);
410         memcpy(req->encoded.data+blob1.length, blob2.data, blob2.length);
411
412         DLIST_ADD_END(cldap->send_queue, req, struct cldap_request *);
413
414         EVENT_FD_WRITEABLE(cldap->fde);
415
416         return NT_STATUS_OK;
417
418 failed:
419         talloc_free(req);
420         return status;
421 }
422
423 /*
424   receive a cldap reply
425 */
426 NTSTATUS cldap_search_recv(struct cldap_request *req, 
427                            TALLOC_CTX *mem_ctx, 
428                            struct cldap_search *io)
429 {
430         struct ldap_message *ldap_msg;
431
432         if (req == NULL) {
433                 return NT_STATUS_NO_MEMORY;
434         }
435
436         while (req->state < CLDAP_REQUEST_DONE) {
437                 if (event_loop_once(req->cldap->event_ctx) != 0) {
438                         talloc_free(req);
439                         return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
440                 }
441         }
442
443         if (req->state == CLDAP_REQUEST_TIMEOUT) {
444                 talloc_free(req);
445                 return NT_STATUS_IO_TIMEOUT;
446         }
447
448         ldap_msg = talloc(mem_ctx, struct ldap_message);
449         NT_STATUS_HAVE_NO_MEMORY(ldap_msg);
450
451         if (!ldap_decode(&req->asn1, ldap_msg)) {
452                 talloc_free(req);
453                 return NT_STATUS_INVALID_PARAMETER;
454         }
455
456         ZERO_STRUCT(io->out);
457
458         /* the first possible form has a search result in first place */
459         if (ldap_msg->type == LDAP_TAG_SearchResultEntry) {
460                 io->out.response = talloc(mem_ctx, struct ldap_SearchResEntry);
461                 NT_STATUS_HAVE_NO_MEMORY(io->out.response);
462                 *io->out.response = ldap_msg->r.SearchResultEntry;
463
464                 /* decode the 2nd part */
465                 if (!ldap_decode(&req->asn1, ldap_msg)) {
466                         talloc_free(req);
467                         return NT_STATUS_INVALID_PARAMETER;
468                 }
469         }
470
471         if (ldap_msg->type != LDAP_TAG_SearchResultDone) {
472                 talloc_free(req);
473                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
474         }
475
476         io->out.result = talloc(mem_ctx, struct ldap_Result);
477         NT_STATUS_HAVE_NO_MEMORY(io->out.result);
478         *io->out.result = ldap_msg->r.SearchResultDone;
479
480         talloc_free(req);
481         return NT_STATUS_OK;
482 }
483
484
485 /*
486   synchronous cldap search
487 */
488 NTSTATUS cldap_search(struct cldap_socket *cldap, 
489                       TALLOC_CTX *mem_ctx, 
490                       struct cldap_search *io)
491 {
492         struct cldap_request *req = cldap_search_send(cldap, io);
493         return cldap_search_recv(req, mem_ctx, io);
494 }
495
496
497
498 /*
499   queue a cldap netlogon for send
500 */
501 struct cldap_request *cldap_netlogon_send(struct cldap_socket *cldap, 
502                                           struct cldap_netlogon *io)
503 {
504         struct cldap_search search;
505         char *filter;
506         struct cldap_request *req;
507         const char *attr[] = { "NetLogon", NULL };
508         TALLOC_CTX *tmp_ctx = talloc_new(cldap);
509
510         filter = talloc_asprintf(tmp_ctx, "(&(NtVer=%s)", 
511                                  ldap_encode_ndr_uint32(tmp_ctx, io->in.version));
512         if (filter == NULL) goto failed;
513         if (io->in.user) {
514                 filter = talloc_asprintf_append(filter, "(User=%s)", io->in.user);
515                 if (filter == NULL) goto failed;
516         }
517         if (io->in.host) {
518                 filter = talloc_asprintf_append(filter, "(Host=%s)", io->in.host);
519                 if (filter == NULL) goto failed;
520         }
521         if (io->in.realm) {
522                 filter = talloc_asprintf_append(filter, "(DnsDomain=%s)", io->in.realm);
523                 if (filter == NULL) goto failed;
524         }
525         if (io->in.acct_control != -1) {
526                 filter = talloc_asprintf_append(filter, "(AAC=%s)", 
527                                                 ldap_encode_ndr_uint32(tmp_ctx, io->in.acct_control));
528                 if (filter == NULL) goto failed;
529         }
530         if (io->in.domain_sid) {
531                 struct dom_sid *sid = dom_sid_parse_talloc(tmp_ctx, io->in.domain_sid);
532                 if (sid == NULL) goto failed;
533                 filter = talloc_asprintf_append(filter, "(domainSid=%s)",
534                                                 ldap_encode_ndr_dom_sid(tmp_ctx, sid));
535                 if (filter == NULL) goto failed;
536         }
537         if (io->in.domain_guid) {
538                 struct GUID guid;
539                 NTSTATUS status;
540                 status = GUID_from_string(io->in.domain_guid, &guid);
541                 if (!NT_STATUS_IS_OK(status)) goto failed;
542                 filter = talloc_asprintf_append(filter, "(DomainGuid=%s)",
543                                                 ldap_encode_ndr_GUID(tmp_ctx, &guid));
544                 if (filter == NULL) goto failed;
545         }
546         filter = talloc_asprintf_append(filter, ")");
547         if (filter == NULL) goto failed;
548
549         search.in.dest_address = io->in.dest_address;
550         search.in.filter       = filter;
551         search.in.attributes   = attr;
552         search.in.timeout      = 2;
553         search.in.retries      = 2;
554
555         req = cldap_search_send(cldap, &search);
556
557         talloc_free(tmp_ctx);
558         return req;
559 failed:
560         talloc_free(tmp_ctx);
561         return NULL;
562 }
563
564
565 /*
566   receive a cldap netlogon reply
567 */
568 NTSTATUS cldap_netlogon_recv(struct cldap_request *req, 
569                              TALLOC_CTX *mem_ctx, 
570                              struct cldap_netlogon *io)
571 {
572         NTSTATUS status;
573         struct cldap_search search;
574         DATA_BLOB *data;
575
576         status = cldap_search_recv(req, mem_ctx, &search);
577         if (!NT_STATUS_IS_OK(status)) {
578                 return status;
579         }
580         if (search.out.response == NULL) {
581                 return NT_STATUS_NOT_FOUND;
582         }
583
584         if (search.out.response->num_attributes != 1 ||
585             strcasecmp(search.out.response->attributes[0].name, "netlogon") != 0 ||
586             search.out.response->attributes[0].num_values != 1 ||
587             search.out.response->attributes[0].values->length < 2) {
588                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
589         }
590         data = search.out.response->attributes[0].values;
591
592         status = ndr_pull_union_blob(data, mem_ctx, &io->out.netlogon, 
593                                      io->in.version & 0xF,
594                                      (ndr_pull_flags_fn_t)ndr_pull_nbt_cldap_netlogon);
595         if (!NT_STATUS_IS_OK(status)) {
596                 DEBUG(2,("cldap failed to parse netlogon response of type 0x%02x\n",
597                          SVAL(data->data, 0)));
598                 dump_data(10, data->data, data->length);
599         }
600
601         return status;
602 }
603
604 /*
605   sync cldap netlogon search
606 */
607 NTSTATUS cldap_netlogon(struct cldap_socket *cldap, 
608                         TALLOC_CTX *mem_ctx, struct cldap_netlogon *io)
609 {
610         struct cldap_request *req = cldap_netlogon_send(cldap, io);
611         return cldap_netlogon_recv(req, mem_ctx, io);
612 }
613
614
615 /*
616   send an empty reply (used on any error, so the client doesn't keep waiting
617   or send the bad request again)
618 */
619 NTSTATUS cldap_empty_reply(struct cldap_socket *cldap, 
620                            uint32_t message_id,
621                            struct socket_address *src)
622 {
623         NTSTATUS status;
624         struct cldap_reply reply;
625         struct ldap_Result result;
626
627         reply.messageid    = message_id;
628         reply.dest         = src;
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                               struct socket_address *src,
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         = src;
665         reply.response     = &response;
666         reply.result       = &result;
667
668         ZERO_STRUCT(result);
669
670         response.dn = "";
671         response.num_attributes = 1;
672         response.attributes = talloc(tmp_ctx, struct ldb_message_element);
673         NT_STATUS_HAVE_NO_MEMORY(response.attributes);
674         response.attributes->name = "netlogon";
675         response.attributes->num_values = 1;
676         response.attributes->values = &blob;
677
678         status = cldap_reply_send(cldap, &reply);
679
680         talloc_free(tmp_ctx);
681
682         return status;
683 }
684
685