xref: /openbsd-src/lib/libc/asr/res_init.c (revision 38a63ed178c3f19f41ef0c3434b850a5cf50fd7e)
1 /*	$OpenBSD: res_init.c,v 1.3 2014/01/15 02:25:34 sthen 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 	int i;
41 
42 	ac = asr_use_resolver(NULL);
43 
44 	/*
45 	 * The first thread to call res_init() will setup the global _res
46 	 * structure from the async context, not overriding fields set early
47 	 * by the user.
48 	 */
49 	_THREAD_PRIVATE_MUTEX_LOCK(init);
50 	if (!(_res.options & RES_INIT)) {
51 		if (_res.retry == 0)
52 			_res.retry = ac->ac_nsretries;
53 		if (_res.options == 0)
54 			_res.options = ac->ac_options;
55 		if (_res.lookups[0] == '\0')
56 			strlcpy(_res.lookups, ac->ac_db, sizeof(_res.lookups));
57 
58 		_res.nscount = ac->ac_nscount;
59 		for (i = 0; i < ac->ac_nscount; i++) {
60 			memcpy(&_res.nsaddr_list[i], ac->ac_ns[i],
61 			    ac->ac_ns[i]->sa_len);
62 		}
63 		_res.options |= RES_INIT;
64 	}
65 	_THREAD_PRIVATE_MUTEX_UNLOCK(init);
66 
67 	/*
68 	 * If the program is not threaded, we want to reflect (some) changes
69 	 * made by the user to the global _res structure.
70 	 * This is a bit of a hack: if there is already an async query on
71 	 * this context, it might change things in its back.  It is ok
72 	 * as long as the user only uses the blocking resolver API.
73 	 * If needed we could consider cloning the context if there is
74 	 * a running query.
75 	 */
76 	if (!__isthreaded) {
77 		ac->ac_nsretries = _res.retry;
78 		ac->ac_options = _res.options;
79 		strlcpy(ac->ac_db, _res.lookups, sizeof(ac->ac_db));
80 		ac->ac_dbcount = strlen(ac->ac_db);
81 	}
82 
83 	asr_ctx_unref(ac);
84 
85 	return (0);
86 }
87