aboutsummaryrefslogtreecommitdiff
path: root/src/platform/posix/posix_resolv_gai.c
blob: b5f48ecc9c396414415b0519f800d8c5a723a277 (plain)
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//
// Copyright 2024 Staysail Systems, Inc. <info@staysail.tech>
// Copyright 2018 Capitar IT Group BV <info@capitar.com>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt).  A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//

#include "core/init.h"
#include "core/nng_impl.h"
#include "nng/nng.h"

#ifdef NNG_USE_POSIX_RESOLV_GAI

#include <ctype.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>

// We use a single resolver taskq - but we allocate a few threads
// for it to ensure that names can be looked up concurrently.  This isn't
// as elegant or scalable as a true asynchronous resolver would be, but
// it has the advantage of being fairly portable, and concurrent enough for
// the vast majority of use cases.  The total thread count can be
// changed with this define.  Note that some platforms may not have a
// thread-safe getaddrinfo().  In that case they should set this to 1.

#ifndef AI_NUMERICSERV
#define AI_NUMERICSERV 0
#endif

#ifndef NNG_HAVE_INET6
#ifdef HAVE_NNG_HAVE_INET6_BSD
#define NNG_HAVE_INET6
#include <netinet6/in6.h>
#else
#undef NNG_ENABLE_IPV6
#endif
#endif

static nni_mtx  resolv_mtx  = NNI_MTX_INITIALIZER;
static nni_cv   resolv_cv   = NNI_CV_INITIALIZER(&resolv_mtx);
static bool     resolv_fini = false;
static nni_list resolv_aios;
static nni_thr *resolv_thrs;
static int16_t  resolv_num_thr;

typedef struct resolv_item resolv_item;
struct resolv_item {
	int           family;
	bool          passive;
	char          host[256];
	char          serv[8];
	nni_aio      *aio;
	nng_sockaddr *sa;
};

static void
resolv_free_item(resolv_item *item)
{
	NNI_FREE_STRUCT(item);
}

static void
resolv_cancel(nni_aio *aio, void *arg, int rv)
{
	resolv_item *item = arg;

	nni_mtx_lock(&resolv_mtx);
	if (item != nni_aio_get_prov_data(aio)) {
		// Already canceled?
		nni_mtx_unlock(&resolv_mtx);
		return;
	}
	nni_aio_set_prov_data(aio, NULL);
	if (nni_aio_list_active(aio)) {
		// We have not been picked up by a resolver thread yet,
		// so we can just discard everything.
		nni_aio_list_remove(aio);
		nni_mtx_unlock(&resolv_mtx);
		resolv_free_item(item);
	} else {
		// This case indicates the resolver is still processing our
		// node. We can discard our interest in the result, but we
		// can't interrupt the resolver itself.  (Too bad, name
		// resolution is utterly synchronous for now.)
		item->aio = NULL;
		item->sa  = NULL;
		nni_mtx_unlock(&resolv_mtx);
	}
	nni_aio_finish_error(aio, rv);
}

static int
posix_gai_errno(int rv)
{
	switch (rv) {
	case 0:
		return (0);

	case EAI_MEMORY:
		return (NNG_ENOMEM);

	case EAI_SYSTEM:
		return (nni_plat_errno(errno));

	case EAI_NONAME:
#ifdef EAI_NODATA
	case EAI_NODATA:
#endif
	case EAI_SERVICE:
		return (NNG_EADDRINVAL);

	case EAI_BADFLAGS:
		return (NNG_EINVAL);

	case EAI_SOCKTYPE:
		return (NNG_ENOTSUP);

#ifdef EAI_CANCELED
	case EAI_CANCELED:
		return (NNG_ECANCELED);
#endif

#ifdef EAI_AGAIN
	case EAI_AGAIN:
		return (NNG_EAGAIN);
#endif

	default:
		return (NNG_ESYSERR + rv);
	}
}

