context.c 12.8 KB
Newer Older
Michael Graff's avatar
Michael Graff committed
1
/*
Automatic Updater's avatar
Automatic Updater committed
2
 * Copyright (C) 2004, 2005, 2007, 2008  Internet Systems Consortium, Inc. ("ISC")
Mark Andrews's avatar
Mark Andrews committed
3
 * Copyright (C) 2000, 2001, 2003  Internet Software Consortium.
4
 *
Automatic Updater's avatar
Automatic Updater committed
5
 * Permission to use, copy, modify, and/or distribute this software for any
Michael Graff's avatar
Michael Graff committed
6 7
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
8
 *
Mark Andrews's avatar
Mark Andrews committed
9 10 11 12 13 14 15
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
Michael Graff's avatar
Michael Graff committed
16 17
 */

Automatic Updater's avatar
Automatic Updater committed
18
/* $Id: context.c,v 1.52 2008/12/17 23:47:58 tbox Exp $ */
19

Automatic Updater's avatar
Automatic Updater committed
20
/*! \file context.c
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
   lwres_context_create() creates a #lwres_context_t structure for use in
   lightweight resolver operations. It holds a socket and other data
   needed for communicating with a resolver daemon. The new
   lwres_context_t is returned through contextp, a pointer to a
   lwres_context_t pointer. This lwres_context_t pointer must initially
   be NULL, and is modified to point to the newly created
   lwres_context_t.

   When the lightweight resolver needs to perform dynamic memory
   allocation, it will call malloc_function to allocate memory and
   free_function to free it. If malloc_function and free_function are
   NULL, memory is allocated using malloc and free. It is not
   permitted to have a NULL malloc_function and a non-NULL free_function
   or vice versa. arg is passed as the first parameter to the memory
   allocation functions. If malloc_function and free_function are NULL,
   arg is unused and should be passed as NULL.

   Once memory for the structure has been allocated, it is initialized
   using lwres_conf_init() and returned via *contextp.

   lwres_context_destroy() destroys a #lwres_context_t, closing its
   socket. contextp is a pointer to a pointer to the context that is to
   be destroyed. The pointer will be set to NULL when the context has
   been destroyed.

   The context holds a serial number that is used to identify resolver
   request packets and associate responses with the corresponding
   requests. This serial number is controlled using
   lwres_context_initserial() and lwres_context_nextserial().
   lwres_context_initserial() sets the serial number for context *ctx to
   serial. lwres_context_nextserial() increments the serial number and
   returns the previous value.

   Memory for a lightweight resolver context is allocated and freed using
   lwres_context_allocmem() and lwres_context_freemem(). These use
   whatever allocations were defined when the context was created with
   lwres_context_create(). lwres_context_allocmem() allocates len bytes
   of memory and if successful returns a pointer to the allocated
   storage. lwres_context_freemem() frees len bytes of space starting at
   location mem.

   lwres_context_sendrecv() performs I/O for the context ctx. Data are
   read and written from the context's socket. It writes data from
   sendbase -- typically a lightweight resolver query packet -- and waits
   for a reply which is copied to the receive buffer at recvbase. The
   number of bytes that were written to this receive buffer is returned
   in *recvd_len.

\section context_return Return Values

   lwres_context_create() returns #LWRES_R_NOMEMORY if memory for the
   struct lwres_context could not be allocated, #LWRES_R_SUCCESS
   otherwise.

   Successful calls to the memory allocator lwres_context_allocmem()
   return a pointer to the start of the allocated space. It returns NULL
   if memory could not be allocated.

   #LWRES_R_SUCCESS is returned when lwres_context_sendrecv() completes
   successfully. #LWRES_R_IOERROR is returned if an I/O error occurs and
   #LWRES_R_TIMEOUT is returned if lwres_context_sendrecv() times out
   waiting for a response.

\section context_see See Also

   lwres_conf_init(), malloc, free.
 */
Michael Graff's avatar
Michael Graff committed
88 89
#include <config.h>

