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
586
extern crate libc;
use crate::ipcon_error::IpconError;
use crate::ipcon_msg::{IpconMsg, LibIpconMsg, IPCON_MAX_NAME_LEN, IPCON_MAX_PAYLOAD_LEN};
use error_stack::{IntoReport, Result, ResultExt};
#[allow(unused)]
use jlogger::{jdebug, jerror, jinfo, jwarn};
use libc::{c_void, size_t};
use nix::errno::Errno;
use std::ffi::CString;
use std::os::raw::{c_char, c_uchar};

#[link(name = "ipcon")]
extern "C" {
    fn ipcon_create_handler(peer_name: *const c_char, flags: usize) -> *mut c_void;
    fn ipcon_free_handler(handler: *mut c_void);
    fn is_peer_present(handler: *mut c_void, peer: *const c_char) -> i32;
    fn is_group_present(handler: *mut c_void, peer: *const c_char, group: *const c_char) -> i32;
    fn ipcon_rcv(handler: *mut c_void, msg: &LibIpconMsg) -> i32;
    fn ipcon_send_unicast(
        handler: *mut c_void,
        peer: *const c_char,
        buf: *const c_uchar,
        size: size_t,
    ) -> i32;
    fn ipcon_register_group(handler: *mut c_void, name: *const c_char) -> i32;
    fn ipcon_unregister_group(handler: *mut c_void, name: *const c_char) -> i32;
    fn ipcon_join_group(
        handler: *mut c_void,
        srv_name: *const c_char,
        grp_name: *const c_char,
    ) -> i32;
    fn ipcon_leave_group(
        handler: *mut c_void,
        srv_name: *const c_char,
        grp_name: *const c_char,
    ) -> i32;
    fn ipcon_send_multicast(
        handler: *mut c_void,
        name: *const c_char,
        buf: *const c_uchar,
        size: size_t,
        sync: i32,
    ) -> i32;
    fn ipcon_rcv_timeout(
        handler: *mut c_void,
        im: &LibIpconMsg,
        timeout: *const libc::timeval,
    ) -> i32;
    fn ipcon_get_read_fd(handler: *mut c_void) -> i32;
    fn ipcon_get_write_fd(handler: *mut c_void) -> i32;
    fn ipcon_get_ctrl_fd(handler: *mut c_void) -> i32;
}

/// IPCON peer.
pub struct Ipcon {
    handler: usize,
    name: Option<String>,
}

pub type IpconFlag = std::os::raw::c_ulong;
pub const IPF_DISABLE_KEVENT_FILTER: IpconFlag = 0x1 << 0;
pub const IPF_RCV_IF: IpconFlag = 0x1 << 1;
pub const IPF_SND_IF: IpconFlag = 0x1 << 2;
pub const IPF_DEFAULT: IpconFlag = IPF_RCV_IF | IPF_SND_IF;
pub const IPCON_KERNEL_NAME: &str = "ipcon";
pub const IPCON_KERNEL_GROUP_NAME: &str = "ipcon_kevent";

fn errno_to_error(i: i32) -> IpconError {
    let eno = Errno::from_i32(i.abs());
    match eno {
        Errno::ETIMEDOUT => IpconError::SysErrorTimeOut,
        Errno::EINVAL => IpconError::SysErrorInvalidValue,
        Errno::EPERM => IpconError::SysErrorPermission,
        Errno::ENOENT => IpconError::SystemErrorNotExist,
        _ => IpconError::SystemErrorOther,
    }
}

pub fn valid_name(name: &str) -> Result<(), IpconError> {
    let mut error_str = None;

    if name.is_empty() {
        error_str = Some("Name is null".to_owned());
    }

    if name.len() > IPCON_MAX_NAME_LEN {
        error_str = Some(format!(
            "Name is too long {} > {}",
            name.len(),
            IPCON_MAX_NAME_LEN
        ));
    }

    if name.trim() != name {
        error_str = Some("Name has blank character".to_owned());
    }

    if let Some(err_str) = error_str {
        Err(IpconError::InvalidName)
            .into_report()
            .attach_printable(err_str)
    } else {
        Ok(())
    }
}

impl Drop for Ipcon {
    fn drop(&mut self) {
        unsafe {
            ipcon_free_handler(Ipcon::to_handler(self.handler));
        }
    }
}

impl Ipcon {
    pub fn to_handler(u: usize) -> *mut c_void {
        u as *mut c_void
    }

    ///# Safety
    pub unsafe fn from_handler(h: *mut c_void) -> usize {
        h as usize
    }

