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