Michael Graff's avatar
Michael Graff committed
90
#include <fcntl.h>
91
#include <limits.h>
Michael Graff's avatar
Michael Graff committed
92 93
#include <stdlib.h>
#include <string.h>
Brian Wellington's avatar
Brian Wellington committed
94
#include <time.h>
95 96 97
#include <unistd.h>

#include <lwres/lwres.h>
Brian Wellington's avatar
Brian Wellington committed
98
#include <lwres/net.h>
99 100 101 102 103
#include <lwres/platform.h>

#ifdef LWRES_PLATFORM_NEEDSYSSELECTH
#include <sys/select.h>
#endif
Michael Graff's avatar
Michael Graff committed
104 105 106 107

#include "context_p.h"
#include "assert_p.h"

108
/*!
109 110 111 112 113 114 115 116
 * Some systems define the socket length argument as an int, some as size_t,
 * some as socklen_t.  The last is what the current POSIX standard mandates.
 * This definition is here so it can be portable but easily changed if needed.
 */
#ifndef LWRES_SOCKADDR_LEN_T
#define LWRES_SOCKADDR_LEN_T unsigned int
#endif

117
/*!
Andreas Gustafsson's avatar
Andreas Gustafsson committed
118
 * Make a socket nonblocking.
Danny Mayer's avatar
Danny Mayer committed
119 120
 */
#ifndef MAKE_NONBLOCKING
Andreas Gustafsson's avatar
Andreas Gustafsson committed
121 122 123 124
#define MAKE_NONBLOCKING(sd, retval) \
do { \
	retval = fcntl(sd, F_GETFL, 0); \
	if (retval != -1) { \
125
		retval |= O_NONBLOCK; \
Andreas Gustafsson's avatar
Andreas Gustafsson committed
126 127
		retval = fcntl(sd, F_SETFL, retval); \
	} \
Danny Mayer's avatar
Danny Mayer committed
128 129 130
} while (0)
#endif

131 132
LIBLWRES_EXTERNAL_DATA lwres_uint16_t lwres_udp_port = LWRES_UDP_PORT;
LIBLWRES_EXTERNAL_DATA const char *lwres_resolv_conf = LWRES_RESOLV_CONF;
133

134 135 136 137 138 139
static void *
lwres_malloc(void *, size_t);

static void
lwres_free(void *, void *, size_t);

140 141 142
/*!
 * lwres_result_t
 */
143 144
static lwres_result_t
context_connect(lwres_context_t *);
Michael Graff's avatar
Michael Graff committed
145

146 147 148 149
/*%
 * Creates a #lwres_context_t structure for use in
 *  lightweight resolver operations.
 */
150
lwres_result_t
Michael Graff's avatar
Michael Graff committed
151 152
lwres_context_create(lwres_context_t **contextp, void *arg,
		     lwres_malloc_t malloc_function,
Michael Graff's avatar
Michael Graff committed
153 154
		     lwres_free_t free_function,
		     unsigned int flags)
Michael Graff's avatar
Michael Graff committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
{
	lwres_context_t *ctx;

	REQUIRE(contextp != NULL && *contextp == NULL);

	/*
	 * If we were not given anything special to use, use our own
	 * functions.  These are just wrappers around malloc() and free().
	 */
	if (malloc_function == NULL || free_function == NULL) {
		REQUIRE(malloc_function == NULL);
		REQUIRE(free_function == NULL);
		malloc_function = lwres_malloc;
		free_function = lwres_free;
	}

	ctx = malloc_function(arg, sizeof(lwres_context_t));
172 173
	if (ctx == NULL)
		return (LWRES_R_NOMEMORY);
Michael Graff's avatar
Michael Graff committed
174 175 176 177 178 179 180

	/*
	 * Set up the context.
	 */
	ctx->malloc = malloc_function;
	ctx->free = free_function;
	ctx->arg = arg;
181
	ctx->sock = -1;
Michael Graff's avatar
Michael Graff committed
182 183

	ctx->timeout = LWRES_DEFAULT_TIMEOUT;
184
	ctx->serial = time(NULL); /* XXXMLG or BEW */
Michael Graff's avatar
Michael Graff committed
185

186 187 188 189 190 191 192 193 194 195 196
	ctx->use_ipv4 = 1;
	ctx->use_ipv6 = 1;
	if ((flags & (LWRES_CONTEXT_USEIPV4 | LWRES_CONTEXT_USEIPV6)) ==
	    LWRES_CONTEXT_USEIPV6) {
		ctx->use_ipv4 = 0;
	}
	if ((flags & (LWRES_CONTEXT_USEIPV4 | LWRES_CONTEXT_USEIPV6)) ==
	    LWRES_CONTEXT_USEIPV4) {
		ctx->use_ipv6 = 0;
	}

197 198 199 200 201
	/*
	 * Init resolv.conf bits.
	 */
	lwres_conf_init(ctx);

Michael Graff's avatar
Michael Graff committed
202
	*contextp = ctx;
203
	return (LWRES_R_SUCCESS);
Michael Graff's avatar
Michael Graff committed
204 205
}

