xref: /openbsd/lib/libc/asr/res_init.c (revision 1ed934d0)
1 /*	$OpenBSD: res_init.c,v 1.2 2013/05/27 17:31:01 eric Exp $	*/
2 /*
3  * Copyright (c) 2012 Eric Faurot <eric@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <sys/types.h>
19 #include <arpa/nameser.h>
20 #include <netinet/in.h>
21 
22 #include <resolv.h>
23 #include <string.h>
24 
25 #include "asr.h"
26 #include "asr_private.h"
27 #include "thread_private.h"
28 
29 
30 struct __res_state _res;
31 struct __res_state_ext _res_ext;
32 
33 int h_errno;
34 
35 int
36 res_init(void)
37 {
38 	_THREAD_PRIVATE_MUTEX(init);
39 	struct asr_ctx	*ac;
40 
41 	ac = asr_use_resolver(NULL);
42 
43 	/*
44 	 * The first thread to call res_init() will setup the global _res
45 	 * structure from the async context, not overriding fields set early
46 	 * by the user.
47 	 */
48 	_THREAD_PRIVATE_MUTEX_LOCK(init);
49 	if (!(_res.options & RES_INIT)) {
50 		if (_res.retry == 0)
51 			_res.retry = ac->ac_nsretries;
52 		if (_res.options == 0)
53 			_res.options = ac->ac_options;
54 		if (_res.lookups[0] == '\0')
55 			strlcpy(_res.lookups, ac->ac_db, sizeof(_res.lookups));
56 
57 		_res.nscount = ac->ac_nscount;
58 		_res.options |= RES_INIT;
59 	}
60 	_THREAD_PRIVATE_MUTEX_UNLOCK(init);
61 
62 	/*
63 	 * If the program is not threaded, we want to reflect (some) changes
64 	 * made by the user to the global _res structure.
65 	 * This is a bit of a hack: if there is already an async query on
66 	 * this context, it might change things in its back.  It is ok
67 	 * as long as the user only uses the blocking resolver API.
68 	 * If needed we could consider cloning the context if there is
69 	 * a running query.
70 	 */
71 	if (!__isthreaded) {
72 		ac->ac_nsretries = _res.retry;
73 		ac->ac_options = _res.options;
74 		strlcpy(ac->ac_db, _res.lookups, sizeof(ac->ac_db));
75 		ac->ac_dbcount = strlen(ac->ac_db);
76 	}
77 
78 	asr_ctx_unref(ac);
79 
80 	return (0);
81 }
82