    /// Create an IPCON peer.
    /// If the name is omitted, an anonymous will be created.
    /// Following flags can be specified with bitwise OR (|).
    /// * IPF_DISABLE_KEVENT_FILTER  
    ///   By default, IPCON kernel module will only delivery the add/remove notification of
    ///   peers and groups which are considered to be interested by the peer. If this flag is
    ///   enabled, all notification will be delivered by IPCON kernel module.
    /// * IPF_SND_IF  
    ///   Use message sending interface.
    /// * IPF_RCV_IF  
    ///   Use message receiving interface.
    /// * IPF_DEFAULT  
    ///   This is same to IPF_RCV_IF | IPF_SND_IF.
    ///
    ///   
    pub fn new(peer_name: Option<&str>, flag: Option<IpconFlag>) -> Result<Ipcon, IpconError> {
        let handler: *mut c_void;
        let mut flg = 0_usize;
        let mut name = None;

        if let Some(a) = flag {
            flg = a as usize;
        }

        let pname = match peer_name {
            Some(a) => {
                valid_name(a).attach_printable(format!("Invalid peer name: {}", a))?;
                name = Some(a.to_string());
                CString::new(a)
                    .into_report()
                    .change_context(IpconError::InvalidName)?
                    .into_raw()
            }
            None => std::ptr::null(),
        };

        unsafe {
            handler = ipcon_create_handler(pname as *const c_char, flg as usize);

            if !pname.is_null() {
                /* deallocate the pname */
                let _ = CString::from_raw(pname as *mut c_char);
            }
        }
        if handler.is_null() {
            Err(IpconError::SystemErrorOther)
                .into_report()
                .attach_printable(format!(
                    "Failed to create ipcon handler for {}, peer name already used?",
                    name.as_deref().unwrap_or("Anon")
                ))
        } else {
            Ok(Ipcon {
                handler: unsafe { Ipcon::from_handler(handler) },
                name,
            })
        }
    }

    /// Retrieve netlink socket file descriptor of message receiving interface.
    pub fn get_read_fd(&self) -> Result<i32, IpconError> {
        unsafe {
            let fd = ipcon_get_read_fd(Ipcon::to_handler(self.handler));
            if fd < 0 {
                Err(errno_to_error(fd))
                    .into_report()
                    .attach_printable(format!(
                        "ipcon_get_read_fd() {} get read fd failed: {}",
                        self.name.as_deref().unwrap_or("Anon"),
                        fd
                    ))
            } else {
                Ok(fd)
            }
        }
    }

    /// Retrieve netlink socket file descriptor of message sending interface.
    pub fn get_write_fd(&self) -> Result<i32, IpconError> {
        unsafe {
            let fd = ipcon_get_write_fd(Ipcon::to_handler(self.handler));
            if fd < 0 {
                Err(errno_to_error(fd))
                    .into_report()
                    .attach_printable(format!(
                        "ipcon_get_write_fd() {} get write fd failed: {}",
                        self.name.as_deref().unwrap_or("Anon"),
                        fd
                    ))
            } else {
                Ok(fd)
            }
        }
    }

    /// Retrieve netlink socket file descriptor of control interface.
    pub fn get_ctrl_fd(&self) -> Result<i32, IpconError> {
        unsafe {
            let fd = ipcon_get_ctrl_fd(Ipcon::to_handler(self.handler));
            if fd < 0 {
                Err(errno_to_error(fd))
                    .into_report()
                    .attach_printable(format!(
                        "ipcon_get_ctrl_fd() {} get ctrl fd failed: {}",
                        self.name.as_deref().unwrap_or("Anon"),
                        fd
                    ))
            } else {
                Ok(fd)
            }
        }
    }

    /// Inquiry whether a peer is present.
    pub fn is_peer_present(&self, peer: &str) -> bool {
        let mut present = false;
        let p = match CString::new(peer) {
            Ok(a) => a,
            Err(_) => return false,
        };

        unsafe {
            let ptr = p.into_raw();
            let ret = is_peer_present(Ipcon::to_handler(self.handler), ptr as *const c_char);
            if ret != 0 {
                present = true;
            }

            let _ = CString::from_raw(ptr);
        }

        present
    }

    /// Inquiry whether the group of a peer is present.
    pub fn is_group_present(&self, peer: &str, group: &str) -> bool {
        let mut present = false;
        let p = match CString::new(peer) {
            Ok(a) => a,
            Err(_) => return false,
        };

        let g = match CString::new(group) {
            Ok(a) => a,
            Err(_) => return false,
        };

        unsafe {
            let ptr = p.into_raw();
            let pgtr = g.into_raw();
            let ret = is_group_present(
                Ipcon::to_handler(self.handler),
                ptr as *const c_char,
                pgtr as *const c_char,
            );
            let _ = CString::from_raw(ptr);
            let _ = CString::from_raw(pgtr);

            if ret != 0 {
                present = true;
            }
        }

        present
    }