206
/*%
Automatic Updater's avatar
Automatic Updater committed
207 208 209
Destroys a #lwres_context_t, closing its socket.
contextp is a pointer to a pointer to the context that is
to be destroyed. The pointer will be set to NULL
210 211
when the context has been destroyed.
 */
Michael Graff's avatar
Michael Graff committed
212
void
213
lwres_context_destroy(lwres_context_t **contextp) {
Michael Graff's avatar
Michael Graff committed
214 215 216 217 218 219 220
	lwres_context_t *ctx;

	REQUIRE(contextp != NULL && *contextp != NULL);

	ctx = *contextp;
	*contextp = NULL;

221
	if (ctx->sock != -1) {
222 223 224
#ifdef WIN32
		DestroySockets();
#endif
225
		(void)close(ctx->sock);
226 227 228
		ctx->sock = -1;
	}

Michael Graff's avatar
Michael Graff committed
229 230
	CTXFREE(ctx, sizeof(lwres_context_t));
}
231
/*% Increments the serial number and returns the previous value. */
232
lwres_uint32_t
233
lwres_context_nextserial(lwres_context_t *ctx) {
Michael Graff's avatar
Michael Graff committed
234 235 236 237 238
	REQUIRE(ctx != NULL);

	return (ctx->serial++);
}

239
/*% Sets the serial number for context *ctx to serial. */
Michael Graff's avatar
Michael Graff committed
240
void
241
lwres_context_initserial(lwres_context_t *ctx, lwres_uint32_t serial) {
Michael Graff's avatar
Michael Graff committed
242 243 244 245 246
	REQUIRE(ctx != NULL);

	ctx->serial = serial;
}

247
/*% Frees len bytes of space starting at location mem. */
Michael Graff's avatar
Michael Graff committed
248
void
249
lwres_context_freemem(lwres_context_t *ctx, void *mem, size_t len) {
Michael Graff's avatar
Michael Graff committed
250
	REQUIRE(mem != NULL);
251
	REQUIRE(len != 0U);
Michael Graff's avatar
Michael Graff committed
252 253 254 255

	CTXFREE(mem, len);
}

256
/*% Allocates len bytes of memory and if successful returns a pointer to the allocated storage. */
Michael Graff's avatar
Michael Graff committed
257
void *
258
lwres_context_allocmem(lwres_context_t *ctx, size_t len) {
259
	REQUIRE(len != 0U);
Michael Graff's avatar
Michael Graff committed
260 261 262 263 264

	return (CTXMALLOC(len));
}

static void *
265
lwres_malloc(void *arg, size_t len) {
Michael Graff's avatar
Michael Graff committed
266 267
	void *mem;

268
	UNUSED(arg);
Michael Graff's avatar
Michael Graff committed
269 270 271 272 273 274 275 276 277 278 279

	mem = malloc(len);
	if (mem == NULL)
		return (NULL);

	memset(mem, 0xe5, len);

	return (mem);
}

static void
280
lwres_free(void *arg, void *mem, size_t len) {
281
	UNUSED(arg);
Michael Graff's avatar
Michael Graff committed
282 283 284 285

	memset(mem, 0xa9, len);
	free(mem);
}
286

