s4 dns: Parse srv and soa records
[sfrench/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         case DNS_QTYPE_SRV:
279                 for (ri = 0; ri < el->num_values; ri++) {
280                         if (recs[ri].wType != question->question_type) {
281                                 continue;
282                         }
283
284                         ZERO_STRUCT(ans[ai]);
285                         ans[ai].name = question->name;
286                         ans[ai].rr_type = DNS_QTYPE_SRV;
287                         ans[ai].rr_class = DNS_QCLASS_IP;
288                         ans[ai].ttl = recs[ri].dwTtlSeconds;
289                         ans[ai].rdata.srv_record.priority = recs[ri].data.srv.wPriority;
290                         ans[ai].rdata.srv_record.weight = recs[ri].data.srv.wWeight;
291                         ans[ai].rdata.srv_record.port = recs[ri].data.srv.wPort;
292                         ans[ai].rdata.srv_record.target = recs[ri].data.srv.nameTarget;
293                         ai++;
294                 }
295                 break;
296         case DNS_QTYPE_SOA:
297                 for (ri = 0; ri < el->num_values; ri++) {
298                         if (recs[ri].wType != question->question_type) {
299                                 continue;
300                         }
301
302                         ZERO_STRUCT(ans[ai]);
303                         ans[ai].name = question->name;
304                         ans[ai].rr_type = DNS_QTYPE_SOA;
305                         ans[ai].rr_class = DNS_QCLASS_IP;
306                         ans[ai].ttl = recs[ri].dwTtlSeconds;
307                         ans[ai].rdata.soa_record.mname  = recs[ri].data.soa.mname;
308                         ans[ai].rdata.soa_record.rname  = recs[ri].data.soa.rname;
309                         ans[ai].rdata.soa_record.serial = recs[ri].data.soa.serial;
310                         ans[ai].rdata.soa_record.refresh= recs[ri].data.soa.refresh;
311                         ans[ai].rdata.soa_record.retry  = recs[ri].data.soa.retry;
312                         ans[ai].rdata.soa_record.expire = recs[ri].data.soa.expire;
313                         ans[ai].rdata.soa_record.minimum= recs[ri].data.soa.minimum;
314                         ai++;
315                 }
316                 break;
317         default:
318                 return NT_STATUS_NOT_IMPLEMENTED;
319         }
320
321         *ancount = ai;
322         *answers = ans;
323
324         return NT_STATUS_OK;
325
326 }
327
328 static NTSTATUS compute_reply(struct dns_server *dns,
329                               TALLOC_CTX *mem_ctx,
330                               struct dns_name_packet *in,
331                               struct dns_res_rec **answers,    uint16_t *ancount,
332                               struct dns_res_rec **nsrecs,     uint16_t *nscount,
333                               struct dns_res_rec **additional, uint16_t *arcount)
334 {
335         uint16_t num_answers=0;
336         struct dns_res_rec *ans=NULL;
337         int i;
338         NTSTATUS status;
339
340         ans = talloc_array(mem_ctx, struct dns_res_rec, 0);
341         if (answers == NULL) return NT_STATUS_NO_MEMORY;
342
343         for (i = 0; i < in->qdcount; ++i) {
344                 status = handle_question(dns, mem_ctx, &in->questions[i], &ans, &num_answers);
345                 NT_STATUS_NOT_OK_RETURN(status);
346         }
347
348         *answers = ans;
349         *ancount = num_answers;
350
351         /*FIXME: Do something for these */
352         *nsrecs  = NULL;
353         *nscount = 0;
354
355         *additional = NULL;
356         *arcount    = 0;
357
358         return NT_STATUS_OK;
359 }
360
361 static NTSTATUS dns_process(struct dns_server *dns,
362                             TALLOC_CTX *mem_ctx,
363                             DATA_BLOB *in,
364                             DATA_BLOB *out)
365 {
366         enum ndr_err_code ndr_err;
367         NTSTATUS ret;
368         struct dns_name_packet *in_packet = talloc_zero(mem_ctx, struct dns_name_packet);
369         struct dns_name_packet *out_packet = talloc_zero(mem_ctx, struct dns_name_packet);
370         struct dns_res_rec *answers, *nsrecs, *additional;
371         uint16_t num_answers, num_nsrecs, num_additional;
372
373         if (in_packet == NULL) return NT_STATUS_INVALID_PARAMETER;
374
375         dump_data(2, in->data, in->length);
376
377         ndr_err = ndr_pull_struct_blob(in, in_packet, in_packet,
378                         (ndr_pull_flags_fn_t)ndr_pull_dns_name_packet);
379         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
380                 TALLOC_FREE(in_packet);
381                 DEBUG(0, ("Failed to parse packet %d!\n", ndr_err));
382                 return NT_STATUS_COULD_NOT_INTERPRET;
383         }
384
385         NDR_PRINT_DEBUG(dns_name_packet, in_packet);
386         out_packet->id = in_packet->id;
387         out_packet->operation = DNS_FLAG_REPLY | DNS_FLAG_AUTHORITATIVE |
388                                 DNS_FLAG_RECURSION_DESIRED | DNS_FLAG_RECURSION_AVAIL;
389
390         out_packet->qdcount = in_packet->qdcount;
391         out_packet->questions = in_packet->questions;
392
393         out_packet->ancount = 0;
394         out_packet->answers = NULL;
395
396         out_packet->nscount = 0;
397         out_packet->nsrecs  = NULL;
398
399         out_packet->arcount = 0;
400         out_packet->additional = NULL;
401
402         ret = compute_reply(dns, out_packet, in_packet, &answers, &num_answers,
403                             &nsrecs, &num_nsrecs, &additional, &num_additional);
404
405         if (NT_STATUS_IS_OK(ret)) {
406                 out_packet->ancount = num_answers;
407                 out_packet->answers = answers;
408
409                 out_packet->nscount = num_nsrecs;
410                 out_packet->nsrecs  = nsrecs;
411
412                 out_packet->arcount = num_additional;
413                 out_packet->additional = additional;
414         }
415
416         NDR_PRINT_DEBUG(dns_name_packet, out_packet);
417         ndr_err = ndr_push_struct_blob(out, out_packet, out_packet,
418                         (ndr_push_flags_fn_t)ndr_push_dns_name_packet);
419         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
420                 TALLOC_FREE(in_packet);
421                 TALLOC_FREE(out_packet);
422                 DEBUG(0, ("Failed to push packet %d!\n", ndr_err));
423                 return NT_STATUS_INTERNAL_ERROR;
424         }
425
426         dump_data(2, out->data, out->length);
427         return NT_STATUS_OK;
428 }
429
430 struct dns_tcp_call {
431         struct dns_tcp_connection *dns_conn;
432         DATA_BLOB in;
433         DATA_BLOB out;
434         uint8_t out_hdr[4];
435         struct iovec out_iov[2];
436 };
437
438 static void dns_tcp_call_writev_done(struct tevent_req *subreq);
439
440 static void dns_tcp_call_loop(struct tevent_req *subreq)
441 {
442         struct dns_tcp_connection *dns_conn = tevent_req_callback_data(subreq,
443                                       struct dns_tcp_connection);
444         struct dns_tcp_call *call;
445         NTSTATUS status;
446
447         call = talloc(dns_conn, struct dns_tcp_call);
448         if (call == NULL) {
449                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
450                                 "no memory for dns_tcp_call");
451                 return;
452         }
453         call->dns_conn = dns_conn;
454
455         status = tstream_read_pdu_blob_recv(subreq,
456                                             call,
457                                             &call->in);
458         TALLOC_FREE(subreq);
459         if (!NT_STATUS_IS_OK(status)) {
460                 const char *reason;
461
462                 reason = talloc_asprintf(call, "dns_tcp_call_loop: "
463                                          "tstream_read_pdu_blob_recv() - %s",
464                                          nt_errstr(status));
465                 if (!reason) {
466                         reason = nt_errstr(status);
467                 }
468
469                 dns_tcp_terminate_connection(dns_conn, reason);
470                 return;
471         }
472
473         DEBUG(10,("Received krb5 TCP packet of length %lu from %s\n",
474                  (long) call->in.length,
475                  tsocket_address_string(dns_conn->conn->remote_address, call)));
476
477         /* skip length header */
478         call->in.data +=4;
479         call->in.length -= 4;
480
481         /* Call dns */
482         status = dns_process(dns_conn->dns_socket->dns, call, &call->in, &call->out);
483         if (!NT_STATUS_IS_OK(status)) {
484                 DEBUG(0, ("dns_process returned %s\n", nt_errstr(status)));
485                 dns_tcp_terminate_connection(dns_conn,
486                                 "dns_tcp_call_loop: process function failed");
487                 return;
488         }
489
490         /* First add the length of the out buffer */
491         RSIVAL(call->out_hdr, 0, call->out.length);
492         call->out_iov[0].iov_base = (char *) call->out_hdr;
493         call->out_iov[0].iov_len = 4;
494
495         call->out_iov[1].iov_base = (char *) call->out.data;
496         call->out_iov[1].iov_len = call->out.length;
497
498         subreq = tstream_writev_queue_send(call,
499                                            dns_conn->conn->event.ctx,
500                                            dns_conn->tstream,
501                                            dns_conn->send_queue,
502                                            call->out_iov, 2);
503         if (subreq == NULL) {
504                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
505                                 "no memory for tstream_writev_queue_send");
506                 return;
507         }
508         tevent_req_set_callback(subreq, dns_tcp_call_writev_done, call);
509
510         /*
511          * The krb5 tcp pdu's has the length as 4 byte (initial_read_size),
512          * packet_full_request_u32 provides the pdu length then.
513          */
514         subreq = tstream_read_pdu_blob_send(dns_conn,
515                                             dns_conn->conn->event.ctx,
516                                             dns_conn->tstream,
517                                             4, /* initial_read_size */
518                                             packet_full_request_u32,
519                                             dns_conn);
520         if (subreq == NULL) {
521                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
522                                 "no memory for tstream_read_pdu_blob_send");
523                 return;
524         }
525         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
526 }
527
528 static void dns_tcp_call_writev_done(struct tevent_req *subreq)
529 {
530         struct dns_tcp_call *call = tevent_req_callback_data(subreq,
531                         struct dns_tcp_call);
532         int sys_errno;
533         int rc;
534
535         rc = tstream_writev_queue_recv(subreq, &sys_errno);
536         TALLOC_FREE(subreq);
537         if (rc == -1) {
538                 const char *reason;
539
540                 reason = talloc_asprintf(call, "dns_tcp_call_writev_done: "
541                                          "tstream_writev_queue_recv() - %d:%s",
542                                          sys_errno, strerror(sys_errno));
543                 if (!reason) {
544                         reason = "dns_tcp_call_writev_done: tstream_writev_queue_recv() failed";
545                 }
546
547                 dns_tcp_terminate_connection(call->dns_conn, reason);
548                 return;
549         }
550
551         /* We don't care about errors */
552
553         talloc_free(call);
554 }
555
556 /*
557   called when we get a new connection
558 */
559 static void dns_tcp_accept(struct stream_connection *conn)
560 {
561         struct dns_socket *dns_socket;
562         struct dns_tcp_connection *dns_conn;
563         struct tevent_req *subreq;
564         int rc;
565
566         dns_conn = talloc_zero(conn, struct dns_tcp_connection);
567         if (dns_conn == NULL) {
568                 stream_terminate_connection(conn,
569                                 "dns_tcp_accept: out of memory");
570                 return;
571         }
572
573         dns_conn->send_queue = tevent_queue_create(conn, "dns_tcp_accept");
574         if (dns_conn->send_queue == NULL) {
575                 stream_terminate_connection(conn,
576                                 "dns_tcp_accept: out of memory");
577                 return;
578         }
579
580         dns_socket = talloc_get_type(conn->private_data, struct dns_socket);
581
582         TALLOC_FREE(conn->event.fde);
583
584         rc = tstream_bsd_existing_socket(dns_conn,
585                         socket_get_fd(conn->socket),
586                         &dns_conn->tstream);
587         if (rc < 0) {
588                 stream_terminate_connection(conn,
589                                 "dns_tcp_accept: out of memory");
590                 return;
591         }
592
593         dns_conn->conn = conn;
594         dns_conn->dns_socket = dns_socket;
595         conn->private_data = dns_conn;
596
597         /*
598          * The krb5 tcp pdu's has the length as 4 byte (initial_read_size),
599          * packet_full_request_u32 provides the pdu length then.
600          */
601         subreq = tstream_read_pdu_blob_send(dns_conn,
602                                             dns_conn->conn->event.ctx,
603                                             dns_conn->tstream,
604                                             4, /* initial_read_size */
605                                             packet_full_request_u32,
606                                             dns_conn);
607         if (subreq == NULL) {
608                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_accept: "
609                                 "no memory for tstream_read_pdu_blob_send");
610                 return;
611         }
612         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
613 }
614
615 static const struct stream_server_ops dns_tcp_stream_ops = {
616         .name                   = "dns_tcp",
617         .accept_connection      = dns_tcp_accept,
618         .recv_handler           = dns_tcp_recv,
619         .send_handler           = dns_tcp_send
620 };
621
622 struct dns_udp_call {
623         struct tsocket_address *src;
624         DATA_BLOB in;
625         DATA_BLOB out;
626 };
627
628 static void dns_udp_call_sendto_done(struct tevent_req *subreq);
629
630 static void dns_udp_call_loop(struct tevent_req *subreq)
631 {
632         struct dns_udp_socket *sock = tevent_req_callback_data(subreq,
633                                       struct dns_udp_socket);
634         struct dns_udp_call *call;
635         uint8_t *buf;
636         ssize_t len;
637         int sys_errno;
638         NTSTATUS status;
639
640         call = talloc(sock, struct dns_udp_call);
641         if (call == NULL) {
642                 talloc_free(call);
643                 goto done;
644         }
645
646         len = tdgram_recvfrom_recv(subreq, &sys_errno,
647                                    call, &buf, &call->src);
648         TALLOC_FREE(subreq);
649         if (len == -1) {
650                 talloc_free(call);
651                 goto done;
652         }
653
654         call->in.data = buf;
655         call->in.length = len;
656
657         DEBUG(10,("Received krb5 UDP packet of length %lu from %s\n",
658                  (long)call->in.length,
659                  tsocket_address_string(call->src, call)));
660
661         /* Call krb5 */
662         status = dns_process(sock->dns_socket->dns, call, &call->in, &call->out);
663         if (!NT_STATUS_IS_OK(status)) {
664                 talloc_free(call);
665                 DEBUG(0, ("dns_process returned %s\n", nt_errstr(status)));
666                 goto done;
667         }
668
669         subreq = tdgram_sendto_queue_send(call,
670                                           sock->dns_socket->dns->task->event_ctx,
671                                           sock->dgram,
672                                           sock->send_queue,
673                                           call->out.data,
674                                           call->out.length,
675                                           call->src);
676         if (subreq == NULL) {
677                 talloc_free(call);
678                 goto done;
679         }
680         tevent_req_set_callback(subreq, dns_udp_call_sendto_done, call);
681
682 done:
683         subreq = tdgram_recvfrom_send(sock,
684                                       sock->dns_socket->dns->task->event_ctx,
685                                       sock->dgram);
686         if (subreq == NULL) {
687                 task_server_terminate(sock->dns_socket->dns->task,
688                                       "no memory for tdgram_recvfrom_send",
689                                       true);
690                 return;
691         }
692         tevent_req_set_callback(subreq, dns_udp_call_loop, sock);
693 }
694
695 static void dns_udp_call_sendto_done(struct tevent_req *subreq)
696 {
697         struct dns_udp_call *call = tevent_req_callback_data(subreq,
698                                        struct dns_udp_call);
699         ssize_t ret;
700         int sys_errno;
701
702         ret = tdgram_sendto_queue_recv(subreq, &sys_errno);
703
704         /* We don't care about errors */
705
706         talloc_free(call);
707 }
708
709 /*
710   start listening on the given address
711 */
712 static NTSTATUS dns_add_socket(struct dns_server *dns,
713                                const struct model_ops *model_ops,
714                                const char *name,
715                                const char *address,
716                                uint16_t port)
717 {
718         struct dns_socket *dns_socket;
719         struct dns_udp_socket *dns_udp_socket;
720         struct tevent_req *udpsubreq;
721         NTSTATUS status;
722         int ret;
723
724         dns_socket = talloc(dns, struct dns_socket);
725         NT_STATUS_HAVE_NO_MEMORY(dns_socket);
726
727         dns_socket->dns = dns;
728
729         ret = tsocket_address_inet_from_strings(dns_socket, "ip",
730                                                 address, port,
731                                                 &dns_socket->local_address);
732         if (ret != 0) {
733                 status = map_nt_error_from_unix(errno);
734                 return status;
735         }
736
737         status = stream_setup_socket(dns->task->event_ctx,
738                                      dns->task->lp_ctx,
739                                      model_ops,
740                                      &dns_tcp_stream_ops,
741                                      "ip", address, &port,
742                                      lpcfg_socket_options(dns->task->lp_ctx),
743                                      dns_socket);
744         if (!NT_STATUS_IS_OK(status)) {
745                 DEBUG(0,("Failed to bind to %s:%u TCP - %s\n",
746                          address, port, nt_errstr(status)));
747                 talloc_free(dns_socket);
748                 return status;
749         }
750
751         dns_udp_socket = talloc(dns_socket, struct dns_udp_socket);
752         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket);
753
754         dns_udp_socket->dns_socket = dns_socket;
755
756         ret = tdgram_inet_udp_socket(dns_socket->local_address,
757                                      NULL,
758                                      dns_udp_socket,
759                                      &dns_udp_socket->dgram);
760         if (ret != 0) {
761                 status = map_nt_error_from_unix(errno);
762                 DEBUG(0,("Failed to bind to %s:%u UDP - %s\n",
763                          address, port, nt_errstr(status)));
764                 return status;
765         }
766
767         dns_udp_socket->send_queue = tevent_queue_create(dns_udp_socket,
768                                                          "dns_udp_send_queue");
769         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket->send_queue);
770
771         udpsubreq = tdgram_recvfrom_send(dns_udp_socket,
772                                          dns->task->event_ctx,
773                                          dns_udp_socket->dgram);
774         NT_STATUS_HAVE_NO_MEMORY(udpsubreq);
775         tevent_req_set_callback(udpsubreq, dns_udp_call_loop, dns_udp_socket);
776
777         return NT_STATUS_OK;
778 }
779
780 /*
781   setup our listening sockets on the configured network interfaces
782 */
783 static NTSTATUS dns_startup_interfaces(struct dns_server *dns, struct loadparm_context *lp_ctx,
784                                        struct interface *ifaces)
785 {
786         const struct model_ops *model_ops;
787         int num_interfaces;
788         TALLOC_CTX *tmp_ctx = talloc_new(dns);
789         NTSTATUS status;
790         int i;
791
792         /* within the dns task we want to be a single process, so
793            ask for the single process model ops and pass these to the
794            stream_setup_socket() call. */
795         model_ops = process_model_startup(dns->task->event_ctx, "single");
796         if (!model_ops) {
797                 DEBUG(0,("Can't find 'single' process model_ops\n"));
798                 return NT_STATUS_INTERNAL_ERROR;
799         }
800
801         num_interfaces = iface_count(ifaces);
802
803         for (i=0; i<num_interfaces; i++) {
804                 const char *address = talloc_strdup(tmp_ctx, iface_n_ip(ifaces, i));
805
806                 status = dns_add_socket(dns, model_ops, "dns", address, DNS_SERVICE_PORT);
807                 NT_STATUS_NOT_OK_RETURN(status);
808         }
809
810         talloc_free(tmp_ctx);
811
812         return NT_STATUS_OK;
813 }
814
815 static int dns_server_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
816 {
817         const char *n1, *n2;
818         size_t l1, l2;
819
820         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
821         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
822
823         l1 = strlen(n1);
824         l2 = strlen(n2);
825
826         /* If the string lengths are not equal just sort by length */
827         if (l1 != l2) {
828                 /* If m1 is the larger zone name, return it first */
829                 return l2 - l1;
830         }
831
832         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
833         return 0;
834 }
835
836 static void dns_task_init(struct task_server *task)
837 {
838         struct dns_server *dns;
839         NTSTATUS status;
840         struct interface *ifaces;
841         int ret;
842         struct ldb_result *res;
843         struct ldb_dn *rootdn;
844         static const char * const attrs[] = { "name", NULL};
845         int i;
846
847
848         switch (lpcfg_server_role(task->lp_ctx)) {
849         case ROLE_STANDALONE:
850                 task_server_terminate(task, "dns: no DNS required in standalone configuration", false);
851                 return;
852         case ROLE_DOMAIN_MEMBER:
853                 task_server_terminate(task, "dns: no DNS required in member server configuration", false);
854                 return;
855         case ROLE_DOMAIN_CONTROLLER:
856                 /* Yes, we want a DNS */
857                 break;
858         }
859
860         load_interfaces(task, lpcfg_interfaces(task->lp_ctx), &ifaces);
861
862         if (iface_count(ifaces) == 0) {
863                 task_server_terminate(task, "dns: no network interfaces configured", false);
864                 return;
865         }
866
867         task_server_set_title(task, "task[dns]");
868
869         dns = talloc_zero(task, struct dns_server);
870         if (dns == NULL) {
871                 task_server_terminate(task, "dns: out of memory", true);
872                 return;
873         }
874
875         dns->task = task;
876
877         dns->samdb = samdb_connect(dns, dns->task->event_ctx, dns->task->lp_ctx,
878                               system_session(dns->task->lp_ctx), 0);
879         if (!dns->samdb) {
880                 task_server_terminate(task, "dns: samdb_connect failed", true);
881                 return;
882         }
883
884         rootdn = ldb_dn_new(dns, dns->samdb, "");
885         if (rootdn == NULL) {
886                 task_server_terminate(task, "dns: out of memory", true);
887                 return;
888         }
889
890         // TODO: this search does not work against windows
891         ret = dsdb_search(dns->samdb, dns, &res, rootdn, LDB_SCOPE_SUBTREE,
892                           attrs, DSDB_SEARCH_SEARCH_ALL_PARTITIONS, "(objectClass=dnsZone)");
893         if (ret != LDB_SUCCESS) {
894                 task_server_terminate(task,
895                                       "dns: failed to look up root DNS zones",
896                                       true);
897                 return;
898         }
899
900         TYPESAFE_QSORT(res->msgs, res->count, dns_server_sort_zones);
901
902         for (i=0; i < res->count; i++) {
903                 struct dns_server_zone *z;
904
905                 z = talloc_zero(dns, struct dns_server_zone);
906                 if (z == NULL) {
907                 }
908
909                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
910                 z->dn = talloc_move(z, &res->msgs[i]->dn);
911
912                 DLIST_ADD_END(dns->zones, z, NULL);
913         }
914
915         status = dns_startup_interfaces(dns, task->lp_ctx, ifaces);
916         if (!NT_STATUS_IS_OK(status)) {
917                 task_server_terminate(task, "dns failed to setup interfaces", true);
918                 return;
919         }
920 }
921
922 NTSTATUS server_service_dns_init(void)
923 {
924         return register_server_service("dns", dns_task_init);
925 }