libknot 0.2.3

High Level bindings to a subset of libknot, the library of the knot dns server
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
use super::error;
use crate::error::KnotError;
use crate::util::MakeFallible;
use crate::{common, KnotSync};
use fallible_iterator::FallibleIterator;
use libknot_sys as sys;
use std::ffi::{CStr, CString};
use std::{fmt, i32, mem, ptr, time};

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum MessageField {
    Command,
    Flags,
    Error,
    Section,
    Item,
    Id,
    Zone,
    Owner,
    TTL,
    Type,
    Data,
    Filter,
}

const ALL_MESSAGE_FIELDS: [MessageField; 12] = [
    MessageField::Command,
    MessageField::Flags,
    MessageField::Error,
    MessageField::Section,
    MessageField::Item,
    MessageField::Id,
    MessageField::Zone,
    MessageField::Owner,
    MessageField::TTL,
    MessageField::Type,
    MessageField::Data,
    MessageField::Filter,
];

impl MessageField {
    #[allow(dead_code)]
    pub(crate) fn to_sys(self) -> sys::knot_ctl_idx_t {
        match self {
            MessageField::Command => sys::knot_ctl_idx_t::KNOT_CTL_IDX_CMD,
            MessageField::Flags => sys::knot_ctl_idx_t::KNOT_CTL_IDX_FLAGS,
            MessageField::Error => sys::knot_ctl_idx_t::KNOT_CTL_IDX_ERROR,
            MessageField::Section => sys::knot_ctl_idx_t::KNOT_CTL_IDX_SECTION,
            MessageField::Item => sys::knot_ctl_idx_t::KNOT_CTL_IDX_ITEM,
            MessageField::Id => sys::knot_ctl_idx_t::KNOT_CTL_IDX_ID,
            MessageField::Zone => sys::knot_ctl_idx_t::KNOT_CTL_IDX_ZONE,
            MessageField::Owner => sys::knot_ctl_idx_t::KNOT_CTL_IDX_OWNER,
            MessageField::TTL => sys::knot_ctl_idx_t::KNOT_CTL_IDX_TTL,
            MessageField::Type => sys::knot_ctl_idx_t::KNOT_CTL_IDX_TYPE,
            MessageField::Data => sys::knot_ctl_idx_t::KNOT_CTL_IDX_DATA,
            MessageField::Filter => sys::knot_ctl_idx_t::KNOT_CTL_IDX_FILTERS,
        }
    }

    #[allow(dead_code)]
    pub(crate) fn from_sys(s: sys::knot_ctl_idx_t) -> MessageField {
        match s {
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_CMD => MessageField::Command,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_FLAGS => MessageField::Flags,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_ERROR => MessageField::Error,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_SECTION => MessageField::Section,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_ITEM => MessageField::Item,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_ID => MessageField::Id,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_ZONE => MessageField::Zone,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_OWNER => MessageField::Owner,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_TTL => MessageField::TTL,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_TYPE => MessageField::Type,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_DATA => MessageField::Data,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX_FILTERS => MessageField::Filter,
            sys::knot_ctl_idx_t::KNOT_CTL_IDX__COUNT => unreachable!("INVALID INDEX __COUNT"),
        }
    }
}

pub struct Control {
    ctl: *mut sys::knot_ctl,
}

impl Control {
    pub fn new(path: &str) -> error::Result<Control> {
        let ptr = unsafe { sys::knot_ctl_alloc() };
        if ptr.is_null() {
            return Err(error::KnotError::OutOfMemory);
        }
        if let Ok(c_path) = CString::new(path) {
            error::auto_err(unsafe { sys::knot_ctl_connect(ptr, c_path.as_ptr()) })?;
        } else {
            return Err(error::KnotError::NulError);
        }
        Ok(Control {
            ctl: ptr,
        })
    }

    pub fn send_message(&self, msg: &ControlMessage) -> error::Result<()> {
        let ptr = (&msg.data) as *const sys::knot_ctl_data_t;
        error::auto_err(unsafe {
            sys::knot_ctl_send(
                self.ctl,
                sys::knot_ctl_type_t_KNOT_CTL_TYPE_DATA,
                ptr as *mut [*const i8; 12],
            ) // libknot doesn't touch the data, so lets make it mutable.
        })?;
        error::auto_err(unsafe {
            sys::knot_ctl_send(
                self.ctl,
                sys::knot_ctl_type_t_KNOT_CTL_TYPE_BLOCK,
                ptr::null::<sys::knot_ctl_data_t>() as *mut [*const i8; 12],
            )
        })?;
        Ok(())
    }