static int
resolv_task(resolv_item *item)
{
	struct addrinfo  hints;
	struct addrinfo *results;
	struct addrinfo *probe;
	int              rv;

	results = NULL;

	// We treat these all as IP addresses.  The service and the
	// host part are split.
	memset(&hints, 0, sizeof(hints));
#ifdef AI_ADDRCONFIG
	hints.ai_flags = AI_ADDRCONFIG;
#endif
	if (item->passive) {
		hints.ai_flags |= AI_PASSIVE;
	}
	hints.ai_family   = item->family;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags |= AI_NUMERICSERV;

	// We can pass any non-zero service number, but we have to pass
	// *something*, in case we are using a NULL hostname.
	if ((rv = getaddrinfo(item->host[0] != 0 ? item->host : NULL,
	         item->serv, &hints, &results)) != 0) {
		rv = posix_gai_errno(rv);
		goto done;
	}

	// We only take the first matching address.  Presumably
	// DNS load balancing is done by the resolver/server.

	rv = NNG_EADDRINVAL;
	for (probe = results; probe != NULL; probe = probe->ai_next) {
		if (probe->ai_addr->sa_family == AF_INET) {
			break;
		}
#ifdef NNG_ENABLE_IPV6
		if (probe->ai_addr->sa_family == AF_INET6) {
			break;
		}
#endif
	}

	nni_mtx_lock(&resolv_mtx);
	if ((probe != NULL) && (item->aio != NULL)) {
		struct sockaddr_in *sin;
#ifdef NNG_ENABLE_IPV6
		struct sockaddr_in6 *sin6;
#endif
		nng_sockaddr *sa = item->sa;

		switch (probe->ai_addr->sa_family) {
		case AF_INET:
			rv                 = 0;
			sin                = (void *) probe->ai_addr;
			sa->s_in.sa_family = NNG_AF_INET;
			sa->s_in.sa_port   = sin->sin_port;
			sa->s_in.sa_addr   = sin->sin_addr.s_addr;
			break;
#ifdef NNG_ENABLE_IPV6
		case AF_INET6:
			rv                  = 0;
			sin6                = (void *) probe->ai_addr;
			sa->s_in6.sa_family = NNG_AF_INET6;
			sa->s_in6.sa_port   = sin6->sin6_port;
			sa->s_in6.sa_scope  = sin6->sin6_scope_id;
			memcpy(sa->s_in6.sa_addr, sin6->sin6_addr.s6_addr, 16);
			break;
#endif
		}
	}
	nni_mtx_unlock(&resolv_mtx);

done:

	if (results != NULL) {
		freeaddrinfo(results);
	}

	return (rv);
}

void
nni_resolv_ip(const char *host, uint16_t port, int af, bool passive,
    nng_sockaddr *sa, nni_aio *aio)
{
	resolv_item *item;
	sa_family_t  fam;

	nni_aio_reset(aio);
	if (host != NULL) {
		if ((strlen(host) >= sizeof(item->host)) ||
		    (strcmp(host, "*") == 0)) {
			nni_aio_finish_error(aio, NNG_EADDRINVAL);
			return;
		}
	}
	switch (af) {
	case NNG_AF_INET:
		fam = AF_INET;
		break;

#ifdef NNG_ENABLE_IPV6
	case NNG_AF_INET6:
		fam = AF_INET6;
		break;
	case NNG_AF_UNSPEC:
		fam = AF_UNSPEC;
		break;
#else
	case NNG_AF_UNSPEC:
		fam = AF_INET;
		break;
#endif

	default:
		nni_aio_finish_error(aio, NNG_ENOTSUP);
		return;
	}

	if ((item = NNI_ALLOC_STRUCT(item)) == NULL) {
		nni_aio_finish_error(aio, NNG_ENOMEM);
		return;
	}

	snprintf(item->serv, sizeof(item->serv), "%u", port);
	if (host == NULL) {
		item->host[0] = '\0';
	} else {
		snprintf(item->host, sizeof(item->host), "%s", host);
	}

	item->aio     = aio;
	item->family  = fam;
	item->passive = passive;
	item->sa      = sa;

	nni_mtx_lock(&resolv_mtx);
	nni_aio_set_prov_data(aio, item);
	if (!nni_aio_start(aio, resolv_cancel, item)) {
		nni_mtx_unlock(&resolv_mtx);
		resolv_free_item(item);
		return;
	}

	if (resolv_fini) {
		nni_mtx_unlock(&resolv_mtx);
		resolv_free_item(item);
		nni_aio_finish_error(aio, NNG_ECLOSED);
		return;
	}
	nni_list_append(&resolv_aios, aio);
	nni_cv_wake1(&resolv_cv);
	nni_mtx_unlock(&resolv_mtx);
}

void
resolv_worker(void *unused)
{

	NNI_ARG_UNUSED(unused);

	nni_thr_set_name(NULL, "nng:resolver");

	nni_mtx_lock(&resolv_mtx);
	for (;;) {
		nni_aio     *aio;
		resolv_item *item;
		int          rv;

		if ((aio = nni_list_first(&resolv_aios)) == NULL) {
			if (resolv_fini) {
				break;
			}
			nni_cv_wait(&resolv_cv);
			continue;
		}

		item = nni_aio_get_prov_data(aio);
		nni_aio_list_remove(aio);

		// Now attempt to do the work.  This runs synchronously.
		nni_mtx_unlock(&resolv_mtx);
		rv = resolv_task(item);
		nni_mtx_lock(&resolv_mtx);

		// Check to make sure we were not canceled.
		if ((aio = item->aio) != NULL) {

			nni_aio_set_prov_data(aio, NULL);
			item->aio = NULL;
			item->sa  = NULL;

			nni_aio_finish(aio, rv, 0);
		}
		resolv_free_item(item);
	}
	nni_mtx_unlock(&resolv_mtx);
}