    /// Receive IPCON message.
    /// This function will fail if the peer doesn't enable IPF_RCV_IF.
    pub fn receive_msg(&self) -> Result<IpconMsg, IpconError> {
        let lmsg = LibIpconMsg::new();

        unsafe {
            let ret = ipcon_rcv(Ipcon::to_handler(self.handler), &lmsg);
            if ret < 0 {
                return Err(errno_to_error(ret))
                    .into_report()
                    .attach_printable(format!(
                        "ipcon_rcv() {} receive message failed: {}",
                        self.name.as_deref().unwrap_or("Anon"),
                        ret
                    ));
            }
        }

        IpconMsg::from_libipcon_msg(lmsg)
    }

    /// Send an unicast IPCON message to a specific peer.
    /// This function will fail if the peer doesn't enable IPF_SND_IF.
    pub fn send_unicast_msg(&self, peer: &str, buf: &[u8]) -> Result<(), IpconError> {
        self.send_unicast_msg_by_ref(peer, buf)
    }

    /// Send an unicast IPCON message to a specific peer.
    /// This function will fail if the peer doesn't enable IPF_SND_IF.
    pub fn send_unicast_msg_by_ref(&self, peer: &str, buf: &[u8]) -> Result<(), IpconError> {
        valid_name(peer).attach_printable(format!("Invalid peer name: {}", peer))?;

        if buf.len() > IPCON_MAX_PAYLOAD_LEN {
            return Err(IpconError::InvalidData)
                .into_report()
                .attach_printable(format!(
                    "Buffer length is to large {} > {}",
                    buf.len(),
                    IPCON_MAX_PAYLOAD_LEN
                ));
        }

        let pname = CString::new(peer)
            .into_report()
            .change_context(IpconError::InvalidData)?;

        unsafe {
            let ptr = pname.into_raw();
            let ret = ipcon_send_unicast(
                Ipcon::to_handler(self.handler),
                ptr as *const c_char,
                buf.as_ptr(),
                buf.len() as size_t,
            );

            let _ = CString::from_raw(ptr);

            if ret < 0 {
                return Err(errno_to_error(ret))
                    .into_report()
                    .attach_printable(format!(
                        "send_unicast_msg() {} send message to peer `{}` failed: {}",
                        self.name.as_deref().unwrap_or("Anon"),
                        peer,
                        ret
                    ));
            }
        }

        Ok(())
    }

    /// Register a multicast group.
    pub fn register_group(&self, group: &str) -> Result<(), IpconError> {
        valid_name(group).attach_printable("register_group error: invalid group name")?;

        let g = CString::new(group)
            .into_report()
            .change_context(IpconError::InvalidName)?;

        unsafe {
            let ptr = g.into_raw();
            let ret = ipcon_register_group(Ipcon::to_handler(self.handler), ptr as *const c_char);
            let _ = CString::from_raw(ptr);
            if ret < 0 {
                return Err(errno_to_error(ret))
                    .into_report()
                    .attach_printable(format!(
                        "ipcon_register_group() {} register `{}` failed: {}",
                        self.name.as_deref().unwrap_or("Anon"),
                        group,
                        ret
                    ));
            }
        }

        Ok(())
    }

    /// Unregister a multicast group.
    pub fn unregister_group(&self, group: &str) -> Result<(), IpconError> {
        valid_name(group).attach_printable(format!("Invalid group name: {}", group))?;

        let g = CString::new(group)
            .into_report()
            .change_context(IpconError::InvalidName)?;

        unsafe {
            let ptr = g.into_raw();
            let ret = ipcon_unregister_group(Ipcon::to_handler(self.handler), ptr as *const c_char);
            let _ = CString::from_raw(ptr);
            if ret < 0 {
                return Err(errno_to_error(ret))
                    .into_report()
                    .attach_printable(format!(
                        "ipcon_unregister_group() {} unregister `{}` failed: {}",
                        self.name.as_deref().unwrap_or("Anon"),
                        group,
                        ret
                    ));
            }
        }

        Ok(())
    }

