s4-smbd: don't initialise process models more than once
[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_process(struct dns_server *dns,
95                             TALLOC_CTX *mem_ctx,
96                             DATA_BLOB *in,
97                             DATA_BLOB *out)
98 {
99         enum ndr_err_code ndr_err;
100         WERROR ret;
101         struct dns_name_packet *in_packet;
102         struct dns_name_packet *out_packet;
103         struct dns_res_rec *answers = NULL, *nsrecs = NULL, *additional = NULL;
104         uint16_t num_answers = 0 , num_nsrecs = 0, num_additional = 0;
105
106         if (in->length < 12) {
107                 return NT_STATUS_INVALID_PARAMETER;
108         }
109
110         in_packet = talloc_zero(mem_ctx, struct dns_name_packet);
111         /* TODO: We don't really need an out_packet. */
112         out_packet = talloc_zero(mem_ctx, struct dns_name_packet);
113
114         if (in_packet == NULL) return NT_STATUS_NO_MEMORY;
115         if (out_packet == NULL) return NT_STATUS_NO_MEMORY;
116
117         dump_data(2, in->data, in->length);
118
119         ndr_err = ndr_pull_struct_blob(in, in_packet, in_packet,
120                         (ndr_pull_flags_fn_t)ndr_pull_dns_name_packet);
121         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
122                 TALLOC_FREE(in_packet);
123                 DEBUG(0, ("Failed to parse packet %d!\n", ndr_err));
124                 *out = *in;
125
126                 out->data[2] |= 0x80; /* Toggle DNS_FLAG_REPLY */
127                 out->data[3] |= DNS_RCODE_FORMERR;
128
129                 return NT_STATUS_OK;
130         }
131
132         NDR_PRINT_DEBUG(dns_name_packet, in_packet);
133         *out_packet = *in_packet;
134         out_packet->operation |= DNS_FLAG_REPLY;
135
136         switch (in_packet->operation & DNS_OPCODE) {
137         case DNS_OPCODE_QUERY:
138
139                 ret = dns_server_process_query(dns, out_packet, in_packet,
140                                                &answers, &num_answers,
141                                                &nsrecs,  &num_nsrecs,
142                                                &additional, &num_additional);
143
144                 break;
145         case DNS_OPCODE_REGISTER:
146                 ret = dns_server_process_update(dns, out_packet, in_packet,
147                                                 answers, num_answers,
148                                                 &nsrecs,  &num_nsrecs,
149                                                 &additional, &num_additional);
150                 break;
151         default:
152                 ret = WERR_DNS_ERROR_RCODE_NOT_IMPLEMENTED;
153                 break;
154         }
155
156         if (W_ERROR_IS_OK(ret)) {
157                 out_packet->ancount = num_answers;
158                 out_packet->answers = answers;
159
160                 out_packet->nscount = num_nsrecs;
161                 out_packet->nsrecs  = nsrecs;
162
163                 out_packet->arcount = num_additional;
164                 out_packet->additional = additional;
165         } else {
166                 out_packet->operation |= werr_to_dns_err(ret);
167         }
168
169         NDR_PRINT_DEBUG(dns_name_packet, out_packet);
170         ndr_err = ndr_push_struct_blob(out, out_packet, out_packet,
171                         (ndr_push_flags_fn_t)ndr_push_dns_name_packet);
172         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
173                 TALLOC_FREE(in_packet);
174                 TALLOC_FREE(out_packet);
175                 DEBUG(0, ("Failed to push packet %d!\n", ndr_err));
176                 *out = *in;
177
178                 out->data[2] |= 0x80; /* Toggle DNS_FLAG_REPLY */
179                 out->data[3] |= DNS_RCODE_SERVFAIL;
180
181                 return NT_STATUS_OK;
182         }
183
184         dump_data(2, out->data, out->length);
185         return NT_STATUS_OK;
186 }
187
188 struct dns_tcp_call {
189         struct dns_tcp_connection *dns_conn;
190         DATA_BLOB in;
191         DATA_BLOB out;
192         uint8_t out_hdr[4];
193         struct iovec out_iov[2];
194 };
195
196 static void dns_tcp_call_writev_done(struct tevent_req *subreq);
197
198 static void dns_tcp_call_loop(struct tevent_req *subreq)
199 {
200         struct dns_tcp_connection *dns_conn = tevent_req_callback_data(subreq,
201                                       struct dns_tcp_connection);
202         struct dns_tcp_call *call;
203         NTSTATUS status;
204
205         call = talloc(dns_conn, struct dns_tcp_call);
206         if (call == NULL) {
207                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
208                                 "no memory for dns_tcp_call");
209                 return;
210         }
211         call->dns_conn = dns_conn;
212
213         status = tstream_read_pdu_blob_recv(subreq,
214                                             call,
215                                             &call->in);
216         TALLOC_FREE(subreq);
217         if (!NT_STATUS_IS_OK(status)) {
218                 const char *reason;
219
220                 reason = talloc_asprintf(call, "dns_tcp_call_loop: "
221                                          "tstream_read_pdu_blob_recv() - %s",
222                                          nt_errstr(status));
223                 if (!reason) {
224                         reason = nt_errstr(status);
225                 }
226
227                 dns_tcp_terminate_connection(dns_conn, reason);
228                 return;
229         }
230
231         DEBUG(10,("Received krb5 TCP packet of length %lu from %s\n",
232                  (long) call->in.length,
233                  tsocket_address_string(dns_conn->conn->remote_address, call)));
234
235         /* skip length header */
236         call->in.data +=4;
237         call->in.length -= 4;
238
239         /* Call dns */
240         status = dns_process(dns_conn->dns_socket->dns, call, &call->in, &call->out);
241         if (!NT_STATUS_IS_OK(status)) {
242                 DEBUG(0, ("dns_process returned %s\n", nt_errstr(status)));
243                 dns_tcp_terminate_connection(dns_conn,
244                                 "dns_tcp_call_loop: process function failed");
245                 return;
246         }
247
248         /* First add the length of the out buffer */
249         RSIVAL(call->out_hdr, 0, call->out.length);
250         call->out_iov[0].iov_base = (char *) call->out_hdr;
251         call->out_iov[0].iov_len = 4;
252
253         call->out_iov[1].iov_base = (char *) call->out.data;
254         call->out_iov[1].iov_len = call->out.length;
255
256         subreq = tstream_writev_queue_send(call,
257                                            dns_conn->conn->event.ctx,
258                                            dns_conn->tstream,
259                                            dns_conn->send_queue,
260                                            call->out_iov, 2);
261         if (subreq == NULL) {
262                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
263                                 "no memory for tstream_writev_queue_send");
264                 return;
265         }
266         tevent_req_set_callback(subreq, dns_tcp_call_writev_done, call);
267
268         /*
269          * The krb5 tcp pdu's has the length as 4 byte (initial_read_size),
270          * packet_full_request_u32 provides the pdu length then.
271          */
272         subreq = tstream_read_pdu_blob_send(dns_conn,
273                                             dns_conn->conn->event.ctx,
274                                             dns_conn->tstream,
275                                             4, /* initial_read_size */
276                                             packet_full_request_u32,
277                                             dns_conn);
278         if (subreq == NULL) {
279                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_call_loop: "
280                                 "no memory for tstream_read_pdu_blob_send");
281                 return;
282         }
283         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
284 }
285
286 static void dns_tcp_call_writev_done(struct tevent_req *subreq)
287 {
288         struct dns_tcp_call *call = tevent_req_callback_data(subreq,
289                         struct dns_tcp_call);
290         int sys_errno;
291         int rc;
292
293         rc = tstream_writev_queue_recv(subreq, &sys_errno);
294         TALLOC_FREE(subreq);
295         if (rc == -1) {
296                 const char *reason;
297
298                 reason = talloc_asprintf(call, "dns_tcp_call_writev_done: "
299                                          "tstream_writev_queue_recv() - %d:%s",
300                                          sys_errno, strerror(sys_errno));
301                 if (!reason) {
302                         reason = "dns_tcp_call_writev_done: tstream_writev_queue_recv() failed";
303                 }
304
305                 dns_tcp_terminate_connection(call->dns_conn, reason);
306                 return;
307         }
308
309         /* We don't care about errors */
310
311         talloc_free(call);
312 }
313
314 /*
315   called when we get a new connection
316 */
317 static void dns_tcp_accept(struct stream_connection *conn)
318 {
319         struct dns_socket *dns_socket;
320         struct dns_tcp_connection *dns_conn;
321         struct tevent_req *subreq;
322         int rc;
323
324         dns_conn = talloc_zero(conn, struct dns_tcp_connection);
325         if (dns_conn == NULL) {
326                 stream_terminate_connection(conn,
327                                 "dns_tcp_accept: out of memory");
328                 return;
329         }
330
331         dns_conn->send_queue = tevent_queue_create(conn, "dns_tcp_accept");
332         if (dns_conn->send_queue == NULL) {
333                 stream_terminate_connection(conn,
334                                 "dns_tcp_accept: out of memory");
335                 return;
336         }
337
338         dns_socket = talloc_get_type(conn->private_data, struct dns_socket);
339
340         TALLOC_FREE(conn->event.fde);
341
342         rc = tstream_bsd_existing_socket(dns_conn,
343                         socket_get_fd(conn->socket),
344                         &dns_conn->tstream);
345         if (rc < 0) {
346                 stream_terminate_connection(conn,
347                                 "dns_tcp_accept: out of memory");
348                 return;
349         }
350
351         dns_conn->conn = conn;
352         dns_conn->dns_socket = dns_socket;
353         conn->private_data = dns_conn;
354
355         /*
356          * The krb5 tcp pdu's has the length as 4 byte (initial_read_size),
357          * packet_full_request_u32 provides the pdu length then.
358          */
359         subreq = tstream_read_pdu_blob_send(dns_conn,
360                                             dns_conn->conn->event.ctx,
361                                             dns_conn->tstream,
362                                             4, /* initial_read_size */
363                                             packet_full_request_u32,
364                                             dns_conn);
365         if (subreq == NULL) {
366                 dns_tcp_terminate_connection(dns_conn, "dns_tcp_accept: "
367                                 "no memory for tstream_read_pdu_blob_send");
368                 return;
369         }
370         tevent_req_set_callback(subreq, dns_tcp_call_loop, dns_conn);
371 }
372
373 static const struct stream_server_ops dns_tcp_stream_ops = {
374         .name                   = "dns_tcp",
375         .accept_connection      = dns_tcp_accept,
376         .recv_handler           = dns_tcp_recv,
377         .send_handler           = dns_tcp_send
378 };
379
380 struct dns_udp_call {
381         struct tsocket_address *src;
382         DATA_BLOB in;
383         DATA_BLOB out;
384 };
385
386 static void dns_udp_call_sendto_done(struct tevent_req *subreq);
387
388 static void dns_udp_call_loop(struct tevent_req *subreq)
389 {
390         struct dns_udp_socket *sock = tevent_req_callback_data(subreq,
391                                       struct dns_udp_socket);
392         struct dns_udp_call *call;
393         uint8_t *buf;
394         ssize_t len;
395         int sys_errno;
396         NTSTATUS status;
397
398         call = talloc(sock, struct dns_udp_call);
399         if (call == NULL) {
400                 talloc_free(call);
401                 goto done;
402         }
403
404         len = tdgram_recvfrom_recv(subreq, &sys_errno,
405                                    call, &buf, &call->src);
406         TALLOC_FREE(subreq);
407         if (len == -1) {
408                 talloc_free(call);
409                 goto done;
410         }
411
412         call->in.data = buf;
413         call->in.length = len;
414
415         DEBUG(10,("Received krb5 UDP packet of length %lu from %s\n",
416                  (long)call->in.length,
417                  tsocket_address_string(call->src, call)));
418
419         /* Call krb5 */
420         status = dns_process(sock->dns_socket->dns, call, &call->in, &call->out);
421         if (!NT_STATUS_IS_OK(status)) {
422                 talloc_free(call);
423                 DEBUG(0, ("dns_process returned %s\n", nt_errstr(status)));
424                 goto done;
425         }
426
427         subreq = tdgram_sendto_queue_send(call,
428                                           sock->dns_socket->dns->task->event_ctx,
429                                           sock->dgram,
430                                           sock->send_queue,
431                                           call->out.data,
432                                           call->out.length,
433                                           call->src);
434         if (subreq == NULL) {
435                 talloc_free(call);
436                 goto done;
437         }
438         tevent_req_set_callback(subreq, dns_udp_call_sendto_done, call);
439
440 done:
441         subreq = tdgram_recvfrom_send(sock,
442                                       sock->dns_socket->dns->task->event_ctx,
443                                       sock->dgram);
444         if (subreq == NULL) {
445                 task_server_terminate(sock->dns_socket->dns->task,
446                                       "no memory for tdgram_recvfrom_send",
447                                       true);
448                 return;
449         }
450         tevent_req_set_callback(subreq, dns_udp_call_loop, sock);
451 }
452
453 static void dns_udp_call_sendto_done(struct tevent_req *subreq)
454 {
455         struct dns_udp_call *call = tevent_req_callback_data(subreq,
456                                        struct dns_udp_call);
457         ssize_t ret;
458         int sys_errno;
459
460         ret = tdgram_sendto_queue_recv(subreq, &sys_errno);
461
462         /* We don't care about errors */
463
464         talloc_free(call);
465 }
466
467 /*
468   start listening on the given address
469 */
470 static NTSTATUS dns_add_socket(struct dns_server *dns,
471                                const struct model_ops *model_ops,
472                                const char *name,
473                                const char *address,
474                                uint16_t port)
475 {
476         struct dns_socket *dns_socket;
477         struct dns_udp_socket *dns_udp_socket;
478         struct tevent_req *udpsubreq;
479         NTSTATUS status;
480         int ret;
481
482         dns_socket = talloc(dns, struct dns_socket);
483         NT_STATUS_HAVE_NO_MEMORY(dns_socket);
484
485         dns_socket->dns = dns;
486
487         ret = tsocket_address_inet_from_strings(dns_socket, "ip",
488                                                 address, port,
489                                                 &dns_socket->local_address);
490         if (ret != 0) {
491                 status = map_nt_error_from_unix(errno);
492                 return status;
493         }
494
495         status = stream_setup_socket(dns->task->event_ctx,
496                                      dns->task->lp_ctx,
497                                      model_ops,
498                                      &dns_tcp_stream_ops,
499                                      "ip", address, &port,
500                                      lpcfg_socket_options(dns->task->lp_ctx),
501                                      dns_socket);
502         if (!NT_STATUS_IS_OK(status)) {
503                 DEBUG(0,("Failed to bind to %s:%u TCP - %s\n",
504                          address, port, nt_errstr(status)));
505                 talloc_free(dns_socket);
506                 return status;
507         }
508
509         dns_udp_socket = talloc(dns_socket, struct dns_udp_socket);
510         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket);
511
512         dns_udp_socket->dns_socket = dns_socket;
513
514         ret = tdgram_inet_udp_socket(dns_socket->local_address,
515                                      NULL,
516                                      dns_udp_socket,
517                                      &dns_udp_socket->dgram);
518         if (ret != 0) {
519                 status = map_nt_error_from_unix(errno);
520                 DEBUG(0,("Failed to bind to %s:%u UDP - %s\n",
521                          address, port, nt_errstr(status)));
522                 return status;
523         }
524
525         dns_udp_socket->send_queue = tevent_queue_create(dns_udp_socket,
526                                                          "dns_udp_send_queue");
527         NT_STATUS_HAVE_NO_MEMORY(dns_udp_socket->send_queue);
528
529         udpsubreq = tdgram_recvfrom_send(dns_udp_socket,
530                                          dns->task->event_ctx,
531                                          dns_udp_socket->dgram);
532         NT_STATUS_HAVE_NO_MEMORY(udpsubreq);
533         tevent_req_set_callback(udpsubreq, dns_udp_call_loop, dns_udp_socket);
534
535         return NT_STATUS_OK;
536 }
537
538 /*
539   setup our listening sockets on the configured network interfaces
540 */
541 static NTSTATUS dns_startup_interfaces(struct dns_server *dns, struct loadparm_context *lp_ctx,
542                                        struct interface *ifaces)
543 {
544         const struct model_ops *model_ops;
545         int num_interfaces;
546         TALLOC_CTX *tmp_ctx = talloc_new(dns);
547         NTSTATUS status;
548         int i;
549
550         /* within the dns task we want to be a single process, so
551            ask for the single process model ops and pass these to the
552            stream_setup_socket() call. */
553         model_ops = process_model_startup("single");
554         if (!model_ops) {
555                 DEBUG(0,("Can't find 'single' process model_ops\n"));
556                 return NT_STATUS_INTERNAL_ERROR;
557         }
558
559         num_interfaces = iface_count(ifaces);
560
561         for (i=0; i<num_interfaces; i++) {
562                 const char *address = talloc_strdup(tmp_ctx, iface_n_ip(ifaces, i));
563
564                 status = dns_add_socket(dns, model_ops, "dns", address, DNS_SERVICE_PORT);
565                 NT_STATUS_NOT_OK_RETURN(status);
566         }
567
568         talloc_free(tmp_ctx);
569
570         return NT_STATUS_OK;
571 }
572
573 static int dns_server_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
574 {
575         const char *n1, *n2;
576         size_t l1, l2;
577
578         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
579         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
580
581         l1 = strlen(n1);
582         l2 = strlen(n2);
583
584         /* If the string lengths are not equal just sort by length */
585         if (l1 != l2) {
586                 /* If m1 is the larger zone name, return it first */
587                 return l2 - l1;
588         }
589
590         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
591         return 0;
592 }
593
594 static void dns_task_init(struct task_server *task)
595 {
596         struct dns_server *dns;
597         NTSTATUS status;
598         struct interface *ifaces;
599         int ret;
600         struct ldb_result *res;
601         struct ldb_dn *rootdn;
602         static const char * const attrs[] = { "name", NULL};
603         unsigned int i;
604
605         switch (lpcfg_server_role(task->lp_ctx)) {
606         case ROLE_STANDALONE:
607                 task_server_terminate(task, "dns: no DNS required in standalone configuration", false);
608                 return;
609         case ROLE_DOMAIN_MEMBER:
610                 task_server_terminate(task, "dns: no DNS required in member server configuration", false);
611                 return;
612         case ROLE_DOMAIN_CONTROLLER:
613                 /* Yes, we want a DNS */
614                 break;
615         }
616
617         load_interfaces(task, lpcfg_interfaces(task->lp_ctx), &ifaces);
618
619         if (iface_count(ifaces) == 0) {
620                 task_server_terminate(task, "dns: no network interfaces configured", false);
621                 return;
622         }
623
624         task_server_set_title(task, "task[dns]");
625
626         dns = talloc_zero(task, struct dns_server);
627         if (dns == NULL) {
628                 task_server_terminate(task, "dns: out of memory", true);
629                 return;
630         }
631
632         dns->task = task;
633
634         dns->samdb = samdb_connect(dns, dns->task->event_ctx, dns->task->lp_ctx,
635                               system_session(dns->task->lp_ctx), 0);
636         if (!dns->samdb) {
637                 task_server_terminate(task, "dns: samdb_connect failed", true);
638                 return;
639         }
640
641         rootdn = ldb_dn_new(dns, dns->samdb, "");
642         if (rootdn == NULL) {
643                 task_server_terminate(task, "dns: out of memory", true);
644                 return;
645         }
646
647         // TODO: this search does not work against windows
648         ret = dsdb_search(dns->samdb, dns, &res, rootdn, LDB_SCOPE_SUBTREE,
649                           attrs, DSDB_SEARCH_SEARCH_ALL_PARTITIONS, "(objectClass=dnsZone)");
650         if (ret != LDB_SUCCESS) {
651                 task_server_terminate(task,
652                                       "dns: failed to look up root DNS zones",
653                                       true);
654                 return;
655         }
656
657         TYPESAFE_QSORT(res->msgs, res->count, dns_server_sort_zones);
658
659         for (i=0; i < res->count; i++) {
660                 struct dns_server_zone *z;
661
662                 z = talloc_zero(dns, struct dns_server_zone);
663                 if (z == NULL) {
664                 }
665
666                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
667                 z->dn = talloc_move(z, &res->msgs[i]->dn);
668
669                 DLIST_ADD_END(dns->zones, z, NULL);
670         }
671
672         status = dns_startup_interfaces(dns, task->lp_ctx, ifaces);
673         if (!NT_STATUS_IS_OK(status)) {
674                 task_server_terminate(task, "dns failed to setup interfaces", true);
675                 return;
676         }
677 }
678
679 NTSTATUS server_service_dns_init(void)
680 {
681         return register_server_service("dns", dns_task_init);
682 }