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
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
|
// decrypter.rs
//
// Copyright 2019 Jordan Petridis <jordan@centricular.com>
//
// 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 above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// 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.
//
// SPDX-License-Identifier: MIT
use gst::glib;
use gst::prelude::*;
use gst::subclass::prelude::*;
use sodiumoxide::crypto::box_;
use std::sync::Mutex;
use once_cell::sync::Lazy;
static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| {
gst::DebugCategory::new(
"sodiumdecrypter",
gst::DebugColorFlags::empty(),
Some("Decrypter Element"),
)
});
#[derive(Debug, Clone, Default)]
struct Props {
receiver_key: Option<glib::Bytes>,
sender_key: Option<glib::Bytes>,
}
#[derive(Debug)]
struct State {
adapter: gst_base::UniqueAdapter,
initial_nonce: Option<box_::Nonce>,
precomputed_key: box_::PrecomputedKey,
block_size: Option<u32>,
}
impl State {
fn from_props(props: &Props) -> Result<Self, gst::ErrorMessage> {
let sender_key = props
.sender_key
.as_ref()
.and_then(|k| box_::PublicKey::from_slice(k))
.ok_or_else(|| {
gst::error_msg!(
gst::ResourceError::NotFound,
[format!(
"Failed to set Sender's Key from property: {:?}",
props.sender_key
)
.as_ref()]
)
})?;
let receiver_key = props
.receiver_key
.as_ref()
.and_then(|k| box_::SecretKey::from_slice(k))
.ok_or_else(|| {
gst::error_msg!(
gst::ResourceError::NotFound,
[format!(
"Failed to set Receiver's Key from property: {:?}",
props.receiver_key
)
.as_ref()]
)
})?;
let precomputed_key = box_::precompute(&sender_key, &receiver_key);
Ok(Self {
adapter: gst_base::UniqueAdapter::new(),
precomputed_key,
initial_nonce: None,
block_size: None,
})
}
// Split the buffer into N(`chunk_index`) chunks of `block_size`,
// decrypt them, and push them to the internal adapter for further
// retrieval
fn decrypt_into_adapter(
&mut self,
imp: &Decrypter,
pad: &gst::Pad,
buffer: &gst::Buffer,
chunk_index: u64,
) -> Result<gst::FlowSuccess, gst::FlowError> {
let map = buffer.map_readable().map_err(|_| {
gst::element_imp_error!(
imp,
gst::StreamError::Format,
["Failed to map buffer readable"]
);
gst::FlowError::Error
})?;
gst::debug!(CAT, obj: pad, "Returned pull size: {}", map.len());
let mut nonce = add_nonce(self.initial_nonce.unwrap(), chunk_index);
let block_size = self.block_size.expect("Block size wasn't set") as usize + box_::MACBYTES;
for subbuffer in map.chunks(block_size) {
let plain =
box_::open_precomputed(subbuffer, &nonce, &self.precomputed_key).map_err(|_| {
gst::element_imp_error!(
imp,
gst::StreamError::Format,
["Failed to decrypt buffer"]
);
gst::FlowError::Error
})?;
// assumes little endian
nonce.increment_le_inplace();
self.adapter.push(gst::Buffer::from_mut_slice(plain));
}
Ok(gst::FlowSuccess::Ok)
}
// Retrieve the requested buffer out of the adapter.
fn requested_buffer(
&mut self,
pad: &gst::Pad,
buffer: Option<&mut gst::BufferRef>,
requested_size: u32,
adapter_offset: usize,
) -> Result<gst::PadGetRangeSuccess, gst::FlowError> {
let avail = self.adapter.available();
gst::debug!(CAT, obj: pad, "Avail: {}", avail);
gst::debug!(CAT, obj: pad, "Adapter offset: {}", adapter_offset);
// if this underflows, the available buffer in the adapter is smaller than the
// requested offset, which means we have reached EOS
let available_buffer = avail
.checked_sub(adapter_offset)
.ok_or(gst::FlowError::Eos)?;
// if the available buffer size is smaller than the requested, it's a short
// read and return that. Else return the requested size
let available_size = if available_buffer <= requested_size as usize {
available_buffer
} else {
requested_size as usize
};
if available_size == 0 {
self.adapter.clear();
// if the requested buffer was 0 sized, return an
// empty buffer
if requested_size == 0 {
if let Some(buffer) = buffer {
buffer.set_size(0);
return Ok(gst::PadGetRangeSuccess::FilledBuffer);
} else {
return Ok(gst::PadGetRangeSuccess::NewBuffer(gst::Buffer::new()));
}
}
return Err(gst::FlowError::Eos);
}
// discard what we don't need
assert!(self.adapter.available() >= adapter_offset);
self.adapter.flush(adapter_offset);
assert!(self.adapter.available() >= available_size);
let res = if let Some(buffer) = buffer {
let mut map = match buffer.map_writable() {
Ok(map) => map,
Err(e) => {
gst::error!(
CAT,
obj: pad,
"Failed to map provided buffer writable: {}",
e
);
return Err(gst::FlowError::Error);
}
};
if let Err(e) = self.adapter.copy(0, &mut map[..available_size]) {
gst::error!(CAT, obj: pad, "Failed to copy into provided buffer: {}", e);
return Err(gst::FlowError::Error);
}
if map.len() != available_size {
drop(map);
buffer.set_size(available_size);
}
gst::PadGetRangeSuccess::FilledBuffer
} else {
let buffer = self
.adapter
.take_buffer(available_size)
.expect("Failed to get buffer from adapter");
gst::PadGetRangeSuccess::NewBuffer(buffer)
};
// Cleanup the adapter
self.adapter.clear();
Ok(res)
}
}
/// Calculate the nonce of a block based on the initial nonce
/// and the block index in the stream.
///
/// This is a faster way of doing `(0..chunk_index).for_each(|_| nonce.increment_le_inplace());`
fn add_nonce(initial_nonce: box_::Nonce, chunk_index: u64) -> box_::Nonce {
let mut nonce = initial_nonce.0;
// convert our index to a bytes array
// add padding so our 8byte array of the chunk_index will have an
// equal length with the nonce, padding at the end cause little endian
let idx = chunk_index.to_le_bytes();
let idx = &[
idx[0], idx[1], idx[2], idx[3], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
assert_eq!(idx.len(), box_::NONCEBYTES);
// add the chunk index to the nonce
sodiumoxide::utils::add_le(&mut nonce, idx).expect("Failed to calculate the nonce");
// construct back a nonce from our custom array
box_::Nonce::from_slice(&nonce).expect("Failed to convert slice back to Nonce")
}
pub struct Decrypter {
srcpad: gst::Pad,
sinkpad: gst::Pad,
props: Mutex<Props>,
state: Mutex<Option<State>>,
}
impl Decrypter {
fn src_activatemode_function(
&self,
_pad: &gst::Pad,
mode: gst::PadMode,
active: bool,
) -> Result<(), gst::LoggableError> {
match mode {
gst::PadMode::Pull => {
self.sinkpad
.activate_mode(mode, active)
.map_err(gst::LoggableError::from)?;
// Set the nonce and block size from the headers
// right after we activate the pad
self.check_headers()
}
gst::PadMode::Push => Err(gst::loggable_error!(CAT, "Push mode not supported")),
_ => Err(gst::loggable_error!(
CAT,
"Failed to activate the pad in Unknown mode, {:?}",
mode
)),
}
}
fn src_query(&self, pad: &gst::Pad, query: &mut gst::QueryRef) -> bool {
use gst::QueryViewMut;
gst::log!(CAT, obj: pad, "Handling query {:?}", query);
match query.view_mut() {
QueryViewMut::Scheduling(q) => {
let mut peer_query = gst::query::Scheduling::new();
let res = self.sinkpad.peer_query(&mut peer_query);
if !res {
return res;
}
gst::log!(CAT, obj: pad, "Upstream returned {:?}", peer_query);
let (flags, min, max, align) = peer_query.result();
q.set(flags, min, max, align);
q.add_scheduling_modes(&[gst::PadMode::Pull]);
gst::log!(CAT, obj: pad, "Returning {:?}", q.query_mut());
true
}
QueryViewMut::Duration(q) => {
if q.format() != gst::Format::Bytes {
return gst::Pad::query_default(pad, Some(&*self.instance()), query);
}
/* First let's query the bytes duration upstream */
let mut peer_query = gst::query::Duration::new(gst::Format::Bytes);
if !self.sinkpad.peer_query(&mut peer_query) {
gst::error!(CAT, "Failed to query upstream duration");
return false;
}
let size = match peer_query.result() {
gst::GenericFormattedValue::Bytes(Some(size)) => *size,
_ => {
gst::error!(CAT, "Failed to query upstream duration");
return false;
}
};
let state = self.state.lock().unwrap();
let state = match state.as_ref() {
// If state isn't set, it means that the
// element hasn't been activated yet.
None => return false,
Some(s) => s,
};
// subtract static offsets
let size = size - crate::HEADERS_SIZE as u64;
// calculate the number of chunks that exist in the stream
let total_chunks =
(size - 1) / state.block_size.expect("Block size wasn't set") as u64;
// subtrack the MAC of each block
let size = size - total_chunks * box_::MACBYTES as u64;
gst::debug!(CAT, obj: pad, "Setting duration bytes: {}", size);
q.set(gst::format::Bytes::from_u64(size));
true
}
_ => gst::Pad::query_default(pad, Some(&*self.instance()), query),
}
}
fn check_headers(&self) -> Result<(), gst::LoggableError> {
let is_none = {
let mutex_state = self.state.lock().unwrap();
let state = mutex_state.as_ref().unwrap();
state.initial_nonce.is_none()
};
if !is_none {
return Ok(());
}
let buffer = self
.sinkpad
.pull_range(0, crate::HEADERS_SIZE as u32)
.map_err(|err| {
let err = gst::loggable_error!(
CAT,
"Failed to pull nonce from the stream, reason: {:?}",
err
);
err
})?;
if buffer.size() != crate::HEADERS_SIZE {
let err = gst::loggable_error!(CAT, "Headers buffer has wrong size");
return Err(err);
}
let map = buffer.map_readable().map_err(|_| {
let err = gst::loggable_error!(CAT, "Failed to map buffer readable");
err
})?;
let sodium_header_slice = &map[..crate::TYPEFIND_HEADER_SIZE];
if sodium_header_slice != crate::TYPEFIND_HEADER {
let err = gst::loggable_error!(CAT, "Buffer has wrong typefind header");
return Err(err);
}
let nonce_slice =
&map[crate::TYPEFIND_HEADER_SIZE..crate::TYPEFIND_HEADER_SIZE + box_::NONCEBYTES];
assert_eq!(nonce_slice.len(), box_::NONCEBYTES);
let nonce = box_::Nonce::from_slice(nonce_slice).ok_or_else(|| {
let err = gst::loggable_error!(CAT, "Failed to create nonce from buffer");
err
})?;
let slice = &map[crate::TYPEFIND_HEADER_SIZE + box_::NONCEBYTES..crate::HEADERS_SIZE];
assert_eq!(
crate::HEADERS_SIZE - crate::TYPEFIND_HEADER_SIZE - box_::NONCEBYTES,
4
);
let block_size = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]);
// reacquire the lock again to change the state
let mut state = self.state.lock().unwrap();
let state = state.as_mut().unwrap();
state.initial_nonce = Some(nonce);
gst::debug!(CAT, imp: self, "Setting nonce to: {:?}", nonce.0);
state.block_size = Some(block_size);
gst::debug!(CAT, imp: self, "Setting block size to: {}", block_size);
Ok(())
}
fn pull_requested_buffer(
&self,
pad: &gst::Pad,
requested_size: u32,
block_size: u32,
chunk_index: u64,
) -> Result<gst::Buffer, gst::FlowError> {
let pull_offset = crate::HEADERS_SIZE as u64
+ (chunk_index * block_size as u64)
+ (chunk_index * box_::MACBYTES as u64);
gst::debug!(CAT, obj: pad, "Pull offset: {}", pull_offset);
gst::debug!(CAT, obj: pad, "block size: {}", block_size);
// calculate how many chunks are needed, if we need something like 3.2
// round the number to 4 and cut the buffer afterwards.
let checked = requested_size.checked_add(block_size).ok_or_else(|| {
gst::element_imp_error!(
self,
gst::LibraryError::Failed,
[
"Addition overflow when adding requested pull size and block size: {} + {}",
requested_size,
block_size,
]
);
gst::FlowError::Error
})?;
// Read at least one chunk in case 0 bytes were requested
let total_chunks = u32::max((checked - 1) / block_size, 1);
gst::debug!(CAT, obj: pad, "Blocks to be pulled: {}", total_chunks);
// Pull a buffer of all the chunks we will need
let checked_size = total_chunks.checked_mul(block_size).ok_or_else(|| {
gst::element_imp_error!(
self,
gst::LibraryError::Failed,
[
"Overflowed trying to calculate the buffer size to pull: {} * {}",
total_chunks,
block_size,
]
);
gst::FlowError::Error
})?;
let total_size = checked_size + (total_chunks * box_::MACBYTES as u32);
gst::debug!(CAT, obj: pad, "Requested pull size: {}", total_size);
self.sinkpad.pull_range(pull_offset, total_size).map_err(|err| {
match err {
gst::FlowError::Flushing => {
gst::debug!(CAT, obj: &self.sinkpad, "Pausing after pulling buffer, reason: flushing");
}
gst::FlowError::Eos => {
gst::debug!(CAT, obj: &self.sinkpad, "Eos");
}
flow => {
gst::error!(CAT, obj: &self.sinkpad, "Failed to pull, reason: {:?}", flow);
}
};
err
})
}
fn range(
&self,
pad: &gst::Pad,
offset: u64,
buffer: Option<&mut gst::BufferRef>,
requested_size: u32,
) -> Result<gst::PadGetRangeSuccess, gst::FlowError> {
let block_size = {
let mut mutex_state = self.state.lock().unwrap();
// This will only be run after READY state,
// and will be guaranted to be initialized
let state = mutex_state.as_mut().unwrap();
// Cleanup the adapter
state.adapter.clear();
state.block_size.expect("Block size wasn't set")
};
gst::debug!(CAT, obj: pad, "Requested offset: {}", offset);
gst::debug!(CAT, obj: pad, "Requested size: {}", requested_size);
let chunk_index = offset as u64 / block_size as u64;
gst::debug!(CAT, obj: pad, "Stream Block index: {}", chunk_index);
let pull_offset = offset - (chunk_index * block_size as u64);
assert!(pull_offset <= std::u32::MAX as u64);
let pull_offset = pull_offset as u32;
let pulled_buffer =
self.pull_requested_buffer(pad, requested_size + pull_offset, block_size, chunk_index)?;
let mut state = self.state.lock().unwrap();
// This will only be run after READY state,
// and will be guaranted to be initialized
let state = state.as_mut().unwrap();
state.decrypt_into_adapter(self, &self.srcpad, &pulled_buffer, chunk_index)?;
let adapter_offset = pull_offset as usize;
state.requested_buffer(&self.srcpad, buffer, requested_size, adapter_offset)
}
}
#[glib::object_subclass]
impl ObjectSubclass for Decrypter {
const NAME: &'static str = "RsSodiumDecryptor";
type Type = super::Decrypter;
type ParentType = gst::Element;
fn with_class(klass: &Self::Class) -> Self {
let templ = klass.pad_template("sink").unwrap();
let sinkpad = gst::Pad::from_template(&templ, Some("sink"));
let templ = klass.pad_template("src").unwrap();
let srcpad = gst::Pad::builder_with_template(&templ, Some("src"))
.getrange_function(|pad, parent, offset, buffer, size| {
Decrypter::catch_panic_pad_function(
parent,
|| Err(gst::FlowError::Error),
|decrypter| decrypter.range(pad, offset, buffer, size),
)
})
.activatemode_function(|pad, parent, mode, active| {
Decrypter::catch_panic_pad_function(
parent,
|| {
Err(gst::loggable_error!(
CAT,
"Panic activating srcpad with mode"
))
},
|decrypter| decrypter.src_activatemode_function(pad, mode, active),
)
})
.query_function(|pad, parent, query| {
Decrypter::catch_panic_pad_function(
parent,
|| false,
|decrypter| decrypter.src_query(pad, query),
)
})
.build();
let props = Mutex::new(Props::default());
let state = Mutex::new(None);
Self {
srcpad,
sinkpad,
props,
state,
}
}
}
impl ObjectImpl for Decrypter {
fn properties() -> &'static [glib::ParamSpec] {
static PROPERTIES: Lazy<Vec<glib::ParamSpec>> = Lazy::new(|| {
vec![
glib::ParamSpecBoxed::builder::<glib::Bytes>("receiver-key")
.nick("Receiver Key")
.blurb("The private key of the Receiver")
.build(),
glib::ParamSpecBoxed::builder::<glib::Bytes>("sender-key")
.nick("Sender Key")
.blurb("The public key of the Sender")
.write_only()
.build(),
]
});
PROPERTIES.as_ref()
}
fn constructed(&self) {
self.parent_constructed();
let obj = self.instance();
obj.add_pad(&self.sinkpad).unwrap();
obj.add_pad(&self.srcpad).unwrap();
}
fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
match pspec.name() {
"sender-key" => {
let mut props = self.props.lock().unwrap();
props.sender_key = value.get().expect("type checked upstream");
}
"receiver-key" => {
let mut props = self.props.lock().unwrap();
props.receiver_key = value.get().expect("type checked upstream");
}
_ => unimplemented!(),
}
}
fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
match pspec.name() {
"receiver-key" => {
let props = self.props.lock().unwrap();
props.receiver_key.to_value()
}
_ => unimplemented!(),
}
}
}
impl GstObjectImpl for Decrypter {}
impl ElementImpl for Decrypter {
fn metadata() -> Option<&'static gst::subclass::ElementMetadata> {
static ELEMENT_METADATA: Lazy<gst::subclass::ElementMetadata> = Lazy::new(|| {
gst::subclass::ElementMetadata::new(
"Decrypter",
"Generic",
"libsodium-based file decrypter",
"Jordan Petridis <jordan@centricular.com>",
)
});
Some(&*ELEMENT_METADATA)
}
fn pad_templates() -> &'static [gst::PadTemplate] {
static PAD_TEMPLATES: Lazy<Vec<gst::PadTemplate>> = Lazy::new(|| {
let src_pad_template = gst::PadTemplate::new(
"src",
gst::PadDirection::Src,
gst::PadPresence::Always,
&gst::Caps::new_any(),
)
.unwrap();
let sink_caps = gst::Caps::builder("application/x-sodium-encrypted").build();
let sink_pad_template = gst::PadTemplate::new(
"sink",
gst::PadDirection::Sink,
gst::PadPresence::Always,
&sink_caps,
)
.unwrap();
vec![src_pad_template, sink_pad_template]
});
PAD_TEMPLATES.as_ref()
}
fn change_state(
&self,
transition: gst::StateChange,
) -> Result<gst::StateChangeSuccess, gst::StateChangeError> {
gst::debug!(CAT, imp: self, "Changing state {:?}", transition);
match transition {
gst::StateChange::NullToReady => {
let props = self.props.lock().unwrap().clone();
// Create an internal state struct from the provided properties or
// refuse to change state
let state_ = State::from_props(&props).map_err(|err| {
self.post_error_message(err);
gst::StateChangeError
})?;
let mut state = self.state.lock().unwrap();
*state = Some(state_);
}
gst::StateChange::ReadyToNull => {
let _ = self.state.lock().unwrap().take();
}
_ => (),
}
let success = self.parent_change_state(transition)?;
if transition == gst::StateChange::ReadyToNull {
let _ = self.state.lock().unwrap().take();
}
Ok(success)
}
}
|