summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 0cb3cc963dbea28431027cae7780256d2ad113cc (plain)
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
// Copyright (C) 2015 Sebastian Dröge <sebastian@centricular.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
// Boston, MA 02110-1301, USA.
//

extern crate mio;

use mio::*;
use mio::udp::*;
use std::net::SocketAddr;
use std::ops::Range;

const SOCKET_EVENT: Token = Token(0);
const SOCKET_GENERAL: Token = Token(1);

struct PtpReflector {
    poll: Poll,
    event_socket: UdpSocket,
    event_addr: SocketAddr,
    general_socket: UdpSocket,
    general_addr: SocketAddr,
}

fn slice_map_range_in_place<T, F>(s: &mut [T], range: Range<usize>, mut f: F)
    where F: FnMut(&T) -> T
{
    let n = s.len();

    if range.end > n {
        panic!("Invalid range {} > {}", range.end, n);
    }

    for i in range {
        s[i] = f(&s[i]);
    }
}

impl PtpReflector {
    fn new() -> Result<PtpReflector, String> {
        let poll = try!(Poll::new().map_err(|e| e.to_string()));

        let multicast_group = "224.0.1.129".parse().unwrap();
        let any_addr = "0.0.0.0".parse().unwrap();

        let event_bind_addr = "0.0.0.0:319".parse().unwrap();
        let event_socket = try!(UdpSocket::bind(&event_bind_addr).map_err(|e| e.to_string()));
        try!(event_socket.join_multicast_v4(&multicast_group, &any_addr)
            .map_err(|e| e.to_string()));
        try!(poll.register(&event_socket,
                      SOCKET_EVENT,
                      Ready::readable(),
                      PollOpt::level())
            .map_err(|e| e.to_string()));

        // FIXME: How can we create this from the multicast group?
        // let event_addr = SocketAddr::new(multicast_group, 319);
        let event_addr = "224.0.1.129:319".parse().unwrap();

        let general_bind_addr = "0.0.0.0:320".parse().unwrap();
        let general_socket = try!(UdpSocket::bind(&general_bind_addr).map_err(|e| e.to_string()));
        try!(general_socket.join_multicast_v4(&multicast_group, &any_addr)
            .map_err(|e| e.to_string()));
        try!(poll.register(&general_socket,
                      SOCKET_GENERAL,
                      Ready::readable(),
                      PollOpt::level())
            .map_err(|e| e.to_string()));

        // FIXME: How can we create this from the multicast group?
        // let general_addr = SocketAddr::new(multicast_group, 320);
        let general_addr = "224.0.1.129:320".parse().unwrap();

        Ok(PtpReflector {
            poll: poll,
            event_socket: event_socket,
            event_addr: event_addr,
            general_socket: general_socket,
            general_addr: general_addr,
        })
    }

    fn ready(&self, event: &Event) {
        if !event.kind().is_readable() {
            return;
        }

        let (socket, addr) = match event.token() {
            SOCKET_EVENT => (&self.event_socket, &self.event_addr),
            SOCKET_GENERAL => (&self.general_socket, &self.general_addr),
            _ => unreachable!(),
        };

        let msg = &mut [0; 1024];

        let length = match socket.recv_from(msg) {
            Err(e) => {
                println!("Error while receiving message: {}", e.to_string());
                return;
            }
            Ok(Some((l, _))) => l,
            Ok(None) => {
                println!("Error while receiving message");
                return;
            }
        };

        println!("Got message of size {}", length);

        if length < 44 {
            return;
        }

        let domain = msg[4];
        let msg_type = msg[0] & 0x0f;

        let forward = match domain {
            0 => {
                msg[4] = 1;
                slice_map_range_in_place(msg, 20..28, |&x| x ^ 0xff);

                match msg_type {
                    0x0 | 0x08 | 0xb => true,
                    0x9 if msg.len() >= 54 => {
                        slice_map_range_in_place(msg, 44..52, |&x| x ^ 0xff);

                        true
                    }
                    _ => false,
                }
            }
            1 => {
                msg[4] = 0;
                slice_map_range_in_place(msg, 20..28, |&x| x ^ 0xff);

                match msg_type {
                    0x1 => true,
                    _ => false,
                }
            }
            _ => false,
        };

        if forward {
            if let Err(e) = socket.send_to(&msg[..length], addr) {
                println!("Error while sending message: {}", e.to_string());
                return;
            };

            println!("Sent message of size {}", length);
        }
    }

    fn run(&self) -> Result<(), String> {
        let mut events = Events::with_capacity(1024);

        loop {
            try!(self.poll.poll(&mut events, None).or_else(|err| Err(err.to_string())));

            for event in events.iter() {
                self.ready(&event);
            }
        }
    }
}

fn main() {
    let res = PtpReflector::new().and_then(|handler| handler.run());

    match res {
        Ok(()) => (),
        Err(s) => panic!(s),
    };
}