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
extern crate libc;

use std::io::{self, Error, ErrorKind};
use std::mem;

use libc::{setsockopt, getsockopt, recvfrom, socket, sockaddr, c_void, c_short, c_int, c_char, c_ulong, AF_PACKET, SOCK_RAW, SOL_SOCKET};

const ETH_P_ALL: u16 = 0x0003;
const PACKET_RX_RING: i32 = 5;

const SIOCGIFFLAGS: c_ulong = 0x00008913;
const SIOCSIFFLAGS: c_ulong = 0x00008914;

const IFF_PROMISC: c_ulong = 1<<8;

const IFNAMESIZE: usize = 16;
const IFREQUNIONSIZE: usize = 24;

/*
struct sockaddr {
    unsigned short sa_family;   // address family, AF_xxx
    char           sa_data[14]; // 14 bytes of protocol address
};

struct ifmap {
    unsigned long   mem_start;
    unsigned long   mem_end;
    unsigned short  base_addr;
    unsigned char   irq;
    unsigned char   dma;
    unsigned char   port;
};

struct ifreq {
    char ifr_name[IFNAMSIZ]; /* Interface name */
    union {
        struct sockaddr ifr_addr;
        struct sockaddr ifr_dstaddr;
        struct sockaddr ifr_broadaddr;
        struct sockaddr ifr_netmask;
        struct sockaddr ifr_hwaddr;
        short           ifr_flags;
        int             ifr_ifindex;
        int             ifr_metric;
        int             ifr_mtu;
        struct ifmap    ifr_map;
        char            ifr_slave[IFNAMSIZ];
        char            ifr_newname[IFNAMSIZ];
        char           *ifr_data;
    };
};
*/

#[derive(Clone, Debug)]
#[repr(C)]
struct IfReqUnion {
    data: [u8; IFREQUNIONSIZE],
}


impl Default for IfReqUnion {
    fn default() -> IfReqUnion {
        IfReqUnion { data: [0; IFREQUNIONSIZE] }
    }
}

impl IfReqUnion {
    fn as_sockaddr(&self) -> sockaddr {
        let mut s = sockaddr {
            sa_family: u16::from_be((self.data[0] as u16) << 8 | (self.data[1] as u16)),
            sa_data: [0; 14],
        };

        // basically a memcpy
        for (i, b) in self.data[2..16].iter().enumerate() {
            s.sa_data[i] = *b as i8;
        }

        s
    }

    fn as_int(&self) -> c_int {
        c_int::from_be((self.data[0] as c_int) << 24 |
                       (self.data[1] as c_int) << 16 |
                       (self.data[2] as c_int) <<  8 |
                       (self.data[3] as c_int))
    }

    fn as_short(&self) -> c_short {
        c_short::from_be((self.data[0] as c_short) << 8 |
                         (self.data[1] as c_short))
    }

    fn from_int(i: c_int) -> IfReqUnion {
        let mut union = IfReqUnion::default();
        let bytes: [u8;4] = unsafe { mem::transmute(i) };
        union.data[0] = bytes[0];
        union.data[1] = bytes[1];
        union.data[2] = bytes[2];
        union.data[3] = bytes[3];
        union
    }

    fn from_short(i: c_short) -> IfReqUnion {
        let mut union = IfReqUnion::default();
        let bytes: [u8;2] = unsafe { mem::transmute(i) };
        union.data[0] = bytes[0];
        union.data[1] = bytes[1];
        union
    }
}


#[derive(Clone, Debug)]
#[repr(C)]
struct IfReq {
    ifr_name: [c_char; IFNAMESIZE],
    union: IfReqUnion,
}

impl IfReq {
    ///
    /// Create an interface request struct with the interface name set
    ///
    fn with_if_name(if_name: &str) -> io::Result<IfReq> {
        let mut if_req = IfReq::default();

        if if_name.len() >= if_req.ifr_name.len() {
            return Err(Error::new(ErrorKind::Other, "Interface name too long"));
        }

        // basically a memcpy
        for (a, c) in if_req.ifr_name.iter_mut().zip(if_name.bytes()) {
            *a = c as i8;
        }

        Ok(if_req)
    }