    pub fn recv_single_message(&self) -> error::Result<(sys::knot_ctl_type_t, ControlMessage)> {
        let mut ty = sys::knot_ctl_type_t_KNOT_CTL_TYPE_BLOCK;
        let mut msg = [ptr::null(); 12];

        error::auto_err(unsafe {
            sys::knot_ctl_receive(
                self.ctl,
                (&mut ty) as *mut sys::knot_ctl_type_t,
                (&mut msg) as *mut sys::knot_ctl_data_t,
            )
        })?;

        Ok((ty, unsafe { ControlMessage::from_raw(msg)? }))
    }

    pub fn set_timeout(&mut self, timeout: Option<time::Duration>) {
        if let Some(t) = timeout {
            let ms = t.as_secs() * 1000 + (t.subsec_millis() as u64);
            if ms > i32::MAX as u64 {
                panic!("Size must be between 1 and i32::MAX ms");
            }
            unsafe { sys::knot_ctl_set_timeout(self.ctl, ms as i32) };
        } else {
            unsafe { sys::knot_ctl_set_timeout(self.ctl, 0) };
        }
    }

    pub fn send_request(&mut self, msg: &ControlMessage) -> error::Result<MessageIterator> {
        //println!("Internal Request: {:?}", msg);
        self.send_message(msg)?;
        Ok(MessageIterator {
            con: self,
            burnt: false,
        })
    }
}

impl KnotSync for Control {
    fn in_transaction(&self) -> bool {
        true
    }

    fn conf_transaction<F, T, C>(&mut self, cb: C) -> Result<T, F>
    where
        C: FnOnce(&mut Self) -> Result<T, F>,
        F: From<KnotError>,
    {
        log::trace!("Beginning Config Transaction");
        let next = self
            .send_request(&MessageBuilder::new().cmd("conf-begin").build())?
            .next();
        if let Some(n) = next {
            n?.make_successful()?;
        }
        match cb(self) {
            Ok(thing) => {
                log::debug!("Committing Config Transaction");
                let next = self
                    .send_request(&MessageBuilder::new().cmd("conf-commit").build())?
                    .next();
                if let Some(n) = next {
                    // We are ignoring the case that an error happends trying to read the reply
                    // for simplicities sake
                    match n?.make_successful() {
                        Ok(_) => Ok(thing),
                        Err(e) => {
                            log::debug!("Commit failed, falling back to aborting it");
                            self.send_request(&MessageBuilder::new().cmd("conf-abort").build())?;
                            Err(e.into())
                        }
                    }
                } else {
                    Ok(thing)
                }
            }
            Err(e) => {
                log::debug!("Aborting Config Transaction");
                self.send_request(&MessageBuilder::new().cmd("conf-abort").build())?;
                Err(e)
            }
        }
    }

    fn conf_set(
        &mut self,
        section: &str,
        id: Option<&str>,
        item: Option<&str>,
        value: Option<&str>,
    ) -> error::Result<()> {
        log::trace!(
            "conf-set: {section}[{id:?}].{item:?} = {data:?}",
            section = section,
            item = item,
            id = id,
            data = value
        );

        let mut msg = MessageBuilder::new()
            .cmd("conf-set")
            .section(section)
            .build();
        msg.set(MessageField::Item, item)?;
        msg.set(MessageField::Id, id)?;
        msg.set(MessageField::Data, value)?;
        for el in self.send_request(&msg)? {
            el?.make_successful()?;
        }
        Ok(())
    }

    fn conf_unset(
        &mut self,
        section: &str,
        id: Option<&str>,
        item: Option<&str>,
        value: Option<&str>,
    ) -> error::Result<()> {
        log::trace!(
            "conf-unset: {section}[{id:?}].{item:?}",
            section = section,
            item = item,
            id = id
        );

        let mut msg = MessageBuilder::new()
            .cmd("conf-unset")
            .section(section)
            .build();
        msg.set(MessageField::Item, item)?;
        msg.set(MessageField::Id, id)?;
        msg.set(MessageField::Data, value)?;
        for el in self.send_request(&msg)? {
            el?.make_successful()?;
        }
        Ok(())
    }

