s4-dns: Reload DNS zones from dsdb when zones are modified through RPC or DRS
[obnox/samba/samba-obnox.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 #include "lib/util/tevent_werror.h"
46 #include "auth/auth.h"
47 #include "auth/credentials/credentials.h"
48 #include "librpc/gen_ndr/ndr_irpc.h"
49 #include "lib/messaging/irpc.h"
50
51 #undef DBGC_CLASS
52 #define DBGC_CLASS DBGC_DNS
53
54 NTSTATUS server_service_dns_init(void);
55
56 /* hold information about one dns socket */
57 struct dns_socket {
58         struct dns_server *dns;
59         struct tsocket_address *local_address;
60 };
61
62 struct dns_udp_socket {
63         struct dns_socket *dns_socket;
64         struct tdgram_context *dgram;
65         struct tevent_queue *send_queue;
66 };
67
68 /*
69   state of an open tcp connection
70 */
71 struct dns_tcp_connection {
72         /* stream connection we belong to */
73         struct stream_connection *conn;
74
75         /* the dns_server the connection belongs to */
76         struct dns_socket *dns_socket;
77
78         struct tstream_context *tstream;
79
80         struct tevent_queue *send_queue;
81 };
82
83 static void dns_tcp_terminate_connection(struct dns_tcp_connection *dnsconn, const char *reason)
84 {
85         stream_terminate_connection(dnsconn->conn, reason);
86 }
87
88 static void dns_tcp_recv(struct stream_connection *conn, uint16_t flags)
89 {
90         struct dns_tcp_connection *dnsconn = talloc_get_type(conn->private_data,
91                                                              struct dns_tcp_connection);
92         /* this should never be triggered! */
93         dns_tcp_terminate_connection(dnsconn, "dns_tcp_recv: called");
94 }
95
96 static void dns_tcp_send(struct stream_connection *conn, uint16_t flags)
97 {
98         struct dns_tcp_connection *dnsconn = talloc_get_type(conn->private_data,
99                                                              struct dns_tcp_connection);
100         /* this should never be triggered! */
101         dns_tcp_terminate_connection(dnsconn, "dns_tcp_send: called");
102 }
103
104 struct dns_process_state {
105         DATA_BLOB *in;
106         struct dns_server *dns;
107         struct dns_name_packet in_packet;
108         struct dns_request_state state;
109         uint16_t dns_err;
110         struct dns_name_packet out_packet;
111         DATA_BLOB out;
112 };
113
114 static void dns_process_done(struct tevent_req *subreq);
115
116 static struct tevent_req *dns_process_send(TALLOC_CTX *mem_ctx,
117                                            struct tevent_context *ev,
118                                            struct dns_server *dns,
119                                            DATA_BLOB *in)
120 {
121         struct tevent_req *req, *subreq;
122         struct dns_process_state *state;
123         enum ndr_err_code ndr_err;
124         WERROR ret;
125         const char *forwarder = lpcfg_dns_forwarder(dns->task->lp_ctx);
126         req = tevent_req_create(mem_ctx, &state, struct dns_process_state);
127         if (req == NULL) {
128                 return NULL;
129         }
130         state->state.mem_ctx = state;
131         state->in = in;
132
133         state->dns = dns;
134
135         if (in->length < 12) {
136                 tevent_req_werror(req, WERR_INVALID_PARAM);
137                 return tevent_req_post(req, ev);
138         }
139         dump_data_dbgc(DBGC_DNS, 8, in->data, in->length);
140
141         ndr_err = ndr_pull_struct_blob(
142                 in, state, &state->in_packet,
143                 (ndr_pull_flags_fn_t)ndr_pull_dns_name_packet);
144
145         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
146                 state->dns_err = DNS_RCODE_FORMERR;
147                 tevent_req_done(req);
148                 return tevent_req_post(req, ev);
149         }
150         if (DEBUGLVLC(DBGC_DNS, 8)) {
151                 NDR_PRINT_DEBUGC(DBGC_DNS, dns_name_packet, &state->in_packet);
152         }
153
154         ret = dns_verify_tsig(dns, state, &state->state, &state->in_packet, in);
155         if (!W_ERROR_IS_OK(ret)) {
156                 DEBUG(1, ("Failed to verify TSIG!\n"));
157                 state->dns_err = werr_to_dns_err(ret);
158                 tevent_req_done(req);
159                 return tevent_req_post(req, ev);
160         }
161
162         if (state->in_packet.operation & DNS_FLAG_REPLY) {
163                 DEBUG(1, ("Won't reply to replies.\n"));
164                 tevent_req_werror(req, WERR_INVALID_PARAM);
165                 return tevent_req_post(req, ev);
166         }
167
168         state->state.flags = state->in_packet.operation;
169         state->state.flags |= DNS_FLAG_REPLY;
170
171         
172         if (forwarder && *forwarder) {
173                 state->state.flags |= DNS_FLAG_RECURSION_AVAIL;
174         }
175
176         state->out_packet = state->in_packet;
177
178         switch (state->in_packet.operation & DNS_OPCODE) {
179         case DNS_OPCODE_QUERY:
180                 subreq = dns_server_process_query_send(
181                         state, ev, dns, &state->state, &state->in_packet);
182                 if (tevent_req_nomem(subreq, req)) {
183                         return tevent_req_post(req, ev);
184                 }
185                 tevent_req_set_callback(subreq, dns_process_done, req);
186                 return req;
187         case DNS_OPCODE_UPDATE:
188                 ret = dns_server_process_update(
189                         dns, &state->state, state, &state->in_packet,
190                         &state->out_packet.answers, &state->out_packet.ancount,
191                         &state->out_packet.nsrecs,  &state->out_packet.nscount,
192                         &state->out_packet.additional,
193                         &state->out_packet.arcount);
194                 break;
195         default:
196                 ret = WERR_DNS_ERROR_RCODE_NOT_IMPLEMENTED;
197         }
198         if (!W_ERROR_IS_OK(ret)) {
199                 state->dns_err = werr_to_dns_err(ret);
200         }
201         tevent_req_done(req);
202         return tevent_req_post(req, ev);
203 }
204
205 static void dns_process_done(struct tevent_req *subreq)
206 {
207         struct tevent_req *req = tevent_req_callback_data(
208                 subreq, struct tevent_req);
209         struct dns_process_state *state = tevent_req_data(
210                 req, struct dns_process_state);
211         WERROR ret;
212
213         ret = dns_server_process_query_recv(
214                 subreq, state,
215                 &state->out_packet.answers, &state->out_packet.ancount,
216                 &state->out_packet.nsrecs,  &state->out_packet.nscount,
217                 &state->out_packet.additional, &state->out_packet.arcount);
218         TALLOC_FREE(subreq);
219
220         if (!W_ERROR_IS_OK(ret)) {
221                 state->dns_err = werr_to_dns_err(ret);
222         }
223         tevent_req_done(req);
224 }
225
226 static WERROR dns_process_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
227                                DATA_BLOB *out)
228 {
229         struct dns_process_state *state = tevent_req_data(
230                 req, struct dns_process_state);
231         enum ndr_err_code ndr_err;
232         WERROR ret;
233
234         if (tevent_req_is_werror(req, &ret)) {
235                 return ret;
236         }
237         if (state->dns_err != DNS_RCODE_OK) {
238                 goto drop;
239         }
240         state->out_packet.operation |= state->state.flags;
241
242         if (state->state.sign) {
243                 ret = dns_sign_tsig(state->dns, mem_ctx, &state->state,
244                                     &state->out_packet, 0);
245                 if (!W_ERROR_IS_OK(ret)) {
246                         state->dns_err = DNS_RCODE_SERVFAIL;
247                         goto drop;
248                 }
249         }
250
251         if (DEBUGLVLC(DBGC_DNS, 8)) {
252                 NDR_PRINT_DEBUGC(DBGC_DNS, dns_name_packet, &state->out_packet);
253         }
254
255         ndr_err = ndr_push_struct_blob(
256                 out, mem_ctx, &state->out_packet,
257                 (ndr_push_flags_fn_t)ndr_push_dns_name_packet);
258         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
259                 DEBUG(1, ("Failed to push packet: %s!\n",
260                           ndr_errstr(ndr_err)));
261                 state->dns_err = DNS_RCODE_SERVFAIL;
262                 goto drop;
263         }
264         return WERR_OK;
265
266 drop:
267         *out = data_blob_talloc(mem_ctx, state->in->data, state->in->length);
268         if (out->data == NULL) {
269                 return WERR_NOMEM;
270         }
271         out->data[2] |= 0x80; /* Toggle DNS_FLAG_REPLY */
272         out->data[3] |= state->dns_err;
273         return WERR_OK;
274 }
275
276 struct dns_tcp_call {
277         struct dns_tcp_connection *dns_conn;
278         DATA_BLOB in;
279         DATA_BLOB out;
280         uint8_t out_hdr[4];
281         struct iovec out_iov[2];
282 };
283
284 static void dns_tcp_call_process_done(struct tevent_req *subreq);
285 static void dns_tcp_call_writev_done(struct tevent_req *subreq);
286
287 static void dns_tcp_call_loop(struct tevent_req *subreq)
288 {
289         struct dns_tcp_connection *dns_conn = tevent_req_callback_data(subreq,
290                                       struct dns_tcp_connection);
291         struct dns_server *dns = dns_conn->dns_socket->dns;
292         struct dns_tcp_call *call;
293         NTSTATUS status;
294
295         call = talloc(dns_conn, struct dns_tcp_call);
296         if (call == NULL) {
297                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
298                                 "no memory for dns_tcp_call");
299                 return;
300         }
301         call->dns_conn = dns_conn;
302
303         status = tstream_read_pdu_blob_recv(subreq,
304                                             call,
305                                             &call->in);
306         TALLOC_FREE(subreq);
307         if (!NT_STATUS_IS_OK(status)) {
308                 const char *reason;
309
310                 reason = talloc_asprintf(call, "dns_tcp_call_loop: "
311                                          "tstream_read_pdu_blob_recv() - %s",
312                                          nt_errstr(status));
313                 if (!reason) {
314                         reason = nt_errstr(status);
315                 }
316
317                 dns_tcp_terminate_connection(dns_conn, reason);
318                 return;
319         }
320
321         DEBUG(10,("Received DNS TCP packet of length %lu from %s\n",
322                  (long) call->in.length,
323                  tsocket_address_string(dns_conn->conn->remote_address, call)));
324
325         /* skip length header */
326         call->in.data += 2;
327         call->in.length -= 2;
328
329         subreq = dns_process_send(call, dns->task->event_ctx, dns,
330                                   &call->in);
331         if (subreq == NULL) {
332                 dns_tcp_terminate_connection(
333                         dns_conn, "dns_tcp_call_loop: dns_process_send "
334                         "failed\n");
335                 return;
336         }
337         tevent_req_set_callback(subreq, dns_tcp_call_process_done, call);
338
339         /*
340          * The dns tcp pdu's has the length as 2 byte (initial_read_size),
341          * packet_full_request_u16 provides the pdu length then.
342          */
343         subreq = tstream_read_pdu_blob_send(dns_conn,
344                                             dns_conn->conn->event.ctx,
345                                             dns_conn->tstream,
346                                             2, /* initial_read_size */
347                                             packet_full_request_u16,
348                                             dns_conn);
349         if (subreq == NULL) {
350                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
351                                 "no memory for tstream_read_pdu_blob_send");
352                 return;
353         }
354         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
355 }
356
357 static void dns_tcp_call_process_done(struct tevent_req *subreq)
358 {
359         struct dns_tcp_call *call = tevent_req_callback_data(subreq,
360                         struct dns_tcp_call);
361         struct dns_tcp_connection *dns_conn = call->dns_conn;
362         WERROR err;
363
364         err = dns_process_recv(subreq, call, &call->out);
365         TALLOC_FREE(subreq);
366         if (!W_ERROR_IS_OK(err)) {
367                 DEBUG(1, ("dns_process returned %s\n", win_errstr(err)));
368                 dns_tcp_terminate_connection(dns_conn,
369                                 "dns_tcp_call_loop: process function failed");
370                 return;
371         }
372
373         /* First add the length of the out buffer */
374         RSSVAL(call->out_hdr, 0, call->out.length);
375         call->out_iov[0].iov_base = (char *) call->out_hdr;
376         call->out_iov[0].iov_len = 2;
377
378         call->out_iov[1].iov_base = (char *) call->out.data;
379         call->out_iov[1].iov_len = call->out.length;
380
381         subreq = tstream_writev_queue_send(call,
382                                            dns_conn->conn->event.ctx,
383                                            dns_conn->tstream,
384                                            dns_conn->send_queue,
385                                            call->out_iov, 2);
386         if (subreq == NULL) {
387                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
388                                 "no memory for tstream_writev_queue_send");
389                 return;
390         }
391         tevent_req_set_callback(subreq, dns_tcp_call_writev_done, call);
392 }
393
394 static void dns_tcp_call_writev_done(struct tevent_req *subreq)
395 {
396         struct dns_tcp_call *call = tevent_req_callback_data(subreq,
397                         struct dns_tcp_call);
398         int sys_errno;
399         int rc;
400
401         rc = tstream_writev_queue_recv(subreq, &sys_errno);
402         TALLOC_FREE(subreq);
403         if (rc == -1) {
404                 const char *reason;
405
406                 reason = talloc_asprintf(call, "dns_tcp_call_writev_done: "
407                                          "tstream_writev_queue_recv() - %d:%s",
408                                          sys_errno, strerror(sys_errno));
409                 if (!reason) {
410                         reason = "dns_tcp_call_writev_done: tstream_writev_queue_recv() failed";
411                 }
412
413                 dns_tcp_terminate_connection(call->dns_conn, reason);
414                 return;
415         }
416
417         /* We don't care about errors */
418
419         talloc_free(call);
420 }
421
422 /*
423   called when we get a new connection
424 */
425 static void dns_tcp_accept(struct stream_connection *conn)
426 {
427         struct dns_socket *dns_socket;
428         struct dns_tcp_connection *dns_conn;
429         struct tevent_req *subreq;
430         int rc;
431
432         dns_conn = talloc_zero(conn, struct dns_tcp_connection);
433         if (dns_conn == NULL) {
434                 stream_terminate_connection(conn,
435                                 "dns_tcp_accept: out of memory");
436                 return;
437         }
438
439         dns_conn->send_queue = tevent_queue_create(conn, "dns_tcp_accept");
440         if (dns_conn->send_queue == NULL) {
441                 stream_terminate_connection(conn,
442                                 "dns_tcp_accept: out of memory");
443                 return;
444         }
445
446         dns_socket = talloc_get_type(conn->private_data, struct dns_socket);
447
448         TALLOC_FREE(conn->event.fde);
449
450         rc = tstream_bsd_existing_socket(dns_conn,
451                         socket_get_fd(conn->socket),
452                         &dns_conn->tstream);
453         if (rc < 0) {
454                 stream_terminate_connection(conn,
455                                 "dns_tcp_accept: out of memory");
456                 return;
457         }
458
459         dns_conn->conn = conn;
460         dns_conn->dns_socket = dns_socket;
461         conn->private_data = dns_conn;
462
463         /*
464          * The dns tcp pdu's has the length as 2 byte (initial_read_size),
465          * packet_full_request_u16 provides the pdu length then.
466          */
467         subreq = tstream_read_pdu_blob_send(dns_conn,
468                                             dns_conn->conn->event.ctx,
469                                             dns_conn->tstream,
470                                             2, /* initial_read_size */
471                                             packet_full_request_u16,
472                                             dns_conn);
473         if (subreq == NULL) {
474                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_accept: "
475                                 "no memory for tstream_read_pdu_blob_send");
476                 return;
477         }
478         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
479 }
480
481 static const struct stream_server_ops dns_tcp_stream_ops = {
482         .name                   = "dns_tcp",
483         .accept_connection      = dns_tcp_accept,
484         .recv_handler           = dns_tcp_recv,
485         .send_handler           = dns_tcp_send
486 };
487
488 struct dns_udp_call {
489         struct dns_udp_socket *sock;
490         struct tsocket_address *src;
491         DATA_BLOB in;
492         DATA_BLOB out;
493 };
494
495 static void dns_udp_call_process_done(struct tevent_req *subreq);
496 static void dns_udp_call_sendto_done(struct tevent_req *subreq);
497
498 static void dns_udp_call_loop(struct tevent_req *subreq)
499 {
500         struct dns_udp_socket *sock = tevent_req_callback_data(subreq,
501                                       struct dns_udp_socket);
502         struct dns_server *dns = sock->dns_socket->dns;
503         struct dns_udp_call *call;
504         uint8_t *buf;
505         ssize_t len;
506         int sys_errno;
507
508         call = talloc(sock, struct dns_udp_call);
509         if (call == NULL) {
510                 talloc_free(call);
511                 goto done;
512         }
513         call->sock = sock;
514
515         len = tdgram_recvfrom_recv(subreq, &sys_errno,
516                                    call, &buf, &call->src);
517         TALLOC_FREE(subreq);
518         if (len == -1) {
519                 talloc_free(call);
520                 goto done;
521         }
522
523         call->in.data = buf;
524         call->in.length = len;
525
526         DEBUG(10,("Received DNS UDP packet of length %lu from %s\n",
527                  (long)call->in.length,
528                  tsocket_address_string(call->src, call)));
529
530         subreq = dns_process_send(call, dns->task->event_ctx, dns,
531                                   &call->in);
532         if (subreq == NULL) {
533                 TALLOC_FREE(call);
534                 goto done;
535         }
536         tevent_req_set_callback(subreq, dns_udp_call_process_done, call);
537
538 done:
539         subreq = tdgram_recvfrom_send(sock,
540                                       sock->dns_socket->dns->task->event_ctx,
541                                       sock->dgram);
542         if (subreq == NULL) {
543                 task_server_terminate(sock->dns_socket->dns->task,
544                                       "no memory for tdgram_recvfrom_send",
545                                       true);
546                 return;
547         }
548         tevent_req_set_callback(subreq, dns_udp_call_loop, sock);
549 }
550
551 static void dns_udp_call_process_done(struct tevent_req *subreq)
552 {
553         struct dns_udp_call *call = tevent_req_callback_data(
554                 subreq, struct dns_udp_call);
555         struct dns_udp_socket *sock = call->sock;
556         struct dns_server *dns = sock->dns_socket->dns;
557         WERROR err;
558
559         err = dns_process_recv(subreq, call, &call->out);
560         TALLOC_FREE(subreq);
561         if (!W_ERROR_IS_OK(err)) {
562                 DEBUG(1, ("dns_process returned %s\n", win_errstr(err)));
563                 TALLOC_FREE(call);
564                 return;
565         }
566
567         subreq = tdgram_sendto_queue_send(call,
568                                           dns->task->event_ctx,
569                                           sock->dgram,
570                                           sock->send_queue,
571                                           call->out.data,
572                                           call->out.length,
573                                           call->src);
574         if (subreq == NULL) {
575                 talloc_free(call);
576                 return;
577         }
578         tevent_req_set_callback(subreq, dns_udp_call_sendto_done, call);
579
580 }
581 static void dns_udp_call_sendto_done(struct tevent_req *subreq)
582 {
583         struct dns_udp_call *call = tevent_req_callback_data(subreq,
584                                        struct dns_udp_call);
585         int sys_errno;
586
587         tdgram_sendto_queue_recv(subreq, &sys_errno);
588
589         /* We don't care about errors */
590
591         talloc_free(call);
592 }
593
594 /*
595   start listening on the given address
596 */
597 static NTSTATUS dns_add_socket(struct dns_server *dns,
598                                const struct model_ops *model_ops,
599                                const char *name,
600                                const char *address,
601                                uint16_t port)
602 {
603         struct dns_socket *dns_socket;
604         struct dns_udp_socket *dns_udp_socket;
605         struct tevent_req *udpsubreq;
606         NTSTATUS status;
607         int ret;
608
609         dns_socket = talloc(dns, struct dns_socket);
610         NT_STATUS_HAVE_NO_MEMORY(dns_socket);
611
612         dns_socket->dns = dns;
613
614         ret = tsocket_address_inet_from_strings(dns_socket, "ip",
615                                                 address, port,
616                                                 &dns_socket->local_address);
617         if (ret != 0) {
618                 status = map_nt_error_from_unix_common(errno);
619                 return status;
620         }
621
622         status = stream_setup_socket(dns->task,
623                                      dns->task->event_ctx,
624                                      dns->task->lp_ctx,
625                                      model_ops,
626                                      &dns_tcp_stream_ops,
627                                      "ip", address, &port,
628                                      lpcfg_socket_options(dns->task->lp_ctx),
629                                      dns_socket);
630         if (!NT_STATUS_IS_OK(status)) {
631                 DEBUG(0,("Failed to bind to %s:%u TCP - %s\n",
632                          address, port, nt_errstr(status)));
633                 talloc_free(dns_socket);
634                 return status;
635         }
636
637         dns_udp_socket = talloc(dns_socket, struct dns_udp_socket);
638         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket);
639
640         dns_udp_socket->dns_socket = dns_socket;
641
642         ret = tdgram_inet_udp_socket(dns_socket->local_address,
643                                      NULL,
644                                      dns_udp_socket,
645                                      &dns_udp_socket->dgram);
646         if (ret != 0) {
647                 status = map_nt_error_from_unix_common(errno);
648                 DEBUG(0,("Failed to bind to %s:%u UDP - %s\n",
649                          address, port, nt_errstr(status)));
650                 return status;
651         }
652
653         dns_udp_socket->send_queue = tevent_queue_create(dns_udp_socket,
654                                                          "dns_udp_send_queue");
655         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket->send_queue);
656
657         udpsubreq = tdgram_recvfrom_send(dns_udp_socket,
658                                          dns->task->event_ctx,
659                                          dns_udp_socket->dgram);
660         NT_STATUS_HAVE_NO_MEMORY(udpsubreq);
661         tevent_req_set_callback(udpsubreq, dns_udp_call_loop, dns_udp_socket);
662
663         return NT_STATUS_OK;
664 }
665
666 /*
667   setup our listening sockets on the configured network interfaces
668 */
669 static NTSTATUS dns_startup_interfaces(struct dns_server *dns,
670                                        struct interface *ifaces)
671 {
672         const struct model_ops *model_ops;
673         int num_interfaces;
674         TALLOC_CTX *tmp_ctx = talloc_new(dns);
675         NTSTATUS status;
676         int i;
677
678         /* within the dns task we want to be a single process, so
679            ask for the single process model ops and pass these to the
680            stream_setup_socket() call. */
681         model_ops = process_model_startup("single");
682         if (!model_ops) {
683                 DEBUG(0,("Can't find 'single' process model_ops\n"));
684                 return NT_STATUS_INTERNAL_ERROR;
685         }
686
687         if (ifaces != NULL) {
688                 num_interfaces = iface_list_count(ifaces);
689
690                 for (i=0; i<num_interfaces; i++) {
691                         const char *address = talloc_strdup(tmp_ctx,
692                                                             iface_list_n_ip(ifaces, i));
693
694                         status = dns_add_socket(dns, model_ops, "dns", address,
695                                                 DNS_SERVICE_PORT);
696                         NT_STATUS_NOT_OK_RETURN(status);
697                 }
698         } else {
699                 int num_binds = 0;
700                 char **wcard;
701                 wcard = iface_list_wildcard(tmp_ctx);
702                 if (wcard == NULL) {
703                         DEBUG(0, ("No wildcard address available\n"));
704                         return NT_STATUS_INTERNAL_ERROR;
705                 }
706                 for (i = 0; wcard[i] != NULL; i++) {
707                         status = dns_add_socket(dns, model_ops, "dns", wcard[i],
708                                                 DNS_SERVICE_PORT);
709                         if (NT_STATUS_IS_OK(status)) {
710                                 num_binds++;
711                         }
712                 }
713                 if (num_binds == 0) {
714                         talloc_free(tmp_ctx);
715                         return NT_STATUS_INVALID_PARAMETER_MIX;
716                 }
717         }
718
719         talloc_free(tmp_ctx);
720
721         return NT_STATUS_OK;
722 }
723
724 static int dns_server_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
725 {
726         const char *n1, *n2;
727         size_t l1, l2;
728
729         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
730         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
731
732         l1 = strlen(n1);
733         l2 = strlen(n2);
734
735         /* If the string lengths are not equal just sort by length */
736         if (l1 != l2) {
737                 /* If m1 is the larger zone name, return it first */
738                 return l2 - l1;
739         }
740
741         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
742         return 0;
743 }
744
745 static struct dns_server_tkey_store *tkey_store_init(TALLOC_CTX *mem_ctx,
746                                                      uint16_t size)
747 {
748         struct dns_server_tkey_store *buffer = talloc_zero(mem_ctx,
749                                                 struct dns_server_tkey_store);
750
751         if (buffer == NULL) {
752                 return NULL;
753         }
754
755         buffer->size = size;
756         buffer->next_idx = 0;
757
758         buffer->tkeys = talloc_zero_array(buffer, struct dns_server_tkey *, size);
759         if (buffer->tkeys == NULL) {
760                 TALLOC_FREE(buffer);
761         }
762
763         return buffer;
764 }
765
766 static NTSTATUS dns_server_reload_zones(struct dns_server *dns)
767 {
768         int ret;
769         static const char * const attrs[] = { "name", NULL};
770         struct ldb_result *res;
771         int i;
772         struct dns_server_zone *new_list = NULL;
773         struct dns_server_zone *old_list = NULL;
774         struct dns_server_zone *old_zone;
775
776         // TODO: this search does not work against windows
777         ret = dsdb_search(dns->samdb, dns, &res, NULL, LDB_SCOPE_SUBTREE,
778                           attrs, DSDB_SEARCH_SEARCH_ALL_PARTITIONS, "(objectClass=dnsZone)");
779         if (ret != LDB_SUCCESS) {
780                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
781         }
782
783         TYPESAFE_QSORT(res->msgs, res->count, dns_server_sort_zones);
784
785         for (i=0; i < res->count; i++) {
786                 struct dns_server_zone *z;
787
788                 z = talloc_zero(dns, struct dns_server_zone);
789                 if (z == NULL) {
790                         return NT_STATUS_NO_MEMORY;
791                 }
792
793                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
794                 z->dn = talloc_move(z, &res->msgs[i]->dn);
795                 /*
796                  * Ignore the RootDNSServers zone and zones that we don't support yet
797                  * RootDNSServers should never be returned (Windows DNS server don't)
798                  * ..TrustAnchors should never be returned as is, (Windows returns
799                  * TrustAnchors) and for the moment we don't support DNSSEC so we'd better
800                  * not return this zone.
801                  */
802                 if ((strcmp(z->name, "RootDNSServers") == 0) ||
803                     (strcmp(z->name, "..TrustAnchors") == 0))
804                 {
805                         DEBUG(10, ("Ignoring zone %s\n", z->name));
806                         talloc_free(z);
807                         continue;
808                 }
809                 DLIST_ADD_END(new_list, z, NULL);
810         }
811
812         old_list = dns->zones;
813         dns->zones = new_list;
814         while ((old_zone = DLIST_TAIL(old_list)) != NULL) {
815                 DLIST_REMOVE(old_list, old_zone);
816                 talloc_free(old_zone);
817         }
818
819         return NT_STATUS_OK;
820 }
821
822 /**
823  * Called when the internal DNS server should reload the zones from DB, for
824  * example, when zones are added or deleted through RPC or replicated by
825  * inbound DRS.
826  */
827 static NTSTATUS dns_reload_zones(struct irpc_message *msg,
828                                  struct dnssrv_reload_dns_zones *r)
829 {
830         struct dns_server *dns;
831
832         dns = talloc_get_type(msg->private_data, struct dns_server);
833         if (dns == NULL) {
834                 r->out.result = NT_STATUS_INTERNAL_ERROR;
835                 return NT_STATUS_INTERNAL_ERROR;
836         }
837
838         r->out.result = dns_server_reload_zones(dns);
839
840         return NT_STATUS_OK;
841 }
842
843 static void dns_task_init(struct task_server *task)
844 {
845         struct dns_server *dns;
846         NTSTATUS status;
847         struct interface *ifaces = NULL;
848         int ret;
849         static const char * const attrs_none[] = { NULL};
850         struct ldb_message *dns_acc;
851         char *hostname_lower;
852         char *dns_spn;
853
854         switch (lpcfg_server_role(task->lp_ctx)) {
855         case ROLE_STANDALONE:
856                 task_server_terminate(task, "dns: no DNS required in standalone configuration", false);
857                 return;
858         case ROLE_DOMAIN_MEMBER:
859                 task_server_terminate(task, "dns: no DNS required in member server configuration", false);
860                 return;
861         case ROLE_ACTIVE_DIRECTORY_DC:
862                 /* Yes, we want a DNS */
863                 break;
864         }
865
866         if (lpcfg_interfaces(task->lp_ctx) && lpcfg_bind_interfaces_only(task->lp_ctx)) {
867                 load_interface_list(task, task->lp_ctx, &ifaces);
868
869                 if (iface_list_count(ifaces) == 0) {
870                         task_server_terminate(task, "dns: no network interfaces configured", false);
871                         return;
872                 }
873         }
874
875         task_server_set_title(task, "task[dns]");
876
877         dns = talloc_zero(task, struct dns_server);
878         if (dns == NULL) {
879                 task_server_terminate(task, "dns: out of memory", true);
880                 return;
881         }
882
883         dns->task = task;
884         /*FIXME: Make this a configurable option */
885         dns->max_payload = 4096;
886
887         dns->server_credentials = cli_credentials_init(dns);
888         if (!dns->server_credentials) {
889                 task_server_terminate(task, "Failed to init server credentials\n", true);
890                 return;
891         }
892
893         dns->samdb = samdb_connect(dns, dns->task->event_ctx, dns->task->lp_ctx,
894                               system_session(dns->task->lp_ctx), 0);
895         if (!dns->samdb) {
896                 task_server_terminate(task, "dns: samdb_connect failed", true);
897                 return;
898         }
899
900         cli_credentials_set_conf(dns->server_credentials, task->lp_ctx);
901
902         hostname_lower = strlower_talloc(dns, lpcfg_netbios_name(task->lp_ctx));
903         dns_spn = talloc_asprintf(dns, "DNS/%s.%s",
904                                   hostname_lower,
905                                   lpcfg_dnsdomain(task->lp_ctx));
906         TALLOC_FREE(hostname_lower);
907
908         ret = dsdb_search_one(dns->samdb, dns, &dns_acc,
909                               ldb_get_default_basedn(dns->samdb), LDB_SCOPE_SUBTREE,
910                               attrs_none, 0, "(servicePrincipalName=%s)",
911                               dns_spn);
912         if (ret == LDB_SUCCESS) {
913                 TALLOC_FREE(dns_acc);
914                 if (!dns_spn) {
915                         task_server_terminate(task, "dns: talloc_asprintf failed", true);
916                         return;
917                 }
918                 status = cli_credentials_set_stored_principal(dns->server_credentials, task->lp_ctx, dns_spn);
919                 if (!NT_STATUS_IS_OK(status)) {
920                         task_server_terminate(task,
921                                               talloc_asprintf(task, "Failed to obtain server credentials for DNS, "
922                                                               "despite finding it in the samdb! %s\n",
923                                                               nt_errstr(status)),
924                                               true);
925                         return;
926                 }
927         } else {
928                 TALLOC_FREE(dns_spn);
929                 status = cli_credentials_set_machine_account(dns->server_credentials, task->lp_ctx);
930                 if (!NT_STATUS_IS_OK(status)) {
931                         task_server_terminate(task,
932                                               talloc_asprintf(task, "Failed to obtain server credentials, perhaps a standalone server?: %s\n",
933                                                               nt_errstr(status)),
934                                               true);
935                         return;
936                 }
937         }
938
939         dns->tkeys = tkey_store_init(dns, TKEY_BUFFER_SIZE);
940         if (!dns->tkeys) {
941                 task_server_terminate(task, "Failed to allocate tkey storage\n", true);
942                 return;
943         }
944
945         status = dns_server_reload_zones(dns);
946         if (!NT_STATUS_IS_OK(status)) {
947                 task_server_terminate(task, "dns: failed to load DNS zones", true);
948                 return;
949         }
950
951         status = dns_startup_interfaces(dns, ifaces);
952         if (!NT_STATUS_IS_OK(status)) {
953                 task_server_terminate(task, "dns failed to setup interfaces", true);
954                 return;
955         }
956
957         /* Setup the IRPC interface and register handlers */
958         status = irpc_add_name(task->msg_ctx, "dnssrv");
959         if (!NT_STATUS_IS_OK(status)) {
960                 task_server_terminate(task, "dns: failed to register IRPC name", true);
961                 return;
962         }
963
964         status = IRPC_REGISTER(task->msg_ctx, irpc, DNSSRV_RELOAD_DNS_ZONES,
965                                dns_reload_zones, dns);
966         if (!NT_STATUS_IS_OK(status)) {
967                 task_server_terminate(task, "dns: failed to setup reload handler", true);
968                 return;
969         }
970 }
971
972 NTSTATUS server_service_dns_init(void)
973 {
974         return register_server_service("dns", dns_task_init);
975 }