    fn ifr_hwaddr(&self) -> sockaddr {
        self.union.as_sockaddr()
    }

    fn ifr_dstaddr(&self) -> sockaddr {
        self.union.as_sockaddr()
    }

    fn ifr_broadaddr(&self) -> sockaddr {
        self.union.as_sockaddr()
    }

    fn ifr_ifindex(&self) -> c_int {
        self.union.as_int()
    }

    fn ifr_media(&self) -> c_int {
        self.union.as_int()
    }

    fn ifr_flags(&self) -> c_short {
        self.union.as_short()
    }
}

impl Default for IfReq {
    fn default() -> IfReq {
        IfReq {
            ifr_name: [0; IFNAMESIZE],
            union: IfReqUnion::default(),
        }
    }
}

extern "C" {
    fn ioctl(fd: c_int, request: c_ulong, ifreq: *mut IfReq) -> c_int;
}


/// ioctl operations on a hardware interface
pub struct HwIf {
    if_name: String,
    fd: i32
}

impl HwIf {
    /// Create new hardware interface instance
    ///
    /// The interface name is something like `eth0`.
    pub fn new<S>(if_name: S) -> HwIf where S: Into<String> {
        let fd = unsafe { socket(AF_PACKET,
                             SOCK_RAW,
                             ETH_P_ALL.to_be() as i32,
                             ) };
        HwIf {
            if_name: if_name.into(),
            fd: fd
        }
    }

    fn get_flags(&self) -> io::Result<IfReq> {
        let if_req = try!(self.ioctl(SIOCGIFFLAGS, IfReq::with_if_name(&self.if_name).unwrap()));
        println!("GET {:?}", if_req);
        Ok(if_req)
    }

    fn set_flag(&mut self, flag: c_ulong) -> io::Result<c_int> {
        let flags = &self.get_flags().unwrap().ifr_flags();
        let new_flags = flags | flag as i16;
        let mut if_req = IfReq::with_if_name(&self.if_name).unwrap();
        if_req.union.data = IfReqUnion::from_short(new_flags).data;
        println!("SET {:?} -> {:?}", flags, new_flags);
        println!("SET {:?}", if_req);
        try!(self.ioctl(SIOCSIFFLAGS, if_req));
        Ok(0)
    }

    pub fn set_promisc(&mut self) -> io::Result<c_int> {
        self.set_flag(IFF_PROMISC)
    }

    fn ioctl(&self, ident: c_ulong, if_req: IfReq) -> io::Result<IfReq> {
        let mut req: Box<IfReq> = Box::new(if_req);

        let result = unsafe { ioctl(self.fd, ident, &mut *req) };

        if result == -1 {
            return Err(Error::last_os_error());
        }

        Ok(*req)
    }

/*    pub fn get_rx_ring(&mut self) {

        unsafe {
            setsockopt(self.fd, SOL_SOCKET, PACKET_RX_RING);
        }
    }

    pub fn get_rx_statistics(&mut self) {
        let mut optval: [u8; 32] = [0; 32];
        let mut optlen: u32 = 0;
        getsockopt(self.fd, SOL_SOCKET, PACKET_STATISTICS, &mut optval, &mut optlen);
    }
    */

    pub fn recv_single_packet(&self, buf: &mut [u8]) -> io::Result<usize> {
        let len: isize;
        let mut sock = sockaddr { sa_data: [0; 14], sa_family: 0 };
        unsafe {
            len = match recvfrom(self.fd, // file descriptor
                                    buf.as_mut_ptr() as *mut c_void, // pointer to buffer for frame content
                                    buf.len(), // frame content buffer length
                                    0,
                                    &mut sock,
                                    &mut 0) { // sender address buffer length
                -1 => {
                    return Err(io::Error::last_os_error());
                },
                len => len
            };
        }
        // Return the number of valid bytes that were placed in the buffer
        Ok(len as usize)
    }
}