s4 dns: Map between NTSTATUS and dns error codes
[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
46 /* hold information about one dns socket */
47 struct dns_socket {
48         struct dns_server *dns;
49         struct tsocket_address *local_address;
50 };
51
52 struct dns_udp_socket {
53         struct dns_socket *dns_socket;
54         struct tdgram_context *dgram;
55         struct tevent_queue *send_queue;
56 };
57
58 /*
59   state of an open tcp connection
60 */
61 struct dns_tcp_connection {
62         /* stream connection we belong to */
63         struct stream_connection *conn;
64
65         /* the dns_server the connection belongs to */
66         struct dns_socket *dns_socket;
67
68         struct tstream_context *tstream;
69
70         struct tevent_queue *send_queue;
71 };
72
73 static void dns_tcp_terminate_connection(struct dns_tcp_connection *dnsconn, const char *reason)
74 {
75         stream_terminate_connection(dnsconn->conn, reason);
76 }
77
78 static void dns_tcp_recv(struct stream_connection *conn, uint16_t flags)
79 {
80         struct dns_tcp_connection *dnsconn = talloc_get_type(conn->private_data,
81                                                              struct dns_tcp_connection);
82         /* this should never be triggered! */
83         dns_tcp_terminate_connection(dnsconn, "dns_tcp_recv: called");
84 }
85
86 static void dns_tcp_send(struct stream_connection *conn, uint16_t flags)
87 {
88         struct dns_tcp_connection *dnsconn = talloc_get_type(conn->private_data,
89                                                              struct dns_tcp_connection);
90         /* this should never be triggered! */
91         dns_tcp_terminate_connection(dnsconn, "dns_tcp_send: called");
92 }
93
94 static NTSTATUS dns_err_to_ntstatus(enum dns_rcode rcode)
95 {
96         switch (rcode) {
97         case DNS_RCODE_OK: return NT_STATUS_OK;
98         case DNS_RCODE_FORMERR: return NT_STATUS_INVALID_PARAMETER;
99         case DNS_RCODE_SERVFAIL: return NT_STATUS_INTERNAL_ERROR;
100         case DNS_RCODE_NXDOMAIN: return NT_STATUS_OBJECT_NAME_NOT_FOUND;
101         case DNS_RCODE_NOTIMP: return NT_STATUS_NOT_IMPLEMENTED;
102         case DNS_RCODE_REFUSED: return NT_STATUS_ACCESS_DENIED;
103         case DNS_RCODE_NOTAUTH: return NT_STATUS_FOOBAR;
104         default: return NT_STATUS_NONE_MAPPED;
105         }
106 }
107
108 static uint8_t ntstatus_to_dns_err(NTSTATUS status)
109 {
110         if (NT_STATUS_EQUAL(NT_STATUS_OK, status)) {
111                 return DNS_RCODE_OK;
112         } else if (NT_STATUS_EQUAL(NT_STATUS_INVALID_PARAMETER, status)) {
113                 return DNS_RCODE_FORMERR;
114         } else if (NT_STATUS_EQUAL(NT_STATUS_INTERNAL_ERROR, status)) {
115                 return DNS_RCODE_SERVFAIL;
116         } else if (NT_STATUS_EQUAL(NT_STATUS_OBJECT_NAME_NOT_FOUND, status)) {
117                 return DNS_RCODE_NXDOMAIN;
118         } else if (NT_STATUS_EQUAL(NT_STATUS_NOT_IMPLEMENTED, status)) {
119                 return DNS_RCODE_NOTIMP;
120         } else if (NT_STATUS_EQUAL(NT_STATUS_ACCESS_DENIED, status)) {
121                 return DNS_RCODE_REFUSED;
122         } else if (NT_STATUS_EQUAL(NT_STATUS_FOOBAR, status)) {
123                 return DNS_RCODE_NOTAUTH;
124         }
125         DEBUG(0, ("No mapping exists for %s\n", nt_errstr(status)));
126 }
127
128 static bool dns_name_match(const char *zone, const char *name, size_t *host_part_len)
129 {
130         size_t zl = strlen(zone);
131         size_t nl = strlen(name);
132         ssize_t zi, ni;
133         static const size_t fixup = 'a' - 'A';
134
135         if (zl > nl) {
136                 return false;
137         }
138
139         for (zi = zl, ni = nl; zi >= 0; zi--, ni--) {
140                 char zc = zone[zi];
141                 char nc = name[ni];
142
143                 /* convert to lower case */
144                 if (zc >= 'A' && zc <= 'Z') {
145                         zc += fixup;
146                 }
147                 if (nc >= 'A' && nc <= 'Z') {
148                         nc += fixup;
149                 }
150
151                 if (zc != nc) {
152                         return false;
153                 }
154         }
155
156         if (ni >= 0) {
157                 if (name[ni] != '.') {
158                         return false;
159                 }
160
161                 ni--;
162         }
163
164         *host_part_len = ni+1;
165
166         return true;
167 }
168
169 static NTSTATUS dns_name2dn(struct dns_server *dns,
170                             TALLOC_CTX *mem_ctx,
171                             const char *name,
172                             struct ldb_dn **_dn)
173 {
174         struct ldb_dn *base;
175         struct ldb_dn *dn;
176         const struct dns_server_zone *z;
177         size_t host_part_len = 0;
178
179         if (name == NULL) {
180                 return NT_STATUS_INVALID_PARAMETER;
181         }
182
183         /*TODO: Check if 'name' is a valid DNS name */
184
185         if (strcmp(name, "") == 0) {
186                 base = ldb_get_default_basedn(dns->samdb);
187                 dn = ldb_dn_copy(mem_ctx, base);
188                 ldb_dn_add_child_fmt(dn, "DC=@,DC=RootDNSServers,CN=MicrosoftDNS,CN=System");
189                 *_dn = dn;
190                 return NT_STATUS_OK;
191         }
192
193         for (z = dns->zones; z != NULL; z = z->next) {
194                 bool match;
195
196                 match = dns_name_match(z->name, name, &host_part_len);
197                 if (match) {
198                         break;
199                 }
200         }
201
202         if (z == NULL) {
203                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
204         }
205
206         if (host_part_len == 0) {
207                 dn = ldb_dn_copy(mem_ctx, z->dn);
208                 ldb_dn_add_child_fmt(dn, "DC=@");
209                 *_dn = dn;
210                 return NT_STATUS_OK;
211         }
212
213         dn = ldb_dn_copy(mem_ctx, z->dn);
214         ldb_dn_add_child_fmt(dn, "DC=%*.*s", (int)host_part_len, (int)host_part_len, name);
215         *_dn = dn;
216         return NT_STATUS_OK;
217 }
218
219 static NTSTATUS handle_question(struct dns_server *dns,
220                                 TALLOC_CTX *mem_ctx,
221                                 const struct dns_name_question *question,
222                                 struct dns_res_rec **answers, uint16_t *ancount)
223 {
224         struct dns_res_rec *ans;
225         struct ldb_dn *dn = NULL;
226         NTSTATUS status;
227         static const char * const attrs[] = { "dnsRecord", NULL};
228         int ret;
229         uint16_t ai = *ancount;
230         uint16_t ri;
231         struct ldb_message *msg = NULL;
232         struct dnsp_DnssrvRpcRecord *recs;
233         struct ldb_message_element *el;
234
235         status = dns_name2dn(dns, mem_ctx, question->name, &dn);
236         NT_STATUS_NOT_OK_RETURN(status);
237
238         ret = dsdb_search_one(dns->samdb, mem_ctx, &msg, dn,
239                               LDB_SCOPE_BASE, attrs, 0, "%s", "(objectClass=dnsNode)");
240         if (ret != LDB_SUCCESS) {
241                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
242         }
243
244         el = ldb_msg_find_element(msg, attrs[0]);
245         if (el == NULL) {
246                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
247         }
248
249         recs = talloc_array(mem_ctx, struct dnsp_DnssrvRpcRecord, el->num_values);
250         for (ri = 0; ri < el->num_values; ri++) {
251                 struct ldb_val *v = &el->values[ri];
252                 enum ndr_err_code ndr_err;
253
254                 ndr_err = ndr_pull_struct_blob(v, recs, &recs[ri],
255                                 (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
256                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
257                         DEBUG(0, ("Failed to grab dnsp_DnssrvRpcRecord\n"));
258                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
259                 }
260         }
261
262         ans = talloc_realloc(mem_ctx, *answers, struct dns_res_rec,
263                              ai + el->num_values);
264         NT_STATUS_HAVE_NO_MEMORY(ans);
265
266         switch (question->question_type) {
267         case DNS_QTYPE_CNAME:
268                 for (ri = 0; ri < el->num_values; ri++) {
269                         if (recs[ri].wType != question->question_type) {
270                                 continue;
271                         }
272
273                         ZERO_STRUCT(ans[ai]);
274                         ans[ai].name = talloc_strdup(ans, question->name);
275                         ans[ai].rr_type = DNS_QTYPE_CNAME;
276                         ans[ai].rr_class = DNS_QCLASS_IP;
277                         ans[ai].ttl = recs[ri].dwTtlSeconds;
278                         ans[ai].length = UINT16_MAX;
279                         ans[ai].rdata.cname_record = talloc_strdup(ans, recs[ri].data.cname);
280                         ai++;
281                 }
282                 break;
283         case DNS_QTYPE_A:
284                 for (ri = 0; ri < el->num_values; ri++) {
285                         if (recs[ri].wType != question->question_type) {
286                                 continue;
287                         }
288
289                         ZERO_STRUCT(ans[ai]);
290                         ans[ai].name = talloc_strdup(ans, question->name);
291                         ans[ai].rr_type = DNS_QTYPE_A;
292                         ans[ai].rr_class = DNS_QCLASS_IP;
293                         ans[ai].ttl = recs[ri].dwTtlSeconds;
294                         ans[ai].length = UINT16_MAX;
295                         ans[ai].rdata.ipv4_record = talloc_strdup(ans, recs[ri].data.ipv4);
296                         ai++;
297                 }
298                 break;
299         case DNS_QTYPE_AAAA:
300                 for (ri = 0; ri < el->num_values; ri++) {
301                         if (recs[ri].wType != question->question_type) {
302                                 continue;
303                         }
304
305                         ZERO_STRUCT(ans[ai]);
306                         ans[ai].name = talloc_strdup(ans, question->name);
307                         ans[ai].rr_type = DNS_QTYPE_AAAA;
308                         ans[ai].rr_class = DNS_QCLASS_IP;
309                         ans[ai].ttl = recs[ri].dwTtlSeconds;
310                         ans[ai].length = UINT16_MAX;
311                         ans[ai].rdata.ipv6_record = recs[ri].data.ipv6;
312                         ai++;
313                 }
314                 break;
315         case DNS_QTYPE_NS:
316                 for (ri = 0; ri < el->num_values; ri++) {
317                         if (recs[ri].wType != question->question_type) {
318                                 continue;
319                         }
320
321                         ZERO_STRUCT(ans[ai]);
322                         ans[ai].name = question->name;
323                         ans[ai].rr_type = DNS_QTYPE_NS;
324                         ans[ai].rr_class = DNS_QCLASS_IP;
325                         ans[ai].ttl = recs[ri].dwTtlSeconds;
326                         ans[ai].length = UINT16_MAX;
327                         ans[ai].rdata.ns_record = recs[ri].data.ns;
328                         ai++;
329                 }
330                 break;
331         case DNS_QTYPE_SRV:
332                 for (ri = 0; ri < el->num_values; ri++) {
333                         if (recs[ri].wType != question->question_type) {
334                                 continue;
335                         }
336
337                         ZERO_STRUCT(ans[ai]);
338                         ans[ai].name = question->name;
339                         ans[ai].rr_type = DNS_QTYPE_SRV;
340                         ans[ai].rr_class = DNS_QCLASS_IP;
341                         ans[ai].ttl = recs[ri].dwTtlSeconds;
342                         ans[ai].length = UINT16_MAX;
343                         ans[ai].rdata.srv_record.priority = recs[ri].data.srv.wPriority;
344                         ans[ai].rdata.srv_record.weight = recs[ri].data.srv.wWeight;
345                         ans[ai].rdata.srv_record.port = recs[ri].data.srv.wPort;
346                         ans[ai].rdata.srv_record.target = recs[ri].data.srv.nameTarget;
347                         ai++;
348                 }
349                 break;
350         case DNS_QTYPE_SOA:
351                 for (ri = 0; ri < el->num_values; ri++) {
352                         if (recs[ri].wType != question->question_type) {
353                                 continue;
354                         }
355
356                         ZERO_STRUCT(ans[ai]);
357                         ans[ai].name = question->name;
358                         ans[ai].rr_type = DNS_QTYPE_SOA;
359                         ans[ai].rr_class = DNS_QCLASS_IP;
360                         ans[ai].ttl = recs[ri].dwTtlSeconds;
361                         ans[ai].length = UINT16_MAX;
362                         ans[ai].rdata.soa_record.mname  = recs[ri].data.soa.mname;
363                         ans[ai].rdata.soa_record.rname  = recs[ri].data.soa.rname;
364                         ans[ai].rdata.soa_record.serial = recs[ri].data.soa.serial;
365                         ans[ai].rdata.soa_record.refresh= recs[ri].data.soa.refresh;
366                         ans[ai].rdata.soa_record.retry  = recs[ri].data.soa.retry;
367                         ans[ai].rdata.soa_record.expire = recs[ri].data.soa.expire;
368                         ans[ai].rdata.soa_record.minimum= recs[ri].data.soa.minimum;
369                         ai++;
370                 }
371                 break;
372         default:
373                 return NT_STATUS_NOT_IMPLEMENTED;
374         }
375
376         if (*ancount == ai) {
377                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
378         }
379
380         *ancount = ai;
381         *answers = ans;
382
383         return NT_STATUS_OK;
384
385 }
386
387 static NTSTATUS dns_server_process_query(struct dns_server *dns,
388                                          TALLOC_CTX *mem_ctx,
389                                          struct dns_name_packet *in,
390                                          struct dns_res_rec **answers,    uint16_t *ancount,
391                                          struct dns_res_rec **nsrecs,     uint16_t *nscount,
392                                          struct dns_res_rec **additional, uint16_t *arcount)
393 {
394         uint16_t num_answers=0;
395         struct dns_res_rec *ans=NULL;
396         int i;
397         NTSTATUS status;
398
399         ans = talloc_array(mem_ctx, struct dns_res_rec, 0);
400         if (answers == NULL) return NT_STATUS_NO_MEMORY;
401
402         for (i = 0; i < in->qdcount; ++i) {
403                 status = handle_question(dns, mem_ctx, &in->questions[i], &ans, &num_answers);
404                 NT_STATUS_NOT_OK_RETURN(status);
405         }
406
407         *answers = ans;
408         *ancount = num_answers;
409
410         /*FIXME: Do something for these */
411         *nsrecs  = NULL;
412         *nscount = 0;
413
414         *additional = NULL;
415         *arcount    = 0;
416
417         return NT_STATUS_OK;
418 }
419
420 static NTSTATUS dns_server_process_update(struct dns_server *dns,
421                                           TALLOC_CTX *mem_ctx,
422                                           struct dns_name_packet *in,
423                                           struct dns_res_rec **prereqs,    uint16_t *prereq_count,
424                                           struct dns_res_rec **updates,    uint16_t *update_count,
425                                           struct dns_res_rec **additional, uint16_t *arcount)
426 {
427         struct dns_name_question *zone;
428
429         if (in->qdcount != 1) {
430                 return NT_STATUS_NOT_IMPLEMENTED;
431         }
432
433         zone = in->questions;
434
435         DEBUG(0, ("Got a dns update request.\n"));
436
437
438         return NT_STATUS_NOT_IMPLEMENTED;
439 }
440
441 static NTSTATUS dns_process(struct dns_server *dns,
442                             TALLOC_CTX *mem_ctx,
443                             DATA_BLOB *in,
444                             DATA_BLOB *out)
445 {
446         enum ndr_err_code ndr_err;
447         NTSTATUS ret;
448         struct dns_name_packet *in_packet;
449         struct dns_name_packet *out_packet;
450         struct dns_res_rec *answers = NULL, *nsrecs = NULL, *additional = NULL;
451         uint16_t num_answers = 0 , num_nsrecs = 0, num_additional = 0;
452         uint16_t reply_code;
453
454         if (in->length < 12) {
455                 return NT_STATUS_INVALID_PARAMETER;
456         }
457
458         in_packet = talloc_zero(mem_ctx, struct dns_name_packet);
459         /* TODO: We don't really need an out_packet. */
460         out_packet = talloc_zero(mem_ctx, struct dns_name_packet);
461
462         if (in_packet == NULL) return NT_STATUS_NO_MEMORY;
463         if (out_packet == NULL) return NT_STATUS_NO_MEMORY;
464
465         dump_data(2, in->data, in->length);
466
467         ndr_err = ndr_pull_struct_blob(in, in_packet, in_packet,
468                         (ndr_pull_flags_fn_t)ndr_pull_dns_name_packet);
469         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
470                 TALLOC_FREE(in_packet);
471                 DEBUG(0, ("Failed to parse packet %d!\n", ndr_err));
472                 *out = *in;
473
474                 out->data[2] |= 0x80; /* Toggle DNS_FLAG_REPLY */
475                 out->data[3] |= DNS_RCODE_FORMERR;
476
477                 return NT_STATUS_OK;
478         }
479
480         NDR_PRINT_DEBUG(dns_name_packet, in_packet);
481         *out_packet = *in_packet;
482         out_packet->operation |= DNS_FLAG_REPLY;
483
484         switch (in_packet->operation & DNS_OPCODE) {
485         case DNS_OPCODE_QUERY:
486
487                 ret = dns_server_process_query(dns, out_packet, in_packet,
488                                                &answers, &num_answers,
489                                                &nsrecs,  &num_nsrecs,
490                                                &additional, &num_additional);
491                 reply_code = DNS_RCODE_NXDOMAIN;
492
493                 break;
494         case DNS_OPCODE_REGISTER:
495                 ret = dns_server_process_update(dns, out_packet, in_packet,
496                                                 &answers, &num_answers,
497                                                 &nsrecs,  &num_nsrecs,
498                                                 &additional, &num_additional);
499                 reply_code = ntstatus_to_dns_err(ret);
500                 break;
501         default:
502                 ret = NT_STATUS_NOT_IMPLEMENTED;
503                 reply_code = DNS_RCODE_NOTIMP;
504                 break;
505         }
506
507         if (NT_STATUS_IS_OK(ret)) {
508                 out_packet->ancount = num_answers;
509                 out_packet->answers = answers;
510
511                 out_packet->nscount = num_nsrecs;
512                 out_packet->nsrecs  = nsrecs;
513
514                 out_packet->arcount = num_additional;
515                 out_packet->additional = additional;
516         } else {
517                 out_packet->operation |= reply_code;
518         }
519
520         NDR_PRINT_DEBUG(dns_name_packet, out_packet);
521         ndr_err = ndr_push_struct_blob(out, out_packet, out_packet,
522                         (ndr_push_flags_fn_t)ndr_push_dns_name_packet);
523         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
524                 TALLOC_FREE(in_packet);
525                 TALLOC_FREE(out_packet);
526                 DEBUG(0, ("Failed to push packet %d!\n", ndr_err));
527                 *out = *in;
528
529                 out->data[2] |= 0x80; /* Toggle DNS_FLAG_REPLY */
530                 out->data[3] |= DNS_RCODE_SERVFAIL;
531
532                 return NT_STATUS_OK;
533         }
534
535         dump_data(2, out->data, out->length);
536         return NT_STATUS_OK;
537 }
538
539 struct dns_tcp_call {
540         struct dns_tcp_connection *dns_conn;
541         DATA_BLOB in;
542         DATA_BLOB out;
543         uint8_t out_hdr[4];
544         struct iovec out_iov[2];
545 };
546
547 static void dns_tcp_call_writev_done(struct tevent_req *subreq);
548
549 static void dns_tcp_call_loop(struct tevent_req *subreq)
550 {
551         struct dns_tcp_connection *dns_conn = tevent_req_callback_data(subreq,
552                                       struct dns_tcp_connection);
553         struct dns_tcp_call *call;
554         NTSTATUS status;
555
556         call = talloc(dns_conn, struct dns_tcp_call);
557         if (call == NULL) {
558                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
559                                 "no memory for dns_tcp_call");
560                 return;
561         }
562         call->dns_conn = dns_conn;
563
564         status = tstream_read_pdu_blob_recv(subreq,
565                                             call,
566                                             &call->in);
567         TALLOC_FREE(subreq);
568         if (!NT_STATUS_IS_OK(status)) {
569                 const char *reason;
570
571                 reason = talloc_asprintf(call, "dns_tcp_call_loop: "
572                                          "tstream_read_pdu_blob_recv() - %s",
573                                          nt_errstr(status));
574                 if (!reason) {
575                         reason = nt_errstr(status);
576                 }
577
578                 dns_tcp_terminate_connection(dns_conn, reason);
579                 return;
580         }
581
582         DEBUG(10,("Received krb5 TCP packet of length %lu from %s\n",
583                  (long) call->in.length,
584                  tsocket_address_string(dns_conn->conn->remote_address, call)));
585
586         /* skip length header */
587         call->in.data +=4;
588         call->in.length -= 4;
589
590         /* Call dns */
591         status = dns_process(dns_conn->dns_socket->dns, call, &call->in, &call->out);
592         if (!NT_STATUS_IS_OK(status)) {
593                 DEBUG(0, ("dns_process returned %s\n", nt_errstr(status)));
594                 dns_tcp_terminate_connection(dns_conn,
595                                 "dns_tcp_call_loop: process function failed");
596                 return;
597         }
598
599         /* First add the length of the out buffer */
600         RSIVAL(call->out_hdr, 0, call->out.length);
601         call->out_iov[0].iov_base = (char *) call->out_hdr;
602         call->out_iov[0].iov_len = 4;
603
604         call->out_iov[1].iov_base = (char *) call->out.data;
605         call->out_iov[1].iov_len = call->out.length;
606
607         subreq = tstream_writev_queue_send(call,
608                                            dns_conn->conn->event.ctx,
609                                            dns_conn->tstream,
610                                            dns_conn->send_queue,
611                                            call->out_iov, 2);
612         if (subreq == NULL) {
613                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
614                                 "no memory for tstream_writev_queue_send");
615                 return;
616         }
617         tevent_req_set_callback(subreq, dns_tcp_call_writev_done, call);
618
619         /*
620          * The krb5 tcp pdu's has the length as 4 byte (initial_read_size),
621          * packet_full_request_u32 provides the pdu length then.
622          */
623         subreq = tstream_read_pdu_blob_send(dns_conn,
624                                             dns_conn->conn->event.ctx,
625                                             dns_conn->tstream,
626                                             4, /* initial_read_size */
627                                             packet_full_request_u32,
628                                             dns_conn);
629         if (subreq == NULL) {
630                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
631                                 "no memory for tstream_read_pdu_blob_send");
632                 return;
633         }
634         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
635 }
636
637 static void dns_tcp_call_writev_done(struct tevent_req *subreq)
638 {
639         struct dns_tcp_call *call = tevent_req_callback_data(subreq,
640                         struct dns_tcp_call);
641         int sys_errno;
642         int rc;
643
644         rc = tstream_writev_queue_recv(subreq, &sys_errno);
645         TALLOC_FREE(subreq);
646         if (rc == -1) {
647                 const char *reason;
648
649                 reason = talloc_asprintf(call, "dns_tcp_call_writev_done: "
650                                          "tstream_writev_queue_recv() - %d:%s",
651                                          sys_errno, strerror(sys_errno));
652                 if (!reason) {
653                         reason = "dns_tcp_call_writev_done: tstream_writev_queue_recv() failed";
654                 }
655
656                 dns_tcp_terminate_connection(call->dns_conn, reason);
657                 return;
658         }
659
660         /* We don't care about errors */
661
662         talloc_free(call);
663 }
664
665 /*
666   called when we get a new connection
667 */
668 static void dns_tcp_accept(struct stream_connection *conn)
669 {
670         struct dns_socket *dns_socket;
671         struct dns_tcp_connection *dns_conn;
672         struct tevent_req *subreq;
673         int rc;
674
675         dns_conn = talloc_zero(conn, struct dns_tcp_connection);
676         if (dns_conn == NULL) {
677                 stream_terminate_connection(conn,
678                                 "dns_tcp_accept: out of memory");
679                 return;
680         }
681
682         dns_conn->send_queue = tevent_queue_create(conn, "dns_tcp_accept");
683         if (dns_conn->send_queue == NULL) {
684                 stream_terminate_connection(conn,
685                                 "dns_tcp_accept: out of memory");
686                 return;
687         }
688
689         dns_socket = talloc_get_type(conn->private_data, struct dns_socket);
690
691         TALLOC_FREE(conn->event.fde);
692
693         rc = tstream_bsd_existing_socket(dns_conn,
694                         socket_get_fd(conn->socket),
695                         &dns_conn->tstream);
696         if (rc < 0) {
697                 stream_terminate_connection(conn,
698                                 "dns_tcp_accept: out of memory");
699                 return;
700         }
701
702         dns_conn->conn = conn;
703         dns_conn->dns_socket = dns_socket;
704         conn->private_data = dns_conn;
705
706         /*
707          * The krb5 tcp pdu's has the length as 4 byte (initial_read_size),
708          * packet_full_request_u32 provides the pdu length then.
709          */
710         subreq = tstream_read_pdu_blob_send(dns_conn,
711                                             dns_conn->conn->event.ctx,
712                                             dns_conn->tstream,
713                                             4, /* initial_read_size */
714                                             packet_full_request_u32,
715                                             dns_conn);
716         if (subreq == NULL) {
717                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_accept: "
718                                 "no memory for tstream_read_pdu_blob_send");
719                 return;
720         }
721         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
722 }
723
724 static const struct stream_server_ops dns_tcp_stream_ops = {
725         .name                   = "dns_tcp",
726         .accept_connection      = dns_tcp_accept,
727         .recv_handler           = dns_tcp_recv,
728         .send_handler           = dns_tcp_send
729 };
730
731 struct dns_udp_call {
732         struct tsocket_address *src;
733         DATA_BLOB in;
734         DATA_BLOB out;
735 };
736
737 static void dns_udp_call_sendto_done(struct tevent_req *subreq);
738
739 static void dns_udp_call_loop(struct tevent_req *subreq)
740 {
741         struct dns_udp_socket *sock = tevent_req_callback_data(subreq,
742                                       struct dns_udp_socket);
743         struct dns_udp_call *call;
744         uint8_t *buf;
745         ssize_t len;
746         int sys_errno;
747         NTSTATUS status;
748
749         call = talloc(sock, struct dns_udp_call);
750         if (call == NULL) {
751                 talloc_free(call);
752                 goto done;
753         }
754
755         len = tdgram_recvfrom_recv(subreq, &sys_errno,
756                                    call, &buf, &call->src);
757         TALLOC_FREE(subreq);
758         if (len == -1) {
759                 talloc_free(call);
760                 goto done;
761         }
762
763         call->in.data = buf;
764         call->in.length = len;
765
766         DEBUG(10,("Received krb5 UDP packet of length %lu from %s\n",
767                  (long)call->in.length,
768                  tsocket_address_string(call->src, call)));
769
770         /* Call krb5 */
771         status = dns_process(sock->dns_socket->dns, call, &call->in, &call->out);
772         if (!NT_STATUS_IS_OK(status)) {
773                 talloc_free(call);
774                 DEBUG(0, ("dns_process returned %s\n", nt_errstr(status)));
775                 goto done;
776         }
777
778         subreq = tdgram_sendto_queue_send(call,
779                                           sock->dns_socket->dns->task->event_ctx,
780                                           sock->dgram,
781                                           sock->send_queue,
782                                           call->out.data,
783                                           call->out.length,
784                                           call->src);
785         if (subreq == NULL) {
786                 talloc_free(call);
787                 goto done;
788         }
789         tevent_req_set_callback(subreq, dns_udp_call_sendto_done, call);
790
791 done:
792         subreq = tdgram_recvfrom_send(sock,
793                                       sock->dns_socket->dns->task->event_ctx,
794                                       sock->dgram);
795         if (subreq == NULL) {
796                 task_server_terminate(sock->dns_socket->dns->task,
797                                       "no memory for tdgram_recvfrom_send",
798                                       true);
799                 return;
800         }
801         tevent_req_set_callback(subreq, dns_udp_call_loop, sock);
802 }
803
804 static void dns_udp_call_sendto_done(struct tevent_req *subreq)
805 {
806         struct dns_udp_call *call = tevent_req_callback_data(subreq,
807                                        struct dns_udp_call);
808         ssize_t ret;
809         int sys_errno;
810
811         ret = tdgram_sendto_queue_recv(subreq, &sys_errno);
812
813         /* We don't care about errors */
814
815         talloc_free(call);
816 }
817
818 /*
819   start listening on the given address
820 */
821 static NTSTATUS dns_add_socket(struct dns_server *dns,
822                                const struct model_ops *model_ops,
823                                const char *name,
824                                const char *address,
825                                uint16_t port)
826 {
827         struct dns_socket *dns_socket;
828         struct dns_udp_socket *dns_udp_socket;
829         struct tevent_req *udpsubreq;
830         NTSTATUS status;
831         int ret;
832
833         dns_socket = talloc(dns, struct dns_socket);
834         NT_STATUS_HAVE_NO_MEMORY(dns_socket);
835
836         dns_socket->dns = dns;
837
838         ret = tsocket_address_inet_from_strings(dns_socket, "ip",
839                                                 address, port,
840                                                 &dns_socket->local_address);
841         if (ret != 0) {
842                 status = map_nt_error_from_unix(errno);
843                 return status;
844         }
845
846         status = stream_setup_socket(dns->task->event_ctx,
847                                      dns->task->lp_ctx,
848                                      model_ops,
849                                      &dns_tcp_stream_ops,
850                                      "ip", address, &port,
851                                      lpcfg_socket_options(dns->task->lp_ctx),
852                                      dns_socket);
853         if (!NT_STATUS_IS_OK(status)) {
854                 DEBUG(0,("Failed to bind to %s:%u TCP - %s\n",
855                          address, port, nt_errstr(status)));
856                 talloc_free(dns_socket);
857                 return status;
858         }
859
860         dns_udp_socket = talloc(dns_socket, struct dns_udp_socket);
861         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket);
862
863         dns_udp_socket->dns_socket = dns_socket;
864
865         ret = tdgram_inet_udp_socket(dns_socket->local_address,
866                                      NULL,
867                                      dns_udp_socket,
868                                      &dns_udp_socket->dgram);
869         if (ret != 0) {
870                 status = map_nt_error_from_unix(errno);
871                 DEBUG(0,("Failed to bind to %s:%u UDP - %s\n",
872                          address, port, nt_errstr(status)));
873                 return status;
874         }
875
876         dns_udp_socket->send_queue = tevent_queue_create(dns_udp_socket,
877                                                          "dns_udp_send_queue");
878         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket->send_queue);
879
880         udpsubreq = tdgram_recvfrom_send(dns_udp_socket,
881                                          dns->task->event_ctx,
882                                          dns_udp_socket->dgram);
883         NT_STATUS_HAVE_NO_MEMORY(udpsubreq);
884         tevent_req_set_callback(udpsubreq, dns_udp_call_loop, dns_udp_socket);
885
886         return NT_STATUS_OK;
887 }
888
889 /*
890   setup our listening sockets on the configured network interfaces
891 */
892 static NTSTATUS dns_startup_interfaces(struct dns_server *dns, struct loadparm_context *lp_ctx,
893                                        struct interface *ifaces)
894 {
895         const struct model_ops *model_ops;
896         int num_interfaces;
897         TALLOC_CTX *tmp_ctx = talloc_new(dns);
898         NTSTATUS status;
899         int i;
900
901         /* within the dns task we want to be a single process, so
902            ask for the single process model ops and pass these to the
903            stream_setup_socket() call. */
904         model_ops = process_model_startup(dns->task->event_ctx, "single");
905         if (!model_ops) {
906                 DEBUG(0,("Can't find 'single' process model_ops\n"));
907                 return NT_STATUS_INTERNAL_ERROR;
908         }
909
910         num_interfaces = iface_count(ifaces);
911
912         for (i=0; i<num_interfaces; i++) {
913                 const char *address = talloc_strdup(tmp_ctx, iface_n_ip(ifaces, i));
914
915                 status = dns_add_socket(dns, model_ops, "dns", address, DNS_SERVICE_PORT);
916                 NT_STATUS_NOT_OK_RETURN(status);
917         }
918
919         talloc_free(tmp_ctx);
920
921         return NT_STATUS_OK;
922 }
923
924 static int dns_server_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
925 {
926         const char *n1, *n2;
927         size_t l1, l2;
928
929         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
930         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
931
932         l1 = strlen(n1);
933         l2 = strlen(n2);
934
935         /* If the string lengths are not equal just sort by length */
936         if (l1 != l2) {
937                 /* If m1 is the larger zone name, return it first */
938                 return l2 - l1;
939         }
940
941         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
942         return 0;
943 }
944
945 static void dns_task_init(struct task_server *task)
946 {
947         struct dns_server *dns;
948         NTSTATUS status;
949         struct interface *ifaces;
950         int ret;
951         struct ldb_result *res;
952         struct ldb_dn *rootdn;
953         static const char * const attrs[] = { "name", NULL};
954         int i;
955
956
957         switch (lpcfg_server_role(task->lp_ctx)) {
958         case ROLE_STANDALONE:
959                 task_server_terminate(task, "dns: no DNS required in standalone configuration", false);
960                 return;
961         case ROLE_DOMAIN_MEMBER:
962                 task_server_terminate(task, "dns: no DNS required in member server configuration", false);
963                 return;
964         case ROLE_DOMAIN_CONTROLLER:
965                 /* Yes, we want a DNS */
966                 break;
967         }
968
969         load_interfaces(task, lpcfg_interfaces(task->lp_ctx), &ifaces);
970
971         if (iface_count(ifaces) == 0) {
972                 task_server_terminate(task, "dns: no network interfaces configured", false);
973                 return;
974         }
975
976         task_server_set_title(task, "task[dns]");
977
978         dns = talloc_zero(task, struct dns_server);
979         if (dns == NULL) {
980                 task_server_terminate(task, "dns: out of memory", true);
981                 return;
982         }
983
984         dns->task = task;
985
986         dns->samdb = samdb_connect(dns, dns->task->event_ctx, dns->task->lp_ctx,
987                               system_session(dns->task->lp_ctx), 0);
988         if (!dns->samdb) {
989                 task_server_terminate(task, "dns: samdb_connect failed", true);
990                 return;
991         }
992
993         rootdn = ldb_dn_new(dns, dns->samdb, "");
994         if (rootdn == NULL) {
995                 task_server_terminate(task, "dns: out of memory", true);
996                 return;
997         }
998
999         // TODO: this search does not work against windows
1000         ret = dsdb_search(dns->samdb, dns, &res, rootdn, LDB_SCOPE_SUBTREE,
1001                           attrs, DSDB_SEARCH_SEARCH_ALL_PARTITIONS, "(objectClass=dnsZone)");
1002         if (ret != LDB_SUCCESS) {
1003                 task_server_terminate(task,
1004                                       "dns: failed to look up root DNS zones",
1005                                       true);
1006                 return;
1007         }
1008
1009         TYPESAFE_QSORT(res->msgs, res->count, dns_server_sort_zones);
1010
1011         for (i=0; i < res->count; i++) {
1012                 struct dns_server_zone *z;
1013
1014                 z = talloc_zero(dns, struct dns_server_zone);
1015                 if (z == NULL) {
1016                 }
1017
1018                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
1019                 z->dn = talloc_move(z, &res->msgs[i]->dn);
1020
1021                 DLIST_ADD_END(dns->zones, z, NULL);
1022         }
1023
1024         status = dns_startup_interfaces(dns, task->lp_ctx, ifaces);
1025         if (!NT_STATUS_IS_OK(status)) {
1026                 task_server_terminate(task, "dns failed to setup interfaces", true);
1027                 return;
1028         }
1029 }
1030
1031 NTSTATUS server_service_dns_init(void)
1032 {
1033         return register_server_service("dns", dns_task_init);
1034 }