dlwp 0.1.0-alpha

The DLWP library
Documentation
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
use crate::{
    codes::{
        Code, DISCONNECT as DISCONNECT_, REMOVE_CLIENT, REQUEST_CONNECTION, STATUS_OK,
        UNKNOWN_STATUS,
    },
    connections::Connections,
    dlcmd::{send_dlcmd, CONNECT, DISCONNECT, SEND},
    encryption::EncryptionInfo,
    id::*,
    message::{string_to_contents, Message, ReceiveInfo, TransmitInfo},
};
use std::{
    fs::File,
    io::{BufRead, BufReader},
    path::Path,
    thread::sleep,
    time::Duration,
};

#[allow(improper_ctypes_definitions)]
fn empty_encryption_function(_i: [i32; 6], s: String) -> String {
    s
}

pub(crate) const EMPTY_ENCRYPTIONIFNO: EncryptionInfo = EncryptionInfo {
    encode_function: empty_encryption_function,
    decode_function: empty_encryption_function,
    info: [0; 6],
};

/// A type for determining how the ``Stream`` will act (as client or server)
#[derive(Copy, Clone)]
pub enum StreamType {
    Client {
        /// The receiving id of a client/server
        rid: LId,
        /// The client/server's Distributor Id
        rdid: DId,
        /// The port that the client/server is using
        port: u16,
    },
    Server {
        /// Port to bind to
        port: u16,
    },
}

impl StreamType {
    /// Returns ``true`` if the ``StreamType`` is ``Client``
    pub fn is_client(self) -> bool {
        return match self {
            Self::Client { .. } => true,
            Self::Server { .. } => false,
        };
    }

    /// If ``StreamType`` is a ``Client`` this returns the stream's receiving ID, if it is a ``Server`` it returns the
    /// local ID
    pub fn rid(self) -> LId {
        return match self {
            Self::Client {
                rid,
                rdid: _,
                port: _,
            } => rid,
            Self::Server { .. } => local_user_id().unwrap_or(0),
        };
    }

    /// If ``StreamType`` is a ``Client`` this returns the stream's receiving distributor ID, if it is a ``Server`` it
    /// returns the local distributor ID
    pub fn rdid(self) -> DId {
        return match self {
            Self::Client {
                rid: _,
                rdid,
                port: _,
            } => rdid,
            Self::Server { .. } => distributor_id().unwrap_or(0),
        };
    }

    /// Gets the port of the ``Stream``
    pub fn port(self) -> u16 {
        return match self {
            Self::Client {
                rid: _,
                rdid: _,
                port,
            } => port,
            Self::Server { port } => port,
        };
    }
}

pub struct Stream {
    /// The ``StreamType`` (client or server)
    pub stream_type: StreamType,
    /// Information for encrypting/decrypting messages before and after being sent to a Distributor
    pub encryption: EncryptionInfo,
    /// Store sent and received messages
    pub history: bool,
    // For servers
    connections: Connections,
    instance_id: InstanceID,
    received_messages: Vec<Message>,
    sent_messages: Vec<Message>,
    running: bool,
}

impl Stream {
    pub fn new(stream_type: StreamType, history: bool) -> Self {
        return Stream {
            stream_type,
            encryption: EMPTY_ENCRYPTIONIFNO,
            history,
            connections: Connections::empty(),
            instance_id: 0,
            received_messages: vec![],
            sent_messages: vec![],
            running: false,
        };
    }

    pub fn add_not_allowed_connections(&mut self, not_allowed_connections: Vec<ReceiveInfo>) {
        if self.stream_type.is_client() {
            return;
        }

        if self.connections.not_allowed.is_empty() {
            self.connections.not_allowed = not_allowed_connections;
        } else {
            for i in 0..not_allowed_connections.len() {
                self.connections
                    .not_allowed
                    .push(not_allowed_connections[i]);
            }
        }
    }

    pub fn check_add_connection(&mut self, message: Message) -> bool {
        if self.stream_type.is_client() {
            return false;
        }

        let ri = message.ti.into_ri(message.ri.instance_id, message.ri.port);

        if self.connections.is_allowed(ri) {
            return false;
        }

        if self.connections.current.get(&ri).is_some() {
            return true;
        } else {
            self.connections.current.insert(
                ri,
                Stream::new(
                    StreamType::Client {
                        rid: ri.rid,
                        rdid: ri.rdid,
                        port: ri.port,
                    },
                    self.history,
                ),
            );
            self.connections
                .current
                .get_mut(&ri)
                .unwrap()
                .add_encryption_info(self.encryption);
            self.connections.current.get_mut(&ri).unwrap().start();
            return true;
        }
    }

    pub fn remove_connection(&mut self, ri: ReceiveInfo) -> Code {
        if self.stream_type.is_client() {
            return UNKNOWN_STATUS;
        }

        let stream = self.connections.current.remove(&ri);
        if stream.is_none() {
            return UNKNOWN_STATUS;
        } else {
            stream.unwrap().write(String::new(), DISCONNECT_);
            return STATUS_OK;
        }
    }

    fn stream_file_exists(&self) -> bool {
        Path::new(&format!(
            "/tmp/darklight/connections/_dl_{}-{}",
            self.stream_type.rid(),
            self.stream_type.port()
        ))
        .exists()
    }

    pub fn add_encryption_info(&mut self, info: EncryptionInfo) {
        self.encryption = info;
    }