int
parse_ip(const char *addr, nng_sockaddr *sa, bool want_port)
{
	struct addrinfo  hints;
	struct addrinfo *results;
	int              rv;
	char            *port;
	char            *host;
	char            *buf;
	size_t           buf_len;

#ifdef NNG_ENABLE_IPV6
	bool  v6      = false;
	bool  wrapped = false;
	char *s;
#endif

	if (addr == NULL) {
		addr = "";
	}

	buf_len = strlen(addr) + 1;
	if ((buf = nni_alloc(buf_len)) == NULL) {
		return (NNG_ENOMEM);
	}
	memcpy(buf, addr, buf_len);
	host = buf;
#ifdef NNG_ENABLE_IPV6
	if (*host == '[') {
		v6      = true;
		wrapped = true;
		host++;
	} else {
		for (s = host; *s != '\0'; s++) {
			if (*s == '.') {
				break;
			}
			if (*s == ':') {
				v6 = true;
				break;
			}
		}
	}
	for (port = host; *port != '\0'; port++) {
		if (wrapped) {
			if (*port == ']') {
				*port++ = '\0';
				wrapped = false;
				break;
			}
		} else if (!v6) {
			if (*port == ':') {
				break;
			}
		}
	}

	if (wrapped) {
		// Never got the closing bracket.
		rv = NNG_EADDRINVAL;
		goto done;
	}
#else  // NNG_ENABLE_IPV6
	for (port = host; *port != '\0'; port++) {
		if (*port == ':') {
			break;
		}
	}
#endif // NNG_ENABLE_IPV6

	if ((!want_port) && (*port != '\0')) {
		rv = NNG_EADDRINVAL;
		goto done;
	} else if (*port == ':') {
		*port++ = '\0';
	}

	if (*port == '\0') {
		port = "0";
	}

	memset(&hints, 0, sizeof(hints));
	hints.ai_flags = AI_NUMERICSERV | AI_NUMERICHOST | AI_PASSIVE;
#ifdef NNG_ENABLE_IPV6
	if (v6) {
		hints.ai_family = AF_INET6;
	}
#else
	hints.ai_family = AF_INET;
#endif
#ifdef AI_ADDRCONFIG
	hints.ai_flags |= AI_ADDRCONFIG;
#endif

	rv = getaddrinfo(host, port, &hints, &results);
	if ((rv != 0) || (results == NULL)) {
		rv = nni_plat_errno(rv);
		goto done;
	}
	nni_posix_sockaddr2nn(
	    sa, (void *) results->ai_addr, results->ai_addrlen);
	freeaddrinfo(results);

done:
	nni_free(buf, buf_len);
	return (rv);
}

int
nni_parse_ip(const char *addr, nni_sockaddr *sa)
{
	return (parse_ip(addr, sa, false));
}

int
nni_parse_ip_port(const char *addr, nni_sockaddr *sa)
{
	return (parse_ip(addr, sa, true));
}

int
nni_get_port_by_name(const char *name, uint32_t *portp)
{
	struct servent *se;
	long            port;
	char           *end = NULL;

	port = strtol(name, &end, 10);
	if ((*end == '\0') && (port >= 0) && (port <= 0xffff)) {
		*portp = (uint16_t) port;
		return (0);
	}

	if ((se = getservbyname(name, "tcp")) != NULL) {
		*portp = (uint16_t) ntohs(se->s_port);
		return (0);
	}
	return (NNG_EADDRINVAL);
}

int
nni_posix_resolv_sysinit(nng_init_params *params)
{
	resolv_fini = false;
	nni_aio_list_init(&resolv_aios);

	resolv_num_thr = params->num_resolver_threads;
	if (resolv_num_thr < 1) {
		resolv_num_thr = 1;
	}
	params->num_resolver_threads = resolv_num_thr;
	// no limit on the maximum for now
	resolv_thrs = NNI_ALLOC_STRUCTS(resolv_thrs, resolv_num_thr);
	if (resolv_thrs == NULL) {
		return (NNG_ENOMEM);
	}

	for (int i = 0; i < resolv_num_thr; i++) {
		int rv = nni_thr_init(&resolv_thrs[i], resolv_worker, NULL);
		if (rv != 0) {
			nni_posix_resolv_sysfini();
			return (rv);
		}
	}
	for (int i = 0; i < resolv_num_thr; i++) {
		nni_thr_run(&resolv_thrs[i]);
	}

	return (0);
}

void
nni_posix_resolv_sysfini(void)
{
	nni_mtx_lock(&resolv_mtx);
	resolv_fini = true;
	nni_cv_wake(&resolv_cv);
	nni_mtx_unlock(&resolv_mtx);

	if (resolv_thrs != NULL) {
		for (int i = 0; i < resolv_num_thr; i++) {
			nni_thr_fini(&resolv_thrs[i]);
		}
		NNI_FREE_STRUCTS(resolv_thrs, resolv_num_thr);
	}
}

#endif // NNG_USE_POSIX_RESOLV_GAI