    fn zone_transaction<F, T, C>(&mut self, zone: &str, cb: C) -> Result<T, F>
    where
        C: FnOnce(&mut Self) -> Result<T, F>,
        F: From<KnotError>,
    {
        let next = self
            .send_request(&MessageBuilder::new().cmd("zone-begin").zone(zone).build())?
            .next();
        if let Some(n) = next {
            n?.make_successful()?;
        }
        match cb(self) {
            Ok(thing) => {
                let next = self
                    .send_request(&MessageBuilder::new().cmd("zone-commit").zone(zone).build())?
                    .next();
                if let Some(n) = next {
                    n?.make_successful()?;
                }
                Ok(thing)
            }
            Err(e) => {
                self.send_request(&MessageBuilder::new().cmd("zone-abort").zone(zone).build())?;
                Err(e)
            }
        }
    }

    fn conf_get<'a>(
        &'a mut self,
        section: Option<&str>,
        id: Option<&str>,
        item: Option<&str>,
    ) -> Result<Vec<common::ControlMessage>, KnotError> {
        log::trace!(
            "conf-get: {section:?}[{id:?}].{item:?}",
            section = section,
            item = item,
            id = id
        );

        let msg = MessageBuilder::new().cmd("conf-get").build();

        fallible_iterator::convert(self.send_request(&msg)?)
            .map(|el| el.into_successful())
            .map(|el| {
                let msg = ALL_MESSAGE_FIELDS
                    .iter()
                    .enumerate()
                    .make_fallible()
                    .flat_map(|(id, field)| {
                        Ok(fallible_iterator::convert(
                            el.get(*field)?
                                .map(|val| Result::<_, KnotError>::Ok((id as u8, val.to_owned())))
                                .into_iter(),
                        ))
                    })
                    .collect()?;
                common::build_message(msg)
            })
            .collect::<Vec<_>>()
    }
}

impl Drop for Control {
    fn drop(&mut self) {
        unsafe {
            sys::knot_ctl_free(self.ctl);
            self.ctl = ptr::null_mut::<sys::knot_ctl>();
        }
    }
}

pub struct ControlMessage {
    pub(crate) data: sys::knot_ctl_data_t,
    data_storage: [Option<CString>; 12],
}

impl ControlMessage {
    pub fn new() -> ControlMessage {
        ControlMessage {
            data: [ptr::null(); 12],
            data_storage: Default::default(),
        }
    }

    pub fn set(&mut self, field: MessageField, value: Option<&str>) -> error::Result<()> {
        match value {
            Some(value) => {
                if let Ok(c_value) = CString::new(value) {
                    self.data[field as usize] = c_value.as_ptr();
                    self.data_storage[field as usize] = Some(c_value);
                } else {
                    return Err(error::KnotError::NulError);
                }
            }
            None => {
                self.data[field as usize] = ptr::null();
                self.data_storage[field as usize] = None;
            }
        }
        Ok(())
    }

    pub fn get(&self, field: MessageField) -> error::Result<Option<&str>> {
        if let Some(ref c_value) = self.data_storage[field as usize] {
            match c_value.as_c_str().to_str() {
                Ok(val) => Ok(Some(val)),
                Err(_) => Err(error::KnotError::UTF8Error),
            }
        } else {
            Ok(None)
        }
    }

    /// # Safety
    /// All pointers inside the struct must be either 0 or valid
    /// Furthermore, as this function takes ownership of all pointers,
    /// you may not use them after calling this function
    pub unsafe fn from_raw(data: sys::knot_ctl_data_t) -> error::Result<ControlMessage> {
        let mut ds: Vec<Option<CString>> = data
            .iter()
            .map(|e| {
                if e.is_null() {
                    None
                } else {
                    Some(CStr::from_ptr(*e).to_owned())
                }
            })
            .collect();
        let mut d: Vec<_> = ds
            .iter()
            .map(|s| {
                if let Some(s) = s {
                    s.as_c_str().as_ptr()
                } else {
                    ptr::null()
                }
            })
            .collect();

        let mut msg = ControlMessage {
            data: [ptr::null(); 12],
            data_storage: Default::default(),
        };

        swap(&mut msg.data, &mut d);
        swap(&mut msg.data_storage, &mut ds);

        Ok(msg)
    }

    pub fn make_successful(&self) -> error::Result<&ControlMessage> {
        if let Some(e) = self.get(MessageField::Error)? {
            Err(error::KnotError::KnotErrorMsg { msg: e.to_string() })
        } else {
            Ok(self)
        }
    }

    pub fn into_successful(self) -> error::Result<ControlMessage> {
        if let Some(e) = self.get(MessageField::Error)? {
            Err(error::KnotError::KnotErrorMsg { msg: e.to_string() })
        } else {
            Ok(self)
        }
    }
}