    pub fn running(&self) -> bool {
        self.running
    }

    /// Clears the messages sent and received
    pub fn clear_history(&mut self) {
        self.received_messages.clear();
        self.sent_messages.clear();
    }

    pub fn _read(&self) -> Vec<String> {
        sleep(Duration::from_micros(15));
        let reader = BufReader::new(
            File::options()
                .read(true)
                .open(&format!(
                    "/tmp/darklight/connections/_dl_{}-{}",
                    self.stream_type.rid(),
                    self.stream_type.port()
                ))
                .unwrap(),
        );
        let mut ret = vec![];

        for line in reader.lines() {
            if line.is_ok() {
                ret.push(line.unwrap());
            }
        }

        ret
    }

    pub fn read(&mut self) -> Vec<Message> {
        let mut ret = vec![];
        let strings = self._read();

        for i in 0..strings.len() {
            let received_message = Message::decode(&strings[i].to_owned(), self.encryption);
            println!("message ti: {:?}", received_message.ti);
            //let received_message = Message::from_string(&strings[i].to_owned());
            ret.push(received_message);
        }

        File::create(format!(
            "/tmp/darklight/connections/_dl_{}-{}",
            self.stream_type.rid(),
            self.stream_type.port()
        ))
        .unwrap();

        ret
    }

    /// Writes a ``Message`` to the stream (client)
    pub fn write_message(&self, message: Message) {
        let encoded = message.encode(self.encryption);

        send_dlcmd(SEND, encoded.split(" ").collect::<Vec<&str>>());
    }

    /// When a server receives a message, it should use the transmit info to respond by calling this function
    pub fn server_write(&mut self, ti: TransmitInfo, write: String, code: Code) {
        if self.stream_type.is_client() {
            return;
        }

        let ri = ti.into_ri(self.instance_id, self.stream_type.port());

        self.connections
            .current
            .get_mut(&ri)
            .unwrap()
            .write(write, code);
    }

    // Write a ``String`` to a client
    pub fn write(&self, write: String, code: Code) {
        if self.stream_type.is_client() {
            self.write_message(Message {
                ri: ReceiveInfo {
                    rid: self.stream_type.rid(),
                    rdid: self.stream_type.rdid(),
                    port: self.stream_type.port(),
                    instance_id: self.instance_id,
                },
                ti: TransmitInfo {
                    tid: local_user_id().unwrap(),
                    tdid: distributor_id().unwrap(),
                    code: code.value(),
                },
                day: self.encryption.info[0],
                week: self.encryption.info[1],
                month: self.encryption.info[2],
                contents: string_to_contents(write),
            });
        }
    }

    fn _server_start(&mut self) -> Code {
        let decode_info = self.encryption.info;
        let local_did = distributor_id().expect("Local Distributor Id is not set");
        let local_id = local_user_id().expect("Failed to get Local Id");

        // Creates a stream that's "connects" your device to itself
        send_dlcmd(
            CONNECT,
            vec![
                &local_did.to_string(),
                &local_id.to_string(),
                &self.stream_type.port().to_string(),
                &self.instance_id.to_string(),
                &decode_info[0].to_string(),
                &decode_info[1].to_string(),
                &decode_info[2].to_string(),
            ],
        );

        self.running = true;
        STATUS_OK
    }

    fn _client_start(&mut self) -> Code {
        let decode_info = self.encryption.info;

        // Create a stream
        send_dlcmd(
            CONNECT,
            vec![
                &self.stream_type.rdid().to_string(),
                &self.stream_type.rid().to_string(),
                &self.stream_type.port().to_string(),
                &self.instance_id.to_string(),
                &decode_info[0].to_string(),
                &decode_info[1].to_string(),
                &decode_info[2].to_string(),
            ],
        );

        // Delay to ensure the stream has been created by now
        sleep(Duration::from_millis(100));

        if self.stream_file_exists() == false {
            return UNKNOWN_STATUS;
        }

        // Request connection to the client/server
        self.write_message(Message {
            ti: TransmitInfo {
                tdid: distributor_id().expect("Failed to get local Distributor ID"),
                tid: local_user_id().expect("Failed to get local ID"),
                code: REQUEST_CONNECTION.value(),
            },
            ri: ReceiveInfo {
                rid: self.stream_type.rid(),
                rdid: self.stream_type.rdid(),
                port: self.stream_type.port(),
                instance_id: self.instance_id,
            },
            contents: [0; 4096],
            day: 0,
            week: 0,
            month: 0,
        });

        self.running = true;
        STATUS_OK
    }

    /// Starts the ``Stream``. If ``self.stream_type`` is ``Client`` it will try to connect to server/client, if it is
    /// ``Server`` it will allow connections on the port used in ``Server``.
    pub fn start(&mut self) -> Code {
        let ret = if self.stream_type.is_client() {
            self._client_start()
        } else {
            self._server_start()
        };

        self.running = true;
        ret
    }

    /// Stops the current stream.
    pub fn stop(&mut self) -> Code {
        self.running = false;

        self.write(String::new(), REMOVE_CLIENT);

        send_dlcmd(
            DISCONNECT,
            vec![
                &self.stream_type.rid().to_string(),
                &self.stream_type.port().to_string(),
                &self.stream_type.rdid().to_string(),
            ],
        );

        // Wait for darklight_driver
        sleep(Duration::from_micros(500));

        REMOVE_CLIENT
    }
}