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