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