287
static lwres_result_t
288
context_connect(lwres_context_t *ctx) {
289 290
	int s;
	int ret;
291 292 293
	struct sockaddr_in sin;
	struct sockaddr_in6 sin6;
	struct sockaddr *sa;
Brian Wellington's avatar
Brian Wellington committed
294
	LWRES_SOCKADDR_LEN_T salen;
295 296 297 298 299 300 301
	int domain;

	if (ctx->confdata.lwnext != 0) {
		memcpy(&ctx->address, &ctx->confdata.lwservers[0],
		       sizeof(lwres_addr_t));
		LWRES_LINK_INIT(&ctx->address, link);
	} else {
302 303 304 305 306 307 308 309
		/* The default is the IPv4 loopback address 127.0.0.1. */
		memset(&ctx->address, 0, sizeof(ctx->address));
		ctx->address.family = LWRES_ADDRTYPE_V4;
		ctx->address.length = 4;
		ctx->address.address[0] = 127;
		ctx->address.address[1] = 0;
		ctx->address.address[2] = 0;
		ctx->address.address[3] = 1;
310
	}
311

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
	if (ctx->address.family == LWRES_ADDRTYPE_V4) {
		memcpy(&sin.sin_addr, ctx->address.address,
		       sizeof(sin.sin_addr));
		sin.sin_port = htons(lwres_udp_port);
		sin.sin_family = AF_INET;
		sa = (struct sockaddr *)&sin;
		salen = sizeof(sin);
		domain = PF_INET;
	} else if (ctx->address.family == LWRES_ADDRTYPE_V6) {
		memcpy(&sin6.sin6_addr, ctx->address.address,
		       sizeof(sin6.sin6_addr));
		sin6.sin6_port = htons(lwres_udp_port);
		sin6.sin6_family = AF_INET6;
		sa = (struct sockaddr *)&sin6;
		salen = sizeof(sin6);
		domain = PF_INET6;
	} else
		return (LWRES_R_IOERROR);
330

331 332 333
#ifdef WIN32
	InitSockets();
#endif
334
	s = socket(domain, SOCK_DGRAM, IPPROTO_UDP);
335 336 337 338
	if (s < 0) {
#ifdef WIN32
		DestroySockets();
#endif
339
		return (LWRES_R_IOERROR);
340
	}
341

342
	ret = connect(s, sa, salen);
343
	if (ret != 0) {
344 345 346
#ifdef WIN32
		DestroySockets();
#endif
347
		(void)close(s);
348
		return (LWRES_R_IOERROR);
349 350
	}

Andreas Gustafsson's avatar
Andreas Gustafsson committed
351
	MAKE_NONBLOCKING(s, ret);
352 353 354 355 356
	if (ret < 0) {
#ifdef WIN32
		DestroySockets();
#endif
		(void)close(s);
357
		return (LWRES_R_IOERROR);
358
	}
359

360 361
	ctx->sock = s;

362
	return (LWRES_R_SUCCESS);
363 364
}

365 366 367 368 369 370 371 372 373
int
lwres_context_getsocket(lwres_context_t *ctx) {
	return (ctx->sock);
}

lwres_result_t
lwres_context_send(lwres_context_t *ctx,
		   void *sendbase, int sendlen) {
	int ret;
374 375 376 377 378 379 380 381
	lwres_result_t lwresult;

	if (ctx->sock == -1) {
		lwresult = context_connect(ctx);
		if (lwresult != LWRES_R_SUCCESS)
			return (lwresult);
	}

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
	ret = sendto(ctx->sock, sendbase, sendlen, 0, NULL, 0);
	if (ret < 0)
		return (LWRES_R_IOERROR);
	if (ret != sendlen)
		return (LWRES_R_IOERROR);

	return (LWRES_R_SUCCESS);
}