    /// Subscribe a multicast group of a peer.
    pub fn join_group(&self, peer: &str, group: &str) -> Result<(), IpconError> {
        valid_name(peer).attach_printable(format!("Invalid peer name: {}", peer))?;
        valid_name(group).attach_printable(format!("Invalid group name: {}", group))?;

        let p = CString::new(peer)
            .into_report()
            .change_context(IpconError::InvalidName)?;

        let g = CString::new(group)
            .into_report()
            .change_context(IpconError::InvalidName)?;

        unsafe {
            let ptr = p.into_raw();
            let pgtr = g.into_raw();
            let ret = ipcon_join_group(
                Ipcon::to_handler(self.handler),
                ptr as *const c_char,
                pgtr as *const c_char,
            );
            let _ = CString::from_raw(ptr);
            let _ = CString::from_raw(pgtr);
            if ret < 0 {
                return Err(errno_to_error(ret))
                    .into_report()
                    .attach_printable(format!(
                        "ipcon_join_group() {} join `{}@{}` failed: {}",
                        self.name.as_deref().unwrap_or("Anon"),
                        group,
                        peer,
                        ret
                    ));
            }
        }

        Ok(())
    }

    /// Unsubscribe a multicast group of a peer.
    pub fn leave_group(&self, peer: &str, group: &str) -> Result<(), IpconError> {
        valid_name(peer).attach_printable(format!("Invalid peer name: {}", peer))?;
        valid_name(group).attach_printable(format!("Invalid group name: {}", group))?;

        let p = CString::new(peer)
            .into_report()
            .change_context(IpconError::InvalidName)?;

        let g = CString::new(group)
            .into_report()
            .change_context(IpconError::InvalidName)?;

        unsafe {
            let ptr = p.into_raw();
            let pgtr = g.into_raw();
            let ret = ipcon_leave_group(
                Ipcon::to_handler(self.handler),
                ptr as *const c_char,
                pgtr as *const c_char,
            );
            let _ = CString::from_raw(ptr);
            let _ = CString::from_raw(pgtr);

            if ret < 0 {
                return Err(errno_to_error(ret))
                    .into_report()
                    .attach_printable(format!(
                        "ipcon_leave_group() {} leave `{}@{}` failed: {}",
                        self.name.as_deref().unwrap_or("Anon"),
                        group,
                        peer,
                        ret
                    ));
            }
        }

        Ok(())
    }

    /// Send multicast messages to an owned group.
    pub fn send_multicast(&self, group: &str, buf: &[u8], sync: bool) -> Result<(), IpconError> {
        self.send_multicast_by_ref(group, buf, sync)
    }

    /// Send multicast messages to an owned group.
    pub fn send_multicast_by_ref(
        &self,
        group: &str,
        buf: &[u8],
        sync: bool,
    ) -> Result<(), IpconError> {
        valid_name(group).attach_printable(format!("Invalid group name: {}", group))?;

        if buf.len() > IPCON_MAX_PAYLOAD_LEN {
            return Err(IpconError::InvalidData)
                .into_report()
                .attach_printable(format!(
                    "Buffer length is too large {} > {}",
                    buf.len(),
                    IPCON_MAX_PAYLOAD_LEN,
                ));
        }

        let g = CString::new(group)
            .into_report()
            .change_context(IpconError::InvalidName)?;

        let mut s: i32 = 0;
        if sync {
            s = 1;
        }

        unsafe {
            let pgtr = g.into_raw();
            let ret = ipcon_send_multicast(
                Ipcon::to_handler(self.handler),
                pgtr as *const c_char,
                buf.as_ptr(),
                buf.len() as size_t,
                s,
            );
            let _ = CString::from_raw(pgtr);

            if ret < 0 {
                return Err(errno_to_error(ret))
                    .into_report()
                    .attach_printable(format!(
                        "ipcon_send_multicast() to `{}@{}` failed: {}",
                        group,
                        self.name.as_deref().unwrap_or("Anon"),
                        ret
                    ));
            }
        }

        Ok(())
    }

    /// Receiving message with timeout.
    /// receive_msg() will block until a message come. receive_msg_timeout() adds a timeout to
    /// it.The timeout is specified with seconds and microseconds.
    pub fn receive_msg_timeout(&self, tv_sec: u32, tv_usec: u32) -> Result<IpconMsg, IpconError> {
        let lmsg = LibIpconMsg::new();
        let t = libc::timeval {
            tv_sec: tv_sec as libc::time_t,
            tv_usec: tv_usec as libc::suseconds_t,
        };

        unsafe {
            let ret = ipcon_rcv_timeout(Ipcon::to_handler(self.handler), &lmsg, &t);
            if ret < 0 {
                return Err(errno_to_error(ret))
                    .into_report()
                    .attach_printable(format!(
                        "ipcon_rcv_timeout() {} receive message failed: {}",
                        self.name.as_deref().unwrap_or("Anon"),
                        ret
                    ));
            }
        }

        IpconMsg::from_libipcon_msg(lmsg)
    }

    /// Receiving message without block.
    /// This is same to receive_msg_timeout(0, 0);
    pub fn receive_msg_nonblock(&self) -> Result<IpconMsg, IpconError> {
        self.receive_msg_timeout(0, 0)
    }
}