cdns-rs 2.0.0-next.0

A native Sync/Async Rust implementation of client DNS resolver.
Documentation
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
/*-
 * cdns-rs - a simple sync/async DNS query library
 * 
 * Copyright (C) 2021  Aleksandr Morozov
 * Copyright (C) 2025  Aleksandr Morozov
 * Copyright (C) 2026  Aleksandr Morozov, 4neko.org
 * 
 * The syslog-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *
 *   2. The MIT License (MIT)
 *                     
 *   3. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */

use std::
{
    fmt, fs::File, io::Read, marker::PhantomData, path::{Path, PathBuf}, sync::OnceLock
};

use instance_copy_on_write::{ICoW, ICoWError, ICoWRead, cow_mutex::ICoWWeak};

use crate::
{
    CDnsErrorType, 
    CDnsResult, 
    HostConfig, 
    ResolveConfig, 
    common, 
    internal_error, 
    internal_error_map
};

/// A global config. Should be initialized using [DnsConfigs<DnsConfigGlobal>].
pub static GLOBAL_CONFIG: OnceLock<DnsConfigs<DnsConfigGlobal>> = OnceLock::new();

pub trait ConfigGetter
{
    fn get_hosts(&self) -> &DnsConfig<HostConfig>;

    fn get_resolv(&self) -> &DnsConfig<ResolveConfig>;
}

pub trait DnsConfigReader: fmt::Debug
{
    type RetItem;

    fn read_config(&self) -> ICoWRead<'_, Self::RetItem>;

    fn get_reader(&self) -> ICoWWeak<Self::RetItem>;
}

pub trait DnsConfigUpdater: fmt::Debug
{
    type NewItem;

    fn get_path_to_file(&self) -> Option<&Path>;

    fn update_in_place(&self, new_item: Self::NewItem) -> CDnsResult<()>;
}


#[derive(Debug)]
pub struct DnsConfig<CFG: fmt::Debug>
{
    file_path: Option<PathBuf>,

    /// hosts file
    conf: ICoW<CFG>
}

impl<CFG: fmt::Debug> DnsConfig<CFG>
{
    fn new(file_path: &Path, conf: CFG) -> Self
    {
        return 
            Self
            {
                file_path: Some(file_path.to_path_buf()),
                conf: ICoW::new(conf),
            };
    }

    fn new_local(conf: CFG) -> Self
    {
        return 
            Self
            {
                file_path: None,
                conf: ICoW::new(conf),
            };
    }
}

impl<CFG: fmt::Debug> DnsConfigReader for DnsConfig<CFG>
{
    type RetItem = CFG;

    fn read_config(&self) -> ICoWRead<'_, Self::RetItem> 
    {
        return self.conf.read();
    }

    fn get_reader(&self) -> ICoWWeak<Self::RetItem>
    {
        return self.conf.reader();
    }
}

impl<CFG: fmt::Debug> DnsConfigUpdater for DnsConfig<CFG>
{
    type NewItem = CFG;

    fn get_path_to_file(&self) -> Option<&Path>
    {
        return self.file_path.as_ref().map(|f| f.as_path());
    }