lwres_result_t
lwres_context_recv(lwres_context_t *ctx,
		   void *recvbase, int recvlen,
		   int *recvd_len)
{
	LWRES_SOCKADDR_LEN_T fromlen;
	struct sockaddr_in sin;
398 399
	struct sockaddr_in6 sin6;
	struct sockaddr *sa;
400 401
	int ret;

402 403 404 405 406 407 408 409
	if (ctx->address.family == LWRES_ADDRTYPE_V4) {
		sa = (struct sockaddr *)&sin;
		fromlen = sizeof(sin);
	} else {
		sa = (struct sockaddr *)&sin6;
		fromlen = sizeof(sin6);
	}

410 411 412 413 414 415
	/*
	 * The address of fromlen is cast to void * to shut up compiler
	 * warnings, namely on systems that have the sixth parameter
	 * prototyped as a signed int when LWRES_SOCKADDR_LEN_T is
	 * defined as unsigned.
	 */
416
	ret = recvfrom(ctx->sock, recvbase, recvlen, 0, sa, (void *)&fromlen);
417 418 419 420

	if (ret < 0)
		return (LWRES_R_IOERROR);

421 422 423
	if (ret == recvlen)
		return (LWRES_R_TOOLARGE);

424 425 426 427 428
	/*
	 * If we got something other than what we expect, have the caller
	 * wait for another packet.  This can happen if an old result
	 * comes in, or if someone is sending us random stuff.
	 */
429 430 431 432 433 434 435 436 437 438 439 440 441
	if (ctx->address.family == LWRES_ADDRTYPE_V4) {
		if (fromlen != sizeof(sin)
		    || memcmp(&sin.sin_addr, ctx->address.address,
			      sizeof(sin.sin_addr)) != 0
		    || sin.sin_port != htons(lwres_udp_port))
			return (LWRES_R_RETRY);
	} else {
		if (fromlen != sizeof(sin6)
		    || memcmp(&sin6.sin6_addr, ctx->address.address,
			      sizeof(sin6.sin6_addr)) != 0
		    || sin6.sin6_port != htons(lwres_udp_port))
			return (LWRES_R_RETRY);
	}
442 443 444 445 446 447 448

	if (recvd_len != NULL)
		*recvd_len = ret;

	return (LWRES_R_SUCCESS);
}

449
/*% performs I/O for the context ctx. */
450
lwres_result_t
451 452
lwres_context_sendrecv(lwres_context_t *ctx,
		       void *sendbase, int sendlen,
453 454
		       void *recvbase, int recvlen,
		       int *recvd_len)
455
{
456
	lwres_result_t result;
Michael Graff's avatar
Michael Graff committed
457 458 459 460
	int ret2;
	fd_set readfds;
	struct timeval timeout;

461
	/*
Automatic Updater's avatar
Automatic Updater committed
462
	 * Type of tv_sec is 32 bits long.
463
	 */
Mark Andrews's avatar
Mark Andrews committed
464 465
	if (ctx->timeout <= 0x7FFFFFFFU)
		timeout.tv_sec = (int)ctx->timeout;
466
	else
Mark Andrews's avatar
Mark Andrews committed
467
		timeout.tv_sec = 0x7FFFFFFF;
468

Michael Graff's avatar
Michael Graff committed
469
	timeout.tv_usec = 0;
470

471 472 473
	result = lwres_context_send(ctx, sendbase, sendlen);
	if (result != LWRES_R_SUCCESS)
		return (result);
474
 again:
Michael Graff's avatar
Michael Graff committed
475 476
	FD_ZERO(&readfds);
	FD_SET(ctx->sock, &readfds);
477
	ret2 = select(ctx->sock + 1, &readfds, NULL, NULL, &timeout);
Automatic Updater's avatar
Automatic Updater committed
478

Michael Graff's avatar
Michael Graff committed
479 480 481 482 483 484 485 486
	/*
	 * What happened with select?
	 */
	if (ret2 < 0)
		return (LWRES_R_IOERROR);
	if (ret2 == 0)
		return (LWRES_R_TIMEOUT);

487 488
	result = lwres_context_recv(ctx, recvbase, recvlen, recvd_len);
	if (result == LWRES_R_RETRY)
489
		goto again;
Automatic Updater's avatar
Automatic Updater committed
490

491
	return (result);
492
}