s4 dns: Look up all names in the ldb database.
[garming/samba-autobuild/.git] / source4 / dns_server / dns_server.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    DNS server startup
5
6    Copyright (C) 2010 Kai Blin  <kai@samba.org>
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 3 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, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "smbd/service_task.h"
24 #include "smbd/service.h"
25 #include "smbd/service_stream.h"
26 #include "smbd/process_model.h"
27 #include "lib/events/events.h"
28 #include "lib/socket/socket.h"
29 #include "lib/tsocket/tsocket.h"
30 #include "libcli/util/tstream.h"
31 #include "libcli/util/ntstatus.h"
32 #include "system/network.h"
33 #include "lib/stream/packet.h"
34 #include "lib/socket/netif.h"
35 #include "dns_server/dns_server.h"
36 #include "param/param.h"
37 #include "librpc/ndr/libndr.h"
38 #include "librpc/gen_ndr/ndr_dns.h"
39 #include "librpc/gen_ndr/ndr_dnsp.h"
40 #include <ldb.h>
41 #include "dsdb/samdb/samdb.h"
42 #include "dsdb/common/util.h"
43 #include "auth/session.h"
44 #include "lib/util/dlinklist.h"
45
46 /* hold information about one dns socket */
47 struct dns_socket {
48         struct dns_server *dns;
49         struct tsocket_address *local_address;
50 };
51
52 struct dns_udp_socket {
53         struct dns_socket *dns_socket;
54         struct tdgram_context *dgram;
55         struct tevent_queue *send_queue;
56 };
57
58 /*
59   state of an open tcp connection
60 */
61 struct dns_tcp_connection {
62         /* stream connection we belong to */
63         struct stream_connection *conn;
64
65         /* the dns_server the connection belongs to */
66         struct dns_socket *dns_socket;
67
68         struct tstream_context *tstream;
69
70         struct tevent_queue *send_queue;
71 };
72
73 static void dns_tcp_terminate_connection(struct dns_tcp_connection *dnsconn, const char *reason)
74 {
75         stream_terminate_connection(dnsconn->conn, reason);
76 }
77
78 static void dns_tcp_recv(struct stream_connection *conn, uint16_t flags)
79 {
80         struct dns_tcp_connection *dnsconn = talloc_get_type(conn->private_data,
81                                                              struct dns_tcp_connection);
82         /* this should never be triggered! */
83         dns_tcp_terminate_connection(dnsconn, "dns_tcp_recv: called");
84 }
85
86 static void dns_tcp_send(struct stream_connection *conn, uint16_t flags)
87 {
88         struct dns_tcp_connection *dnsconn = talloc_get_type(conn->private_data,
89                                                              struct dns_tcp_connection);
90         /* this should never be triggered! */
91         dns_tcp_terminate_connection(dnsconn, "dns_tcp_send: called");
92 }
93
94 static bool dns_name_match(const char *zone, const char *name, size_t *host_part_len)
95 {
96         size_t zl = strlen(zone);
97         size_t nl = strlen(name);
98         ssize_t zi, ni;
99         static const size_t fixup = 'a' - 'A';
100
101         if (zl > nl) {
102                 return false;
103         }
104
105         for (zi = zl, ni = nl; zi >= 0; zi--, ni--) {
106                 char zc = zone[zi];
107                 char nc = name[ni];
108
109                 /* convert to lower case */
110                 if (zc >= 'A' && zc <= 'Z') {
111                         zc += fixup;
112                 }
113                 if (nc >= 'A' && nc <= 'Z') {
114                         nc += fixup;
115                 }
116
117                 if (zc != nc) {
118                         return false;
119                 }
120         }
121
122         if (ni >= 0) {
123                 if (name[ni] != '.') {
124                         return false;
125                 }
126
127                 ni--;
128         }
129
130         *host_part_len = ni+1;
131
132         return true;
133 }
134
135 static NTSTATUS dns_name2dn(struct dns_server *dns,
136                             TALLOC_CTX *mem_ctx,
137                             const char *name,
138                             struct ldb_dn **_dn)
139 {
140         struct ldb_dn *base;
141         struct ldb_dn *dn;
142         const struct dns_server_zone *z;
143         size_t host_part_len = 0;
144
145         if (name == NULL) {
146                 return NT_STATUS_INVALID_PARAMETER;
147         }
148
149         /*TODO: Check if 'name' is a valid DNS name */
150
151         if (strcmp(name, "") == 0) {
152                 base = ldb_get_default_basedn(dns->samdb);
153                 dn = ldb_dn_copy(mem_ctx, base);
154                 ldb_dn_add_child_fmt(dn, "DC=@,DC=RootDNSServers,CN=MicrosoftDNS,CN=System");
155                 *_dn = dn;
156                 return NT_STATUS_OK;
157         }
158
159         for (z = dns->zones; z != NULL; z = z->next) {
160                 bool match;
161
162                 match = dns_name_match(z->name, name, &host_part_len);
163                 if (match) {
164                         break;
165                 }
166         }
167
168         if (z == NULL) {
169                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
170         }
171
172         if (host_part_len == 0) {
173                 dn = ldb_dn_copy(mem_ctx, z->dn);
174                 ldb_dn_add_child_fmt(dn, "DC=@");
175                 *_dn = dn;
176                 return NT_STATUS_OK;
177         }
178
179         dn = ldb_dn_copy(mem_ctx, z->dn);
180         ldb_dn_add_child_fmt(dn, "DC=%*.*s", (int)host_part_len, (int)host_part_len, name);
181         *_dn = dn;
182         return NT_STATUS_OK;
183 }
184
185 static NTSTATUS handle_question(struct dns_server *dns,
186                                 TALLOC_CTX *mem_ctx,
187                                 const struct dns_name_question *question,
188                                 struct dns_res_rec **answers, uint16_t *ancount)
189 {
190         struct dns_res_rec *ans;
191         struct ldb_dn *dn = NULL;
192         NTSTATUS status;
193         static const char * const attrs[] = { "dnsRecord", NULL};
194         int ret;
195         uint16_t ai = *ancount;
196         uint16_t ri;
197         struct ldb_message *msg = NULL;
198         struct dnsp_DnssrvRpcRecord *recs;
199         struct ldb_message_element *el;
200
201         status = dns_name2dn(dns, mem_ctx, question->name, &dn);
202         NT_STATUS_NOT_OK_RETURN(status);
203
204         ret = dsdb_search_one(dns->samdb, mem_ctx, &msg, dn,
205                               LDB_SCOPE_BASE, attrs, 0, "%s", "(objectClass=dnsNode)");
206         if (ret != LDB_SUCCESS) {
207                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
208         }
209
210         el = ldb_msg_find_element(msg, attrs[0]);
211         if (el == NULL) {
212                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
213         }
214
215         recs = talloc_array(mem_ctx, struct dnsp_DnssrvRpcRecord, el->num_values);
216         for (ri = 0; ri < el->num_values; ri++) {
217                 struct ldb_val *v = &el->values[ri];
218                 enum ndr_err_code ndr_err;
219
220                 ndr_err = ndr_pull_struct_blob(v, recs, &recs[ri],
221                                 (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
222                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
223                         DEBUG(0, ("Failed to grab dnsp_DnssrvRpcRecord\n"));
224                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
225                 }
226         }
227
228         ans = talloc_realloc(mem_ctx, *answers, struct dns_res_rec,
229                              ai + el->num_values);
230         NT_STATUS_HAVE_NO_MEMORY(ans);
231
232         switch (question->question_type) {
233         case DNS_QTYPE_A:
234                 for (ri = 0; ri < el->num_values; ri++) {
235                         if (recs[ri].wType != question->question_type) {
236                                 continue;
237                         }
238
239                         ZERO_STRUCT(ans[ai]);
240                         ans[ai].name = talloc_strdup(ans, question->name);
241                         ans[ai].rr_type = DNS_QTYPE_A;
242                         ans[ai].rr_class = DNS_QCLASS_IP;
243                         ans[ai].ttl = recs[ri].dwTtlSeconds;
244                         ans[ai].rdata.ipv4_record = talloc_strdup(ans, recs[ri].data.ipv4);
245                         ai++;
246                 }
247                 break;
248         case DNS_QTYPE_AAAA:
249                 for (ri = 0; ri < el->num_values; ri++) {
250                         if (recs[ri].wType != question->question_type) {
251                                 continue;
252                         }
253
254                         ZERO_STRUCT(ans[ai]);
255                         ans[ai].name = talloc_strdup(ans, question->name);
256                         ans[ai].rr_type = DNS_QTYPE_AAAA;
257                         ans[ai].rr_class = DNS_QCLASS_IP;
258                         ans[ai].ttl = recs[ri].dwTtlSeconds;
259                         ans[ai].rdata.ipv6_record = recs[ri].data.ipv6;
260                         ai++;
261                 }
262                 break;
263         case DNS_QTYPE_NS:
264                 for (ri = 0; ri < el->num_values; ri++) {
265                         if (recs[ri].wType != question->question_type) {
266                                 continue;
267                         }
268
269                         ZERO_STRUCT(ans[ai]);
270                         ans[ai].name = question->name;
271                         ans[ai].rr_type = DNS_QTYPE_NS;
272                         ans[ai].rr_class = DNS_QCLASS_IP;
273                         ans[ai].ttl = recs[ri].dwTtlSeconds;
274                         ans[ai].rdata.ns_record = recs[ri].data.ns;
275                         ai++;
276                 }
277                 break;
278         default:
279                 return NT_STATUS_NOT_IMPLEMENTED;
280         }
281
282         *ancount = ai;
283         *answers = ans;
284
285         return NT_STATUS_OK;
286
287 }
288
289 static NTSTATUS compute_reply(struct dns_server *dns,
290                               TALLOC_CTX *mem_ctx,
291                               struct dns_name_packet *in,
292                               struct dns_res_rec **answers,    uint16_t *ancount,
293                               struct dns_res_rec **nsrecs,     uint16_t *nscount,
294                               struct dns_res_rec **additional, uint16_t *arcount)
295 {
296         uint16_t num_answers=0;
297         struct dns_res_rec *ans=NULL;
298         int i;
299         NTSTATUS status;
300
301         ans = talloc_array(mem_ctx, struct dns_res_rec, 0);
302         if (answers == NULL) return NT_STATUS_NO_MEMORY;
303
304         for (i = 0; i < in->qdcount; ++i) {
305                 status = handle_question(dns, mem_ctx, &in->questions[i], &ans, &num_answers);
306                 NT_STATUS_NOT_OK_RETURN(status);
307         }
308
309         *answers = ans;
310         *ancount = num_answers;
311
312         /*FIXME: Do something for these */
313         *nsrecs  = NULL;
314         *nscount = 0;
315
316         *additional = NULL;
317         *arcount    = 0;
318
319         return NT_STATUS_OK;
320 }
321
322 static NTSTATUS dns_process(struct dns_server *dns,
323                             TALLOC_CTX *mem_ctx,
324                             DATA_BLOB *in,
325                             DATA_BLOB *out)
326 {
327         enum ndr_err_code ndr_err;
328         NTSTATUS ret;
329         struct dns_name_packet *in_packet = talloc_zero(mem_ctx, struct dns_name_packet);
330         struct dns_name_packet *out_packet = talloc_zero(mem_ctx, struct dns_name_packet);
331         struct dns_res_rec *answers, *nsrecs, *additional;
332         uint16_t num_answers, num_nsrecs, num_additional;
333
334         if (in_packet == NULL) return NT_STATUS_INVALID_PARAMETER;
335
336         dump_data(2, in->data, in->length);
337
338         ndr_err = ndr_pull_struct_blob(in, in_packet, in_packet,
339                         (ndr_pull_flags_fn_t)ndr_pull_dns_name_packet);
340         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
341                 TALLOC_FREE(in_packet);
342                 DEBUG(0, ("Failed to parse packet %d!\n", ndr_err));
343                 return NT_STATUS_COULD_NOT_INTERPRET;
344         }
345
346         NDR_PRINT_DEBUG(dns_name_packet, in_packet);
347         out_packet->id = in_packet->id;
348         out_packet->operation = DNS_FLAG_REPLY | DNS_FLAG_AUTHORITATIVE |
349                                 DNS_FLAG_RECURSION_DESIRED | DNS_FLAG_RECURSION_AVAIL;
350
351         out_packet->qdcount = in_packet->qdcount;
352         out_packet->questions = in_packet->questions;
353
354         out_packet->ancount = 0;
355         out_packet->answers = NULL;
356
357         out_packet->nscount = 0;
358         out_packet->nsrecs  = NULL;
359
360         out_packet->arcount = 0;
361         out_packet->additional = NULL;
362
363         ret = compute_reply(dns, out_packet, in_packet, &answers, &num_answers,
364                             &nsrecs, &num_nsrecs, &additional, &num_additional);
365
366         if (NT_STATUS_IS_OK(ret)) {
367                 out_packet->ancount = num_answers;
368                 out_packet->answers = answers;
369
370                 out_packet->nscount = num_nsrecs;
371                 out_packet->nsrecs  = nsrecs;
372
373                 out_packet->arcount = num_additional;
374                 out_packet->additional = additional;
375         }
376
377         NDR_PRINT_DEBUG(dns_name_packet, out_packet);
378         ndr_err = ndr_push_struct_blob(out, out_packet, out_packet,
379                         (ndr_push_flags_fn_t)ndr_push_dns_name_packet);
380         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
381                 TALLOC_FREE(in_packet);
382                 TALLOC_FREE(out_packet);
383                 DEBUG(0, ("Failed to push packet %d!\n", ndr_err));
384                 return NT_STATUS_INTERNAL_ERROR;
385         }
386
387         dump_data(2, out->data, out->length);
388         return NT_STATUS_OK;
389 }
390
391 struct dns_tcp_call {
392         struct dns_tcp_connection *dns_conn;
393         DATA_BLOB in;
394         DATA_BLOB out;
395         uint8_t out_hdr[4];
396         struct iovec out_iov[2];
397 };
398
399 static void dns_tcp_call_writev_done(struct tevent_req *subreq);
400
401 static void dns_tcp_call_loop(struct tevent_req *subreq)
402 {
403         struct dns_tcp_connection *dns_conn = tevent_req_callback_data(subreq,
404                                       struct dns_tcp_connection);
405         struct dns_tcp_call *call;
406         NTSTATUS status;
407
408         call = talloc(dns_conn, struct dns_tcp_call);
409         if (call == NULL) {
410                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
411                                 "no memory for dns_tcp_call");
412                 return;
413         }
414         call->dns_conn = dns_conn;
415
416         status = tstream_read_pdu_blob_recv(subreq,
417                                             call,
418                                             &call->in);
419         TALLOC_FREE(subreq);
420         if (!NT_STATUS_IS_OK(status)) {
421                 const char *reason;
422
423                 reason = talloc_asprintf(call, "dns_tcp_call_loop: "
424                                          "tstream_read_pdu_blob_recv() - %s",
425                                          nt_errstr(status));
426                 if (!reason) {
427                         reason = nt_errstr(status);
428                 }
429
430                 dns_tcp_terminate_connection(dns_conn, reason);
431                 return;
432         }
433
434         DEBUG(10,("Received krb5 TCP packet of length %lu from %s\n",
435                  (long) call->in.length,
436                  tsocket_address_string(dns_conn->conn->remote_address, call)));
437
438         /* skip length header */
439         call->in.data +=4;
440         call->in.length -= 4;
441
442         /* Call dns */
443         status = dns_process(dns_conn->dns_socket->dns, call, &call->in, &call->out);
444         if (!NT_STATUS_IS_OK(status)) {
445                 DEBUG(0, ("dns_process returned %s\n", nt_errstr(status)));
446                 dns_tcp_terminate_connection(dns_conn,
447                                 "dns_tcp_call_loop: process function failed");
448                 return;
449         }
450
451         /* First add the length of the out buffer */
452         RSIVAL(call->out_hdr, 0, call->out.length);
453         call->out_iov[0].iov_base = (char *) call->out_hdr;
454         call->out_iov[0].iov_len = 4;
455
456         call->out_iov[1].iov_base = (char *) call->out.data;
457         call->out_iov[1].iov_len = call->out.length;
458
459         subreq = tstream_writev_queue_send(call,
460                                            dns_conn->conn->event.ctx,
461                                            dns_conn->tstream,
462                                            dns_conn->send_queue,
463                                            call->out_iov, 2);
464         if (subreq == NULL) {
465                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
466                                 "no memory for tstream_writev_queue_send");
467                 return;
468         }
469         tevent_req_set_callback(subreq, dns_tcp_call_writev_done, call);
470
471         /*
472          * The krb5 tcp pdu's has the length as 4 byte (initial_read_size),
473          * packet_full_request_u32 provides the pdu length then.
474          */
475         subreq = tstream_read_pdu_blob_send(dns_conn,
476                                             dns_conn->conn->event.ctx,
477                                             dns_conn->tstream,
478                                             4, /* initial_read_size */
479                                             packet_full_request_u32,
480                                             dns_conn);
481         if (subreq == NULL) {
482                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
483                                 "no memory for tstream_read_pdu_blob_send");
484                 return;
485         }
486         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
487 }
488
489 static void dns_tcp_call_writev_done(struct tevent_req *subreq)
490 {
491         struct dns_tcp_call *call = tevent_req_callback_data(subreq,
492                         struct dns_tcp_call);
493         int sys_errno;
494         int rc;
495
496         rc = tstream_writev_queue_recv(subreq, &sys_errno);
497         TALLOC_FREE(subreq);
498         if (rc == -1) {
499                 const char *reason;
500
501                 reason = talloc_asprintf(call, "dns_tcp_call_writev_done: "
502                                          "tstream_writev_queue_recv() - %d:%s",
503                                          sys_errno, strerror(sys_errno));
504                 if (!reason) {
505                         reason = "dns_tcp_call_writev_done: tstream_writev_queue_recv() failed";
506                 }
507
508                 dns_tcp_terminate_connection(call->dns_conn, reason);
509                 return;
510         }
511
512         /* We don't care about errors */
513
514         talloc_free(call);
515 }
516
517 /*
518   called when we get a new connection
519 */
520 static void dns_tcp_accept(struct stream_connection *conn)
521 {
522         struct dns_socket *dns_socket;
523         struct dns_tcp_connection *dns_conn;
524         struct tevent_req *subreq;
525         int rc;
526
527         dns_conn = talloc_zero(conn, struct dns_tcp_connection);
528         if (dns_conn == NULL) {
529                 stream_terminate_connection(conn,
530                                 "dns_tcp_accept: out of memory");
531                 return;
532         }
533
534         dns_conn->send_queue = tevent_queue_create(conn, "dns_tcp_accept");
535         if (dns_conn->send_queue == NULL) {
536                 stream_terminate_connection(conn,
537                                 "dns_tcp_accept: out of memory");
538                 return;
539         }
540
541         dns_socket = talloc_get_type(conn->private_data, struct dns_socket);
542
543         TALLOC_FREE(conn->event.fde);
544
545         rc = tstream_bsd_existing_socket(dns_conn,
546                         socket_get_fd(conn->socket),
547                         &dns_conn->tstream);
548         if (rc < 0) {
549                 stream_terminate_connection(conn,
550                                 "dns_tcp_accept: out of memory");
551                 return;
552         }
553
554         dns_conn->conn = conn;
555         dns_conn->dns_socket = dns_socket;
556         conn->private_data = dns_conn;
557
558         /*
559          * The krb5 tcp pdu's has the length as 4 byte (initial_read_size),
560          * packet_full_request_u32 provides the pdu length then.
561          */
562         subreq = tstream_read_pdu_blob_send(dns_conn,
563                                             dns_conn->conn->event.ctx,
564                                             dns_conn->tstream,
565                                             4, /* initial_read_size */
566                                             packet_full_request_u32,
567                                             dns_conn);
568         if (subreq == NULL) {
569                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_accept: "
570                                 "no memory for tstream_read_pdu_blob_send");
571                 return;
572         }
573         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
574 }
575
576 static const struct stream_server_ops dns_tcp_stream_ops = {
577         .name                   = "dns_tcp",
578         .accept_connection      = dns_tcp_accept,
579         .recv_handler           = dns_tcp_recv,
580         .send_handler           = dns_tcp_send
581 };
582
583 struct dns_udp_call {
584         struct tsocket_address *src;
585         DATA_BLOB in;
586         DATA_BLOB out;
587 };
588
589 static void dns_udp_call_sendto_done(struct tevent_req *subreq);
590
591 static void dns_udp_call_loop(struct tevent_req *subreq)
592 {
593         struct dns_udp_socket *sock = tevent_req_callback_data(subreq,
594                                       struct dns_udp_socket);
595         struct dns_udp_call *call;
596         uint8_t *buf;
597         ssize_t len;
598         int sys_errno;
599         NTSTATUS status;
600
601         call = talloc(sock, struct dns_udp_call);
602         if (call == NULL) {
603                 talloc_free(call);
604                 goto done;
605         }
606
607         len = tdgram_recvfrom_recv(subreq, &sys_errno,
608                                    call, &buf, &call->src);
609         TALLOC_FREE(subreq);
610         if (len == -1) {
611                 talloc_free(call);
612                 goto done;
613         }
614
615         call->in.data = buf;
616         call->in.length = len;
617
618         DEBUG(10,("Received krb5 UDP packet of length %lu from %s\n",
619                  (long)call->in.length,
620                  tsocket_address_string(call->src, call)));
621
622         /* Call krb5 */
623         status = dns_process(sock->dns_socket->dns, call, &call->in, &call->out);
624         if (!NT_STATUS_IS_OK(status)) {
625                 talloc_free(call);
626                 DEBUG(0, ("dns_process returned %s\n", nt_errstr(status)));
627                 goto done;
628         }
629
630         subreq = tdgram_sendto_queue_send(call,
631                                           sock->dns_socket->dns->task->event_ctx,
632                                           sock->dgram,
633                                           sock->send_queue,
634                                           call->out.data,
635                                           call->out.length,
636                                           call->src);
637         if (subreq == NULL) {
638                 talloc_free(call);
639                 goto done;
640         }
641         tevent_req_set_callback(subreq, dns_udp_call_sendto_done, call);
642
643 done:
644         subreq = tdgram_recvfrom_send(sock,
645                                       sock->dns_socket->dns->task->event_ctx,
646                                       sock->dgram);
647         if (subreq == NULL) {
648                 task_server_terminate(sock->dns_socket->dns->task,
649                                       "no memory for tdgram_recvfrom_send",
650                                       true);
651                 return;
652         }
653         tevent_req_set_callback(subreq, dns_udp_call_loop, sock);
654 }
655
656 static void dns_udp_call_sendto_done(struct tevent_req *subreq)
657 {
658         struct dns_udp_call *call = tevent_req_callback_data(subreq,
659                                        struct dns_udp_call);
660         ssize_t ret;
661         int sys_errno;
662
663         ret = tdgram_sendto_queue_recv(subreq, &sys_errno);
664
665         /* We don't care about errors */
666
667         talloc_free(call);
668 }
669
670 /*
671   start listening on the given address
672 */
673 static NTSTATUS dns_add_socket(struct dns_server *dns,
674                                const struct model_ops *model_ops,
675                                const char *name,
676                                const char *address,
677                                uint16_t port)
678 {
679         struct dns_socket *dns_socket;
680         struct dns_udp_socket *dns_udp_socket;
681         struct tevent_req *udpsubreq;
682         NTSTATUS status;
683         int ret;
684
685         dns_socket = talloc(dns, struct dns_socket);
686         NT_STATUS_HAVE_NO_MEMORY(dns_socket);
687
688         dns_socket->dns = dns;
689
690         ret = tsocket_address_inet_from_strings(dns_socket, "ip",
691                                                 address, port,
692                                                 &dns_socket->local_address);
693         if (ret != 0) {
694                 status = map_nt_error_from_unix(errno);
695                 return status;
696         }
697
698         status = stream_setup_socket(dns->task->event_ctx,
699                                      dns->task->lp_ctx,
700                                      model_ops,
701                                      &dns_tcp_stream_ops,
702                                      "ip", address, &port,
703                                      lpcfg_socket_options(dns->task->lp_ctx),
704                                      dns_socket);
705         if (!NT_STATUS_IS_OK(status)) {
706                 DEBUG(0,("Failed to bind to %s:%u TCP - %s\n",
707                          address, port, nt_errstr(status)));
708                 talloc_free(dns_socket);
709                 return status;
710         }
711
712         dns_udp_socket = talloc(dns_socket, struct dns_udp_socket);
713         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket);
714
715         dns_udp_socket->dns_socket = dns_socket;
716
717         ret = tdgram_inet_udp_socket(dns_socket->local_address,
718                                      NULL,
719                                      dns_udp_socket,
720                                      &dns_udp_socket->dgram);
721         if (ret != 0) {
722                 status = map_nt_error_from_unix(errno);
723                 DEBUG(0,("Failed to bind to %s:%u UDP - %s\n",
724                          address, port, nt_errstr(status)));
725                 return status;
726         }
727
728         dns_udp_socket->send_queue = tevent_queue_create(dns_udp_socket,
729                                                          "dns_udp_send_queue");
730         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket->send_queue);
731
732         udpsubreq = tdgram_recvfrom_send(dns_udp_socket,
733                                          dns->task->event_ctx,
734                                          dns_udp_socket->dgram);
735         NT_STATUS_HAVE_NO_MEMORY(udpsubreq);
736         tevent_req_set_callback(udpsubreq, dns_udp_call_loop, dns_udp_socket);
737
738         return NT_STATUS_OK;
739 }
740
741 /*
742   setup our listening sockets on the configured network interfaces
743 */
744 static NTSTATUS dns_startup_interfaces(struct dns_server *dns, struct loadparm_context *lp_ctx,
745                                        struct interface *ifaces)
746 {
747         const struct model_ops *model_ops;
748         int num_interfaces;
749         TALLOC_CTX *tmp_ctx = talloc_new(dns);
750         NTSTATUS status;
751         int i;
752
753         /* within the dns task we want to be a single process, so
754            ask for the single process model ops and pass these to the
755            stream_setup_socket() call. */
756         model_ops = process_model_startup(dns->task->event_ctx, "single");
757         if (!model_ops) {
758                 DEBUG(0,("Can't find 'single' process model_ops\n"));
759                 return NT_STATUS_INTERNAL_ERROR;
760         }
761
762         num_interfaces = iface_count(ifaces);
763
764         for (i=0; i<num_interfaces; i++) {
765                 const char *address = talloc_strdup(tmp_ctx, iface_n_ip(ifaces, i));
766
767                 status = dns_add_socket(dns, model_ops, "dns", address, DNS_SERVICE_PORT);
768                 NT_STATUS_NOT_OK_RETURN(status);
769         }
770
771         talloc_free(tmp_ctx);
772
773         return NT_STATUS_OK;
774 }
775
776 static int dns_server_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
777 {
778         const char *n1, *n2;
779         size_t l1, l2;
780
781         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
782         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
783
784         l1 = strlen(n1);
785         l2 = strlen(n2);
786
787         /* If the string lengths are not equal just sort by length */
788         if (l1 != l2) {
789                 /* If m1 is the larger zone name, return it first */
790                 return l2 - l1;
791         }
792
793         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
794         return 0;
795 }
796
797 static void dns_task_init(struct task_server *task)
798 {
799         struct dns_server *dns;
800         NTSTATUS status;
801         struct interface *ifaces;
802         int ret;
803         struct ldb_result *res;
804         struct ldb_dn *rootdn;
805         static const char * const attrs[] = { "name", NULL};
806         int i;
807
808
809         switch (lpcfg_server_role(task->lp_ctx)) {
810         case ROLE_STANDALONE:
811                 task_server_terminate(task, "dns: no DNS required in standalone configuration", false);
812                 return;
813         case ROLE_DOMAIN_MEMBER:
814                 task_server_terminate(task, "dns: no DNS required in member server configuration", false);
815                 return;
816         case ROLE_DOMAIN_CONTROLLER:
817                 /* Yes, we want a DNS */
818                 break;
819         }
820
821         load_interfaces(task, lpcfg_interfaces(task->lp_ctx), &ifaces);
822
823         if (iface_count(ifaces) == 0) {
824                 task_server_terminate(task, "dns: no network interfaces configured", false);
825                 return;
826         }
827
828         task_server_set_title(task, "task[dns]");
829
830         dns = talloc_zero(task, struct dns_server);
831         if (dns == NULL) {
832                 task_server_terminate(task, "dns: out of memory", true);
833                 return;
834         }
835
836         dns->task = task;
837
838         dns->samdb = samdb_connect(dns, dns->task->event_ctx, dns->task->lp_ctx,
839                               system_session(dns->task->lp_ctx), 0);
840         if (!dns->samdb) {
841                 task_server_terminate(task, "dns: samdb_connect failed", true);
842                 return;
843         }
844
845         rootdn = ldb_dn_new(dns, dns->samdb, "");
846         if (rootdn == NULL) {
847                 task_server_terminate(task, "dns: out of memory", true);
848                 return;
849         }
850
851         // TODO: this search does not work against windows
852         ret = dsdb_search(dns->samdb, dns, &res, rootdn, LDB_SCOPE_SUBTREE,
853                           attrs, DSDB_SEARCH_SEARCH_ALL_PARTITIONS, "(objectClass=dnsZone)");
854         if (ret != LDB_SUCCESS) {
855                 task_server_terminate(task,
856                                       "dns: failed to look up root DNS zones",
857                                       true);
858                 return;
859         }
860
861         TYPESAFE_QSORT(res->msgs, res->count, dns_server_sort_zones);
862
863         for (i=0; i < res->count; i++) {
864                 struct dns_server_zone *z;
865
866                 z = talloc_zero(dns, struct dns_server_zone);
867                 if (z == NULL) {
868                 }
869
870                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
871                 z->dn = talloc_move(z, &res->msgs[i]->dn);
872
873                 DLIST_ADD_END(dns->zones, z, NULL);
874         }
875
876         status = dns_startup_interfaces(dns, task->lp_ctx, ifaces);
877         if (!NT_STATUS_IS_OK(status)) {
878                 task_server_terminate(task, "dns failed to setup interfaces", true);
879                 return;
880         }
881 }
882
883 NTSTATUS server_service_dns_init(void)
884 {
885         return register_server_service("dns", dns_task_init);
886 }