    fn update_in_place(&self, new_item: Self::NewItem) -> CDnsResult<()> 
    {
        let mut commit_item = new_item;

        loop
        {
            let Err((err, ret_item)) = self.conf.try_new_inplace(commit_item)
                else
                {
                    return Ok(());
                };

            match err
            {
                ICoWError::ExclusiveLockPending =>
                    internal_error!(CDnsErrorType::SoftAssertion, 
                        "update_in_place() exclusive lock pending error, not exclusive lock should be held!"),
                ICoWError::WouldBlock => 
                {
                    commit_item = ret_item;
                }
            }
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum DnsConfigSource<'s, CFG>
{
    SourceFile(&'s Path),
    SourceText(&'s str),
    SourceInstance(CFG),
}

pub trait DnsConfigDest {}

#[derive(Debug)]
pub struct DnsConfigGlobal;

impl DnsConfigDest for DnsConfigGlobal {}

#[derive(Debug)]
pub struct DnsConfigUser;

impl DnsConfigDest for DnsConfigUser {}

#[derive(Debug)]
pub struct DnsConfigs<DEST: DnsConfigDest>
{
    /// hosts file
    hosts_conf: DnsConfig<HostConfig>,

    /// resolv.conf file
    resolv_conf: DnsConfig<ResolveConfig>,

    _p: PhantomData<DEST>
}

impl DnsConfigs<DnsConfigGlobal>
{
    pub 
    fn init_global_config(opt_conf: Option<DnsConfigs<DnsConfigGlobal>>) -> CDnsResult<()> 
    {
        let global_cfg = 
            opt_conf.unwrap_or(DnsConfigs::new_system()?);

        return 
            GLOBAL_CONFIG
                .set(global_cfg)
                .map_err(|_c|
                    internal_error_map!(CDnsErrorType::SoftAssertion, "GLOBAL_CONFIG already inited!")
                );
    }

    pub 
    fn reload_hosts(&self) -> CDnsResult<()>
    {
        let hosts_cfg = Self::load_host(self.hosts_conf.get_path_to_file().unwrap())?;

        return self.hosts_conf.update_in_place(hosts_cfg);
    }

    pub 
    fn reload_resolv(&self) -> CDnsResult<()>
    {
        let resolv_cfg = Self::load_resolv(self.resolv_conf.get_path_to_file().unwrap())?;

        return self.resolv_conf.update_in_place(resolv_cfg);
    }
}

impl DnsConfigs<DnsConfigUser>
{
    /// This function updates the `hosts`. If `raw_cfg` contains a hosts file from somewhere
    /// else, it will be used ignoring the path.
    /// 
    /// If `raw_cfg` is [Option::None] and the internal path is also [Option::None],
    /// the error will be returned.
    pub 
    fn reload_hosts(&self, raw_cfg: Option<String>) -> CDnsResult<()>
    {
        let Some(raw_cfgtext) = raw_cfg
            else
            {
                // try the path
                let Some(file_path) = self.hosts_conf.get_path_to_file()
                    else
                    {
                        internal_error!(CDnsErrorType::ConfigError, "cannot reload hosts, no data provided!")
                    };  

                let hosts_cfg = Self::load_host(file_path)?;

                return self.hosts_conf.update_in_place(hosts_cfg);
            };

        let hosts = HostConfig::parse_host_file_internal(&raw_cfgtext)?; 

        return self.hosts_conf.update_in_place(hosts);
    }

    /// This function updates the `resolv.conf`. If `raw_cfg` contains a hosts file from somewhere
    /// else, it will be used ignoring the path.
    /// 
    /// If `raw_cfg` is [Option::None] and the internal path is also [Option::None],
    /// the error will be returned.
    pub 
    fn reload_resolv(&self, raw_cfg: Option<String>) -> CDnsResult<()>
    {
        let Some(raw_cfgtext) = raw_cfg
            else
            {
                // try the path
                let Some(file_path) = self.resolv_conf.get_path_to_file()
                    else
                    {
                        internal_error!(CDnsErrorType::ConfigError, "cannot reload resolv.conf, no data provided!")
                    };  

                let resolv_cfg = Self::load_resolv(file_path)?;

                return self.resolv_conf.update_in_place(resolv_cfg);
            };

        let resolv_conf = ResolveConfig::parser_resolv_internal(&raw_cfgtext)?; 

        return self.resolv_conf.update_in_place(resolv_conf);
    }
}

impl<DEST: DnsConfigDest> DnsConfigs<DEST>
{
    fn load_file(file_path: &Path) -> CDnsResult<String>
    {
        let mut hosts_conf = 
            File::options()
                .read(true)
                .open(file_path)
                .map_err(|e|
                    internal_error_map!(CDnsErrorType::IoError, 
                        "cannot read file {}, error: {}", file_path.display(), e)
                )?;

        let mut contents = String::new();

        hosts_conf
            .read_to_string(&mut contents)
            .map_err(|e|
                internal_error_map!(CDnsErrorType::IoError, 
                        "cannot read file {}, error: {}", file_path.display(), e)
            )?;

        return Ok(contents);
    }

    pub 
    fn load_host(file_path: &Path) -> CDnsResult<HostConfig>
    {
        let contents = Self::load_file(file_path)?;

        return HostConfig::parse_host_file_internal(&contents); 
    }

    pub 
    fn load_resolv(file_path: &Path) -> CDnsResult<ResolveConfig>
    {
        let contents = Self::load_file(file_path)?;

        return ResolveConfig::parser_resolv_internal(&contents); 
    }

    pub 
    fn new_system() -> CDnsResult<Self>
    {
        let hosts_path = Path::new(common::HOST_CFG_PATH);
        let hosts = 
            DnsConfig::<HostConfig>::new(hosts_path, Self::load_host(hosts_path)? );

        let resolv_path = Path::new(common::RESOLV_CFG_PATH);
        let resolv = 
            DnsConfig::<ResolveConfig>::new(resolv_path, Self::load_resolv(resolv_path)?);

        return Ok(
            Self
            {
                hosts_conf: hosts,
                resolv_conf: resolv,
                _p: PhantomData,
            }
        );
    }

    pub 
    fn new_custom(hosts: DnsConfigSource<'_, HostConfig>, resolv: DnsConfigSource<'_, ResolveConfig>) -> CDnsResult<Self>
    {
        let hosts_conf = 
            match hosts
            {
                DnsConfigSource::SourceFile(path) => 
                    DnsConfig::<HostConfig>::new(path, Self::load_host(path)? ),
                DnsConfigSource::SourceText(cfg_text) => 
                    DnsConfig::<HostConfig>::new_local(HostConfig::parse_host_file_internal(cfg_text)? ),
                DnsConfigSource::SourceInstance(inst) => 
                    DnsConfig::<HostConfig>::new_local(inst),
            };

        let resolv_conf = 
            match resolv
            {
                DnsConfigSource::SourceFile(path) => 
                    DnsConfig::<ResolveConfig>::new(path, Self::load_resolv(path)? ),
                DnsConfigSource::SourceText(cfg_text) => 
                    DnsConfig::<ResolveConfig>::new_local(ResolveConfig::parser_resolv_internal(cfg_text)? ),
                DnsConfigSource::SourceInstance(inst) => 
                    DnsConfig::<ResolveConfig>::new_local(inst),
            };
        
        return Ok(
            Self
            {
                hosts_conf: hosts_conf,
                resolv_conf: resolv_conf,
                _p: PhantomData,
            }
        );
    }

    pub 
    fn get_hosts_l(&self) -> &DnsConfig<HostConfig>
    {
        return &self.hosts_conf;
    }

    pub 
    fn get_resolv_l(&self) -> &DnsConfig<ResolveConfig>
    {
        return &self.resolv_conf;
    }
}

impl<DEST: DnsConfigDest> ConfigGetter for DnsConfigs<DEST>
{
    fn get_hosts(&self) -> &DnsConfig<HostConfig> 
    {
        return &self.hosts_conf;
    }

    fn get_resolv(&self) -> &DnsConfig<ResolveConfig> 
    {
        return &self.resolv_conf;
    }
}

impl<DEST: DnsConfigDest> ConfigGetter for &DnsConfigs<DEST>
{
    fn get_hosts(&self) -> &DnsConfig<HostConfig> 
    {
        return &self.hosts_conf;
    }

    fn get_resolv(&self) -> &DnsConfig<ResolveConfig> 
    {
        return &self.resolv_conf;
    }
}

#[cfg(test)]
mod test_config
{
    use std::net::IpAddr;

    use crate::QType;

    use super::*;

    #[test]
    fn test_0()
    {
        assert_eq!(GLOBAL_CONFIG.get().is_none(), true);

        DnsConfigs::<DnsConfigGlobal>::init_global_config(None).unwrap();

        assert_eq!(GLOBAL_CONFIG.get().is_some(), true);

        let read0 = GLOBAL_CONFIG.get().unwrap().get_hosts().read_config();
        let localhost = read0.search_by_ip(&"127.0.0.1".parse::<IpAddr>().unwrap());

        assert_eq!(localhost.is_some(), true);

        drop(read0);

        let reader = GLOBAL_CONFIG.get().unwrap().get_hosts().get_reader();
        let rr = reader.aquire().unwrap();

        let fqdn = rr.search_by_fqdn(QType::A, "localhost");
        assert_eq!(fqdn.is_some(), true);
    }
}