1use crate::Point;
6use std::{rc::Rc, sync::Arc};
7
8pub const BUNDLE_MIME: &str = "application/vnd.day.transfer";
9pub const MAX_BYTES: usize = 64 * 1024 * 1024;
10pub const MAX_ITEMS: usize = 256;
11
12#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct Representation {
15 pub mime: String,
16 pub bytes: Arc<Vec<u8>>,
17}
18impl Representation {
19 pub fn new(mime: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
20 Self {
21 mime: mime.into(),
22 bytes: Arc::new(bytes.into()),
23 }
24 }
25}
26#[derive(Clone, Debug, Default, PartialEq, Eq)]
28pub struct Item {
29 pub representations: Vec<Representation>,
30}
31impl Item {
32 #[must_use]
33 pub fn new(representations: Vec<Representation>) -> Self {
34 Self { representations }
35 }
36 #[must_use]
37 pub fn get(&self, mime: &str) -> Option<&[u8]> {
38 self.representations
39 .iter()
40 .find(|r| r.mime == mime)
41 .map(|r| r.bytes.as_slice())
42 }
43}
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
45pub enum Operation {
46 #[default]
47 None,
48 Copy,
49 Move,
50 Link,
51}
52#[derive(Clone, Debug, Default, PartialEq, Eq)]
53pub struct Offer {
54 pub items: Vec<Item>,
55}
56
57#[derive(Clone, Debug)]
58pub struct Location {
59 pub position: Point,
61 pub types: Vec<String>,
62 pub allowed: Vec<Operation>,
63 pub local: bool,
65}
66impl Location {
67 #[must_use]
68 pub fn has(&self, mime: &str) -> bool {
69 self.types.iter().any(|m| m == mime)
70 }
71}
72#[derive(Clone, Debug)]
73pub struct Drop {
74 pub local: bool,
75 pub position: Point,
76 pub operation: Operation,
77 pub items: Vec<Item>,
78}
79pub type Source = Rc<dyn Fn(Point) -> Option<Offer>>;
81#[derive(Clone)]
85pub struct Target {
86 pub types: Vec<String>,
87 pub accept: Rc<dyn Fn(&Location) -> Operation>,
88 pub receive: Rc<dyn Fn(Drop) -> bool>,
89}
90impl Target {
91 #[must_use]
92 pub fn proposal(&self, location: &Location) -> Operation {
93 let op = crate::ffi_guard::contain(Operation::None, || (self.accept)(location));
94 if location.allowed.contains(&op) {
95 op
96 } else {
97 Operation::None
98 }
99 }
100 #[must_use]
101 #[expect(
102 clippy::needless_pass_by_value,
103 reason = "public signature; toolkits pass the location they built for this drop"
104 )]
105 pub fn deliver(&self, location: Location, offer: Offer) -> bool {
106 let op = self.proposal(&location);
107 op != Operation::None
108 && crate::ffi_guard::contain(false, || {
109 (self.receive)(Drop {
110 local: location.local,
111 position: location.position,
112 operation: op,
113 items: offer.items,
114 })
115 })
116 }
117}
118
119impl Offer {
122 #[must_use]
123 pub fn types(&self) -> Vec<String> {
124 let mut out = Vec::new();
125 for r in self.items.iter().flat_map(|i| &i.representations) {
126 if !out.contains(&r.mime) {
127 out.push(r.mime.clone());
128 }
129 }
130 out
131 }
132 #[must_use]
133 pub fn encode(&self) -> Option<Vec<u8>> {
134 if self.items.is_empty() || self.items.len() > MAX_ITEMS {
135 return None;
136 }
137 let mut out = b"DAYDND\0\x01".to_vec();
138 out.extend_from_slice(&(self.items.len() as u32).to_le_bytes());
139 for item in &self.items {
140 if item.representations.is_empty() || item.representations.len() > 32 {
141 return None;
142 }
143 out.extend_from_slice(&(item.representations.len() as u32).to_le_bytes());
144 let mut seen = std::collections::HashSet::new();
145 for r in &item.representations {
146 if !valid_mime(&r.mime) || r.mime == BUNDLE_MIME || !seen.insert(&r.mime) {
147 return None;
148 }
149 if out
150 .len()
151 .checked_add(r.mime.len() + 8)?
152 .checked_add(r.bytes.len())?
153 > MAX_BYTES
154 {
155 return None;
156 }
157 out.extend_from_slice(&(r.mime.len() as u32).to_le_bytes());
158 out.extend_from_slice(&(r.bytes.len() as u32).to_le_bytes());
159 out.extend_from_slice(r.mime.as_bytes());
160 out.extend_from_slice(&r.bytes);
161 }
162 }
163 Some(out)
164 }
165 #[must_use]
166 pub fn decode(mut bytes: &[u8]) -> Option<Self> {
167 fn take<'a>(b: &mut &'a [u8], n: usize) -> Option<&'a [u8]> {
168 let (a, rest) = b.split_at_checked(n)?;
169 *b = rest;
170 Some(a)
171 }
172 fn number(b: &mut &[u8]) -> Option<usize> {
173 Some(u32::from_le_bytes(take(b, 4)?.try_into().ok()?) as usize)
174 }
175 if bytes.len() > MAX_BYTES || take(&mut bytes, 8)? != b"DAYDND\0\x01" {
176 return None;
177 }
178 let count = number(&mut bytes)?;
179 if count == 0 || count > MAX_ITEMS {
180 return None;
181 }
182 let mut items = Vec::new();
183 for _ in 0..count {
184 let count = number(&mut bytes)?;
185 if count == 0 || count > 32 {
186 return None;
187 }
188 let mut representations = Vec::new();
189 for _ in 0..count {
190 let m = number(&mut bytes)?;
191 let n = number(&mut bytes)?;
192 if m > 255 {
193 return None;
194 }
195 let mime = std::str::from_utf8(take(&mut bytes, m)?).ok()?;
196 if !valid_mime(mime)
197 || mime == BUNDLE_MIME
198 || representations
199 .iter()
200 .any(|r: &Representation| r.mime == mime)
201 {
202 return None;
203 }
204 representations.push(Representation::new(mime, take(&mut bytes, n)?));
205 }
206 items.push(Item { representations });
207 }
208 if !bytes.is_empty() {
209 return None;
210 }
211 Some(Self { items })
212 }
213}
214#[must_use]
215pub fn valid_mime(m: &str) -> bool {
216 m.len() <= 255
217 && m.split_once('/')
218 .is_some_and(|(a, b)| !a.is_empty() && !b.is_empty() && !b.contains('/'))
219 && m.bytes()
220 .all(|c| c.is_ascii_alphanumeric() || b"/!#$&^_.+-".contains(&c))
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226 #[test]
227 fn items_and_alternatives_survive_untrusted_transport() {
228 let offer = Offer {
229 items: vec![
230 Item::new(vec![
231 Representation::new("image/png", [0, 255]),
232 Representation::new("application/x-test", [9, 0]),
233 ]),
234 Item::new(vec![Representation::new(
235 "text/uri-list",
236 b"file:///tmp/a%20b\r\n",
237 )]),
238 ],
239 };
240 let encoded = offer.encode().unwrap();
241 assert_eq!(Offer::decode(&encoded), Some(offer));
242 for n in 0..encoded.len() {
243 assert!(Offer::decode(&encoded[..n]).is_none());
244 }
245 let mut extra = encoded;
246 extra.push(0);
247 assert!(Offer::decode(&extra).is_none());
248 }
249 #[test]
250 fn location_guard_is_rechecked_and_cannot_escalate_operations() {
251 let target = Target {
252 types: vec![],
253 accept: Rc::new(|p| {
254 if p.position.x < 50.0 {
255 Operation::Copy
256 } else {
257 Operation::Move
258 }
259 }),
260 receive: Rc::new(|_| true),
261 };
262 let mut p = Location {
263 position: Point::new(5., 5.),
264 types: vec![],
265 allowed: vec![Operation::Copy],
266 local: true,
267 };
268 assert_eq!(target.proposal(&p), Operation::Copy);
269 p.position.x = 80.;
270 assert!(!target.deliver(p, Offer::default()));
271 }
272}
273
274pub fn file_paths(bytes: &[u8]) -> Option<Vec<std::path::PathBuf>> {
277 let text = std::str::from_utf8(bytes).ok()?;
278 let mut paths = Vec::new();
279 for line in text
280 .lines()
281 .map(str::trim)
282 .filter(|l| !l.is_empty() && !l.starts_with('#'))
283 {
284 let uri = line.strip_prefix("file://")?;
285 let path = if uri.starts_with('/') {
286 uri
287 } else {
288 uri.strip_prefix("localhost/")
289 .map(|p| &uri[uri.len() - p.len() - 1..])?
290 };
291 if path.contains(['?', '#']) {
292 return None;
293 }
294 let mut decoded = Vec::with_capacity(path.len());
295 let mut raw = path.bytes();
296 while let Some(b) = raw.next() {
297 let b = if b == b'%' {
298 let hi = (raw.next()? as char).to_digit(16)?;
299 let lo = (raw.next()? as char).to_digit(16)?;
300 (hi * 16 + lo) as u8
301 } else {
302 b
303 };
304 if b == 0 {
305 return None;
306 }
307 decoded.push(b);
308 }
309 #[cfg(unix)]
310 let path = {
311 use std::os::unix::ffi::OsStringExt;
312 std::path::PathBuf::from(std::ffi::OsString::from_vec(decoded))
313 };
314 #[cfg(not(unix))]
315 let path = {
316 let s = String::from_utf8(decoded).ok()?;
317 #[cfg(windows)]
318 let s = if s.as_bytes().get(2) == Some(&b':') {
319 s[1..].to_string()
320 } else {
321 s
322 };
323 std::path::PathBuf::from(s)
324 };
325 paths.push(path);
326 if paths.len() > MAX_ITEMS {
327 return None;
328 }
329 }
330 (!paths.is_empty()).then_some(paths)
331}
332
333#[cfg(test)]
334mod file_tests {
335 use super::*;
336 #[test]
337 fn uri_references_decode_without_fetching_remote_resources() {
338 assert_eq!(
339 file_paths(b"# files\r\nfile:///tmp/a%20b%23c.png\r\nfile://localhost/tmp/two\r\n")
340 .unwrap(),
341 vec![
342 std::path::PathBuf::from("/tmp/a b#c.png"),
343 std::path::PathBuf::from("/tmp/two")
344 ]
345 );
346 for s in [
347 "https://example.com/a",
348 "file://remote/a",
349 "file:///tmp/%00",
350 "file:///tmp/%xx",
351 "file:///tmp/a#fragment",
352 ] {
353 assert!(file_paths(s.as_bytes()).is_none());
354 }
355 }
356}