impl Default for ControlMessage {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for ControlMessage {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ControlMessage")
            .field(
                "KNOT_CTL_IDX_CMD",
                &self.get(MessageField::Command).unwrap(),
            )
            .field(
                "KNOT_CTL_IDX_FLAGS",
                &self.get(MessageField::Flags).unwrap(),
            )
            .field(
                "KNOT_CTL_IDX_ERROR",
                &self.get(MessageField::Error).unwrap(),
            )
            .field(
                "KNOT_CTL_IDX_SECTION",
                &self.get(MessageField::Section).unwrap(),
            )
            .field("KNOT_CTL_IDX_ITEM", &self.get(MessageField::Item).unwrap())
            .field("KNOT_CTL_IDX_ID", &self.get(MessageField::Id).unwrap())
            .field("KNOT_CTL_IDX_ZONE", &self.get(MessageField::Zone).unwrap())
            .field(
                "KNOT_CTL_IDX_OWNER",
                &self.get(MessageField::Owner).unwrap(),
            )
            .field("KNOT_CTL_IDX_TTL", &self.get(MessageField::TTL).unwrap())
            .field("KNOT_CTL_IDX_TYPE", &self.get(MessageField::Type).unwrap())
            .field("KNOT_CTL_IDX_DATA", &self.get(MessageField::Data).unwrap())
            .field(
                "KNOT_CTL_IDX_FILTER",
                &self.get(MessageField::Filter).unwrap(),
            )
            .finish()
    }
}

#[derive(Debug)]
pub struct MessageBuilder {
    pub(crate) message: ControlMessage,
}

impl MessageBuilder {
    pub fn new() -> MessageBuilder {
        MessageBuilder {
            message: ControlMessage::new(),
        }
    }

    pub fn cmd(mut self, cmd: &str) -> Self {
        self.message.set(MessageField::Command, Some(cmd)).unwrap();
        self
    }

    pub fn section(mut self, section: &str) -> Self {
        self.message
            .set(MessageField::Section, Some(section))
            .unwrap();
        self
    }

    //item, zone, owner, ttl, typ, data

    pub fn item(mut self, item: &str) -> Self {
        self.message.set(MessageField::Item, Some(item)).unwrap();
        self
    }

    pub fn zone(mut self, zone: &str) -> Self {
        self.message.set(MessageField::Zone, Some(zone)).unwrap();
        self
    }

    pub fn owner(mut self, owner: &str) -> Self {
        self.message.set(MessageField::Owner, Some(owner)).unwrap();
        self
    }

    pub fn ttl(mut self, ttl: u32) -> Self {
        self.message
            .set(MessageField::TTL, Some(&format!("{}", ttl)))
            .unwrap();
        self
    }

    pub fn record_type(mut self, ty: &str) -> Self {
        self.message.set(MessageField::Type, Some(ty)).unwrap();
        self
    }

    pub fn data(mut self, data: &str) -> Self {
        self.message.set(MessageField::Data, Some(data)).unwrap();
        self
    }

    pub fn build(self) -> ControlMessage {
        self.message
    }
}

impl Default for MessageBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl From<MessageBuilder> for ControlMessage {
    fn from(thing: MessageBuilder) -> ControlMessage {
        thing.message
    }
}

pub struct MessageIterator<'a> {
    pub(crate) con: &'a mut Control,
    /// This iterator has already seen a BLOCK frame and therefore is depleted
    pub(crate) burnt: bool,
}

impl<'a> Iterator for MessageIterator<'a> {
    type Item = error::Result<ControlMessage>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.burnt {
            None
        } else {
            let (id, m) = match self.con.recv_single_message() {
                Ok(thing) => thing,
                Err(e) => return Some(Err(e)),
            };
            match id {
                sys::knot_ctl_type_t_KNOT_CTL_TYPE_DATA
                | sys::knot_ctl_type_t_KNOT_CTL_TYPE_EXTRA => Some(Ok(m)),
                sys::knot_ctl_type_t_KNOT_CTL_TYPE_BLOCK
                | sys::knot_ctl_type_t_KNOT_CTL_TYPE_END => {
                    self.burnt = true;
                    None
                }
                _ => panic!("Unexpected frame type {}", id),
            }
        }
    }
}

impl<'a> Drop for MessageIterator<'a> {
    fn drop(&mut self) {
        for _ in self {}
    }
}

fn swap<T>(s1: &mut [T], s2: &mut [T]) {
    for i in 0..s1.len() {
        mem::swap(&mut s1[i], &mut s2[i]);
    }
}