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