Struct ipcon_sys::ipcon::Ipcon

source ·
pub struct Ipcon { /* private fields */ }
Expand description

IPCON peer.

Implementations§

Examples found in repository?
src/ipcon.rs (line 110)
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
    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
                    ));
            }
        }

        lmsg.into()
    }

    /// 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
                    ));
            }
        }

        lmsg.into()
    }
Examples found in repository?
src/ipcon.rs (line 178)
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
    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,
            })
        }
    }

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.

Retrieve netlink socket file descriptor of message receiving interface.

Retrieve netlink socket file descriptor of message sending interface.

Retrieve netlink socket file descriptor of control interface.

Inquiry whether a peer is present.

Inquiry whether the group of a peer is present.

Receive IPCON message. This function will fail if the peer doesn’t enable IPF_RCV_IF.

Send an unicast IPCON message to a specific peer. This function will fail if the peer doesn’t enable IPF_SND_IF.

Send an unicast IPCON message to a specific peer. This function will fail if the peer doesn’t enable IPF_SND_IF.

Examples found in repository?
src/ipcon.rs (line 315)
314
315
316
    pub fn send_unicast_msg(&self, peer: &str, buf: &[u8]) -> Result<(), IpconError> {
        self.send_unicast_msg_by_ref(peer, buf)
    }

Register a multicast group.

Unregister a multicast group.

Subscribe a multicast group of a peer.

Unsubscribe a multicast group of a peer.

Send multicast messages to an owned group.

Send multicast messages to an owned group.

Examples found in repository?
src/ipcon.rs (line 498)
497
498
499
    pub fn send_multicast(&self, group: &str, buf: &[u8], sync: bool) -> Result<(), IpconError> {
        self.send_multicast_by_ref(group, buf, sync)
    }

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.

Examples found in repository?
src/ipcon.rs (line 584)
583
584
585
    pub fn receive_msg_nonblock(&self) -> Result<IpconMsg, IpconError> {
        self.receive_msg_timeout(0, 0)
    }

Receiving message without block. This is same to receive_msg_timeout(0, 0);

Trait Implementations§

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Set the foreground color generically Read more
Set the background color generically. Read more
Change the foreground color to black
Change the background color to black
Change the foreground color to red
Change the background color to red
Change the foreground color to green
Change the background color to green
Change the foreground color to yellow
Change the background color to yellow
Change the foreground color to blue
Change the background color to blue
Change the foreground color to magenta
Change the background color to magenta
Change the foreground color to purple
Change the background color to purple
Change the foreground color to cyan
Change the background color to cyan
Change the foreground color to white
Change the background color to white
Change the foreground color to the terminal default
Change the background color to the terminal default
Change the foreground color to bright black
Change the background color to bright black
Change the foreground color to bright red
Change the background color to bright red
Change the foreground color to bright green
Change the background color to bright green
Change the foreground color to bright yellow
Change the background color to bright yellow
Change the foreground color to bright blue
Change the background color to bright blue
Change the foreground color to bright magenta
Change the background color to bright magenta
Change the foreground color to bright purple
Change the background color to bright purple
Change the foreground color to bright cyan
Change the background color to bright cyan
Change the foreground color to bright white
Change the background color to bright white
Make the text bold
Make the text dim
Make the text italicized
Make the text italicized
Make the text blink
Make the text blink (but fast!)
Swap the foreground and background colors
Hide the text
Cross out the text
Set the foreground color at runtime. Only use if you do not know which color will be used at compile-time. If the color is constant, use either OwoColorize::fg or a color-specific method, such as OwoColorize::green, Read more
Set the background color at runtime. Only use if you do not know what color to use at compile-time. If the color is constant, use either OwoColorize::bg or a color-specific method, such as OwoColorize::on_yellow, Read more
Set the foreground color to a specific RGB value.
Set the background color to a specific RGB value.
Sets the foreground color to an RGB value.
Sets the background color to an RGB value.
Apply a runtime-determined style
Apply a given transformation function to all formatters if the given stream supports at least basic ANSI colors, allowing you to conditionally apply given styles/colors. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more