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
// MIT License
//
// Copyright (c) 2019 Temirkhan Myrzamadi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! This crate provides a convenient approach for transmitting multiple messages
//! using one system call (but only on Linux-based operating systems).
//!
//! Kernel calls might take relatively long time, consequently, calling the same
//! kernel function lots of times will increase CPU load significantly. This is
//! why I have created this library; it simply wraps the [sendmmsg] kernel
//! function.
//!
//! [sendmmsg]: http://man7.org/linux/man-pages/man2/sendmmsg.2.html
//!
//! # Examples
//! This example sends four messages called *data portions* to the `example.com`
//! website using a single system call on an orginary `TcpStream`:
//!
//! ([`examples/sender.rs`](https://github.com/Gymmasssorla/sendmmsg/blob/master/examples/sender.rs))
//! ```rust,no_run
//! #![feature(iovec)]
//!
//! use sendmmsg::Sendmmsg;
//! use std::io::IoVec;
//! use std::net::TcpStream;
//!
//! fn main() {
//!    // Specify all the messages you want to send
//!    let messages = &mut [
//!        (0, IoVec::new(b"Generals gathered in their masses")),
//!        (0, IoVec::new(b"Just like witches at black masses")),
//!        (0, IoVec::new(b"Evil minds that plot destruction")),
//!        (0, IoVec::new(b"Sorcerers of death's construction")),
//!    ];
//!
//!    // Setup the `TcpStream` instance connected to example.com
//!    let socket = TcpStream::connect("93.184.216.34:80").unwrap();
//!
//!    // Finally, send all the messages above
//!    match socket.sendmmsg(messages) {
//!        Err(error) => eprintln!("An error occurred: {}!", error),
//!        Ok(packets) => println!("Packets sent: {}", packets),
//!    }
//! }
//! ```

#![feature(iovec)]

use std::io::{self, IoVec};
use std::mem;
use std::net::{TcpStream, UdpSocket};
use std::os::unix::io::AsRawFd;

use libc::{self, c_int, c_uint, iovec, mmsghdr, msghdr};

// *****************************************************************************
// SENDMMSG TRAIT
// *****************************************************************************

/// A trait which is implemented for `UdpSocket` and `TcpStream`, thereby
/// allowing them to send multiple messages using one system call.
pub trait Sendmmsg {
    /// Sends all the specified messages of `packets` using one system call, and
    /// assigns the total bytes sent for each packet into the first slice
    /// elements. If you want, you can send remaining bytes later.
    ///
    /// # Errors
    /// The provided socket must be connected to the remote address before
    /// calling this function, otherwise, `io::ErrorKind::NotConnected` error
    /// might be returned.
    ///
    /// Other kinds of errors can also be returned, see the errors descriptions
    /// of `io::ErrorKind` enumeration.
    ///
    /// [sendmmsg]: http://man7.org/linux/man-pages/man2/sendmmsg.2.html
    fn sendmmsg(&self, packets: &mut [(usize, IoVec)]) -> io::Result<usize>;
}

// *****************************************************************************
// IMPLEMENTATIONS
// *****************************************************************************

impl Sendmmsg for TcpStream {
    fn sendmmsg(&self, packets: &mut [(usize, IoVec)]) -> io::Result<usize> {
        inner_sendmmsg(self.as_raw_fd(), packets)
    }
}

impl Sendmmsg for UdpSocket {
    fn sendmmsg(&self, packets: &mut [(usize, IoVec)]) -> io::Result<usize> {
        inner_sendmmsg(self.as_raw_fd(), packets)
    }
}

// *****************************************************************************
// INNER IMPLEMENTATION
// *****************************************************************************

/// Does all the dirty work using the specified `fd` (socket file descriptor)
/// and `packets`.
fn inner_sendmmsg(fd: c_int, packets: &mut [(usize, IoVec)]) -> io::Result<usize> {
    let mut messages: Vec<mmsghdr> = prepare_messages(packets);

    unsafe {
        match libc::sendmmsg(fd, messages.as_mut_ptr(), messages.len() as c_uint, 0) {
            -1 => Err(io::Error::last_os_error()),
            packets_sent => {
                // The system sendmmsg assigns a number of bytes sent for each packet to
                // mmsghdr, so copy it into our DataPortion
                for i in 0..messages.len() {
                    packets[i].0 = messages[i].msg_len as usize;
                }

                Ok(packets_sent as usize)
            }
        }
    }
}

/// Prepares the vector of `mmsghdr` structures using the specified `io_data`.
fn prepare_messages(io_data: &mut [(usize, IoVec)]) -> Vec<mmsghdr> {
    let mut messages: Vec<mmsghdr> = Vec::with_capacity(io_data.len());

    for portion in io_data {
        messages.push(mmsghdr {
            msg_hdr: {
                let mut message = unsafe { mem::zeroed::<msghdr>() };

                message.msg_iov = &portion.1 as *const _ as *mut iovec;
                message.msg_iovlen = 1;

                message
            },
            msg_len: 0,
        });
    }

    messages
}

// *****************************************************************************
// TESTS
// *****************************************************************************

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn sends_all_data() {
        let socket = UdpSocket::bind("0.0.0.0:0").expect("UdpSocket::bind() has failed");
        socket
            .connect(socket.local_addr().unwrap())
            .expect("socket.connect() has failed");

        let portions = &mut [
            (0, IoVec::new(b"Welcome to the jungle")),
            (0, IoVec::new(b"We got fun 'n' games")),
            (0, IoVec::new(b"We got everything you want")),
        ];

        assert_eq!(
            socket
                .sendmmsg(portions)
                .expect("socket.sendmmsg(messages) has failed"),
            portions.len()
        );

        for portion in portions {
            assert_eq!(portion.0, portion.1.len());
        }
    }
}