summaryrefslogtreecommitdiffstats
path: root/rtemsbsd/mdns/mdns.c
blob: 48d65ff8ae4c616edcdce94c062c5a842968eba7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*
 * Copyright (c) 2014 embedded brains GmbH.  All rights reserved.
 *
 *  embedded brains GmbH
 *  Dornierstr. 4
 *  82178 Puchheim
 *  Germany
 *  <rtems@embedded-brains.de>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <mDNSEmbeddedAPI.h>
#include <mDNSPosix.h>
#include <DNSCommon.h>

#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>

#include <netinet/in.h>
#include <arpa/inet.h>
#include <arpa/nameser.h>

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <nsswitch.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <rtems/bsd/util.h>
#include <rtems/mdns.h>

static rtems_id mdns_daemon_id;

static mDNS mDNSStorage;

static mDNS_PlatformSupport PlatformStorage;

typedef struct {
	mDNSu16 rrtype;
	struct hostent *he;
	rtems_id task_id;
} query_context;

static void
query_callback(mDNS *m, DNSQuestion *q, const ResourceRecord *answer,
    QC_result add_record)
{
	query_context *ctx = q->QuestionContext;
	struct hostent *he = ctx->he;
	bool stop = false;
	rtems_id task_id = ctx->task_id;

	(void)m;
	(void)add_record;

	if (ctx->rrtype == kDNSType_A && answer->rrtype == kDNSType_A) {
		const mDNSv4Addr *ipv4 = &answer->rdata->u.ipv4;

		memcpy(he->h_addr_list[0], ipv4, sizeof(*ipv4));
		stop = true;
	} else if (ctx->rrtype == kDNSType_AAAA
	    && answer->rrtype == kDNSType_AAAA) {
		const mDNSv6Addr *ipv6 = &answer->rdata->u.ipv6;

		memcpy(he->h_addr_list[0], ipv6, sizeof(*ipv6));
		stop = true;
	}

	if (stop && task_id != 0) {
		rtems_status_code sc;

		ctx->task_id = 0;

		sc = rtems_event_transient_send(task_id);
		assert(sc == RTEMS_SUCCESSFUL);
	}
}

static bool is_local_name(const char *name)
{
	size_t len = strlen(name);
	const char local[] = "local";
	size_t locallen = sizeof(local) - 1;

	if (len == 0) {
		return (false);
	}

	if (name[len - 1] == '.') {
		--len;
	}

	if (len < locallen) {
		return (false);
	}

	return strncasecmp(name + len - locallen, &local[0], locallen) == 0;
}

static int
mdns_gethostbyname(void *rval, void *cb_data, va_list ap)
{
	const char *name;
	int af;
	char *buffer;
	size_t buflen;
	size_t len;
	size_t namelen;
	int *errnop;
	int *h_errnop;
	struct hostent *hep;
	struct hostent **resultp;
	DNSQuestion q;
	query_context ctx;
	mDNSu8 *qname;
	rtems_status_code sc;

	memset(&q, 0, sizeof(q));
	memset(&ctx, 0, sizeof(ctx));

	name = va_arg(ap, const char *);
	af = va_arg(ap, int);
	hep = va_arg(ap, struct hostent *);
	buffer = va_arg(ap, char *);
	buflen = va_arg(ap, size_t);
	errnop = va_arg(ap, int *);
	h_errnop = va_arg(ap, int *);
	resultp = (struct hostent **)rval;

	*resultp = NULL;

	if (!is_local_name(name)) {
		*h_errnop = NETDB_INTERNAL;
		*errnop = EINVAL;
		return (NS_NOTFOUND);
	}

	hep->h_addrtype = af;
	switch (af) {
	case AF_INET:
		hep->h_length = NS_INADDRSZ;
		ctx.rrtype = kDNSType_A;
		break;
	case AF_INET6:
		hep->h_length = NS_IN6ADDRSZ;
		ctx.rrtype = kDNSType_AAAA;
		break;
	default:
		*h_errnop = NETDB_INTERNAL;
		*errnop = EAFNOSUPPORT;
		return (NS_UNAVAIL);
	}

	len = (char *)ALIGN(buffer) - buffer;
	len += 3 * sizeof(char *);
	len += ALIGN(hep->h_length);
	namelen = strlen(name) + 1;
	len += namelen;

	if (len > buflen) {
		*h_errnop = NETDB_INTERNAL;
		*errnop = ERANGE;
		return (NS_UNAVAIL);
	}

	buffer = (char *)ALIGN(buffer);

	hep->h_aliases = (char **)buffer;
	buffer += sizeof(char *);
	hep->h_aliases[0] = NULL;

	hep->h_addr_list = (char **)buffer;
	buffer += 2 * sizeof(char *);
	hep->h_addr_list[0] = buffer;
	buffer += ALIGN(hep->h_length);
	hep->h_addr_list[1] = NULL;

	hep->h_name = buffer;
	memcpy(buffer, name, namelen);

	qname = MakeDomainNameFromDNSNameString(&q.qname, name);
	if (qname == NULL) {
		*h_errnop = NETDB_INTERNAL;
		*errnop = ERANGE;
		return (NS_UNAVAIL);
	}

	q.TargetPort = MulticastDNSPort;
	q.qtype = kDNSQType_ANY;
	q.qclass = kDNSClass_IN;
	q.ForceMCast = mDNStrue;
	q.ReturnIntermed = mDNStrue;
	q.QuestionCallback = query_callback;
	q.QuestionContext = &ctx;

	ctx.rrtype = kDNSType_A;
	ctx.he = hep;
	ctx.task_id = rtems_task_self();

	mDNS_StartQuery(&mDNSStorage, &q);
	rtems_bsd_force_select_timeout(mdns_daemon_id);

	sc = rtems_event_transient_receive(RTEMS_WAIT,
	    10 * rtems_clock_get_ticks_per_second());

	mDNS_StopQuery(&mDNSStorage, &q);

	if (sc != RTEMS_SUCCESSFUL) {
		*h_errnop = NETDB_INTERNAL;
		*errnop = ETIMEDOUT;
		return (NS_NOTFOUND);
	}

	*resultp = hep;
	return (NS_SUCCESS);
}

static ns_mtab mdns_mtab[] = {
	{
		.database = NSDB_HOSTS,
		.name = "gethostbyname2_r",
		.method = mdns_gethostbyname
	}
};

static void
mdns_daemon(rtems_task_argument arg)
{
	while (true) {
		struct timeval timeout = { .tv_sec = 0x1, .tv_usec = 0 };
		sigset_t signals;
		mDNSBool got_something;

		mDNSPosixRunEventLoopOnce(&mDNSStorage, &timeout, &signals,
		    &got_something);
	}
}

static void
truncate_at_first_dot(domainlabel *name)
{
	int c = name->c[0];
	int n = 0;

	while (n < c && name->c[n + 1] != '.') {
		++n;
	}

	name->c[0] = n;
}

static int
mdns_sethostname(const char *hostname)
{
	mDNS *m = &mDNSStorage;

	mDNS_Lock(m);

	MakeDomainLabelFromLiteralString(&m->hostlabel, hostname);
	truncate_at_first_dot(&m->hostlabel);

	mDNS_Unlock(m);

	mDNS_SetFQDN(m);

	rtems_bsd_force_select_timeout(mdns_daemon_id);

	return (0);
}

static int
mdns_gethostname(char *hostname, size_t size)
{
	mDNS *m = &mDNSStorage;

	if (size < MAX_ESCAPED_DOMAIN_LABEL) {
		errno = ERANGE;

		return (-1);
	}

	mDNS_Lock(m);

	ConvertDomainLabelToCString(&m->hostlabel, hostname);

	mDNS_Unlock(m);

	return (0);
}

rtems_status_code
rtems_mdns_initialize(rtems_task_priority daemon_priority,
    CacheEntity *rrcachestorage, mDNSu32 rrcachesize)
{
	mStatus status;
	int rv;
	int fd;
	rtems_status_code sc;

	status = mDNS_Init(&mDNSStorage, &PlatformStorage, rrcachestorage,
	    rrcachesize, mDNS_Init_AdvertiseLocalAddresses,
	    mDNS_Init_NoInitCallback, mDNS_Init_NoInitCallbackContext);
	if (status != mStatus_NoError) {
		return (RTEMS_UNSATISFIED);
	}

	sc = rtems_task_create(rtems_build_name('m', 'D', 'N', 'S'),
	    daemon_priority, 32 * 1024, RTEMS_DEFAULT_MODES,
	    RTEMS_FLOATING_POINT, &mdns_daemon_id);
	if (sc != RTEMS_SUCCESSFUL) {
		return (RTEMS_UNSATISFIED);
	}

	sc = rtems_task_start(mdns_daemon_id, mdns_daemon, 0);
	if (sc != RTEMS_SUCCESSFUL) {
		return (RTEMS_UNSATISFIED);
	}

	rv = rtems_nss_register_module("mdns", &mdns_mtab[0],
	    RTEMS_ARRAY_SIZE(mdns_mtab));
	if (rv != 0) {
		return (RTEMS_UNSATISFIED);
	}

	fd = open(_PATH_NS_CONF, O_WRONLY | O_CREAT | O_EXCL,
	    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	if (fd >= 0) {
		static const char nsconf[] = "hosts: files mdns dns\n";
		ssize_t n;

		n = write(fd, &nsconf[0], sizeof(nsconf) - 1);

		rv = close(fd);
		assert(rv == 0);

		if (n != (ssize_t) (sizeof(nsconf) - 1)) {
			return (RTEMS_UNSATISFIED);
		}
	}

	rtems_mdns_sethostname_handler = mdns_sethostname;
	rtems_mdns_gethostname_handler = mdns_gethostname;

	return (RTEMS_SUCCESSFUL);
}

mDNS *
rtems_mdns_get_instance(void)
{
	return (&mDNSStorage);
}