xref: /aosp_15_r20/external/cronet/net/dns/public/scoped_res_state.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2021 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/dns/public/scoped_res_state.h"
6 
7 #include <cstring>
8 #include <memory>
9 
10 #include "base/check.h"
11 #include "build/build_config.h"
12 
13 namespace net {
14 
ScopedResState()15 ScopedResState::ScopedResState() {
16 #if BUILDFLAG(IS_OPENBSD) || BUILDFLAG(IS_FUCHSIA)
17   // Note: res_ninit in glibc always returns 0 and sets RES_INIT.
18   // res_init behaves the same way.
19   memset(&_res, 0, sizeof(_res));
20   res_init_result_ = res_init();
21 #else
22   memset(&res_, 0, sizeof(res_));
23   res_init_result_ = res_ninit(&res_);
24 #endif  // BUILDFLAG(IS_OPENBSD) || BUILDFLAG(IS_FUCHSIA)
25 }
26 
~ScopedResState()27 ScopedResState::~ScopedResState() {
28 #if !BUILDFLAG(IS_OPENBSD) && !BUILDFLAG(IS_FUCHSIA)
29 
30   // Prefer res_ndestroy where available.
31 #if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_FREEBSD)
32   res_ndestroy(&res_);
33 #else
34   res_nclose(&res_);
35 #endif  // BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_FREEBSD)
36 
37 #endif  // !BUILDFLAG(IS_OPENBSD) && !BUILDFLAG(IS_FUCHSIA)
38 }
39 
IsValid() const40 bool ScopedResState::IsValid() const {
41   return res_init_result_ == 0;
42 }
43 
state() const44 const struct __res_state& ScopedResState::state() const {
45   DCHECK(IsValid());
46 #if BUILDFLAG(IS_OPENBSD) || BUILDFLAG(IS_FUCHSIA)
47   return _res;
48 #else
49   return res_;
50 #endif  // BUILDFLAG(IS_OPENBSD) || BUILDFLAG(IS_FUCHSIA)
51 }
52 
53 }  // namespace net
54