tailtalk 0.4.4

A modern async user space AppleTalk stack with Rust + Tokio
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
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
use std::path::Path;
use tailtalk_packets::afp::AfpError;
use tracing::error;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct IconKey {
    pub creator: [u8; 4],
    pub file_type: [u8; 4],
    pub icon_type: u8,
}

impl IconKey {
    pub fn to_bytes(&self) -> [u8; 9] {
        let mut bytes = [0u8; 9];
        // AFP creator and file_type are exactly 4 bytes (Mac OS OSType format)
        bytes[0..4].copy_from_slice(&self.creator);
        bytes[4..8].copy_from_slice(&self.file_type);

        bytes[8] = self.icon_type;
        bytes
    }
}

pub struct DesktopDatabase {
    pub dt_ref_num: u16,
    icons: sled::Tree,
    comments: sled::Tree,
    appls: sled::Tree,
}

impl DesktopDatabase {
    /// Open (or create) the desktop database at the standard path under `volume_root`.
    pub fn open_or_create(volume_root: &Path) -> Result<sled::Db, AfpError> {
        let db_path = volume_root.join(".tailtalk").join("desktop.db");

        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                error!(
                    "Failed to create Desktop Database directory at {:?}: {}",
                    parent, e
                );
                AfpError::AccessDenied
            })?;
        }

        sled::open(&db_path).map_err(|e| {
            error!("Failed to open Desktop Database at {:?}: {}", db_path, e);
            AfpError::AccessDenied
        })
    }

    /// Construct a `DesktopDatabase` from an already-open `sled::Db` handle.
    /// Use this to share a single DB handle across multiple AFP sessions.
    pub fn from_db(db: sled::Db, dt_ref_num: u16) -> Result<Self, AfpError> {
        let icons = db.open_tree(b"icons").map_err(|e| {
            error!("Failed to open 'icons' tree: {}", e);
            AfpError::AccessDenied
        })?;
        let comments = db.open_tree(b"comments").map_err(|e| {
            error!("Failed to open 'comments' tree: {}", e);
            AfpError::AccessDenied
        })?;
        let appls = db.open_tree(b"appls").map_err(|e| {
            error!("Failed to open 'appls' tree: {}", e);
            AfpError::AccessDenied
        })?;
        Ok(Self { dt_ref_num, icons, comments, appls })
    }

    /// Open (or create) the desktop database at the standard path and wrap it.
    /// Prefer `open_or_create` + `from_db` when sharing across sessions.
    pub fn new(volume_root: &Path, dt_ref_num: u16) -> Result<Self, AfpError> {
        let db = Self::open_or_create(volume_root)?;
        Self::from_db(db, dt_ref_num)
    }

    pub fn add_icon(
        &self,
        creator: [u8; 4],
        file_type: [u8; 4],
        icon_type: u8,
        icon_data: &[u8],
    ) -> Result<(), AfpError> {
        let key = IconKey {
            creator,
            file_type,
            icon_type,
        };

        self.icons.insert(key.to_bytes(), icon_data).map_err(|e| {
            error!("Failed to insert icon: {}", e);
            AfpError::AccessDenied
        })?;
        Ok(())
    }

    pub fn get_icon(
        &self,
        creator: [u8; 4],
        file_type: [u8; 4],
        icon_type: u8,
        // AFP wire format includes an iconSize field; we store one copy per type and ignore it.
        _size: u16,
    ) -> Result<Vec<u8>, AfpError> {
        let key = IconKey {
            creator,
            file_type,
            icon_type,
        };

        if let Some(data) = self.icons.get(key.to_bytes()).map_err(|e| {
            error!("Failed to get icon: {}", e);
            AfpError::AccessDenied
        })? {
            Ok(data.to_vec())
        } else {
            Err(AfpError::ItemNotFound)
        }
    }
    pub fn get_icon_info(
        &self,
        creator: [u8; 4],
        _icon_type: u16,
    ) -> Result<(u32, u32, u16), AfpError> {
        // Since sled stores the entire icon, we can iterate over the keys matching the creator
        // and find an icon type that matches the request. Or return basic size info.

        // Format is:
        // tag (4 bytes)
        // file_type (4 bytes)
        // icon_type (1 byte, padding, or matching requested size)
        // size (2 bytes)

        for result in self.icons.iter() {
            if let Ok((key, value)) = result
                && key.len() == 9
            {
                let mut key_creator = [0u8; 4];
                key_creator.copy_from_slice(&key[0..4]);
                if key_creator == creator {
                    let mut file_type = [0u8; 4];
                    file_type.copy_from_slice(&key[4..8]);

                    // We just return the first icon we find for this creator
                    // For a full implementation we would want to correctly parse the icon_type u16 request into the actual icon_type u8
                    // Return: IconTag (4 bytes), FileCreator/Type (4 bytes), Size (2 bytes)
                    let icon_tag = 0; // Or whatever tag you want
                    let file_type_u32 = u32::from_be_bytes(file_type);
                    let size = value.len() as u16;

                    return Ok((icon_tag, file_type_u32, size));
                }
            }
        }

        Err(AfpError::ItemNotFound)
    }

    pub fn set_comment(&self, rel_path: &std::path::Path, comment: &[u8]) -> Result<(), AfpError> {
        let key = rel_path.to_string_lossy();
        self.comments.insert(key.as_bytes(), comment).map_err(|e| {
            error!("Failed to insert comment: {}", e);
            AfpError::AccessDenied
        })?;

        tracing::info!(
            "Set comment of length {} for path {:?}",
            comment.len(),
            rel_path
        );
        Ok(())
    }

    pub fn get_comment(&self, rel_path: &std::path::Path) -> Result<Vec<u8>, AfpError> {
        tracing::info!("Get comment for path {:?}", rel_path);
        let key = rel_path.to_string_lossy();
        if let Some(data) = self.comments.get(key.as_bytes()).map_err(|e| {
            error!("Failed to get comment: {}", e);
            AfpError::AccessDenied
        })? {
            Ok(data.to_vec())
        } else {
            Err(AfpError::ItemNotFound)
        }
    }

    pub fn remove_comment(&self, rel_path: &std::path::Path) -> Result<(), AfpError> {
        let key = rel_path.to_string_lossy();
        self.comments.remove(key.as_bytes()).map_err(|e| {
            error!("Failed to remove comment: {}", e);
            AfpError::AccessDenied
        })?;
        Ok(())
    }

    /// Move a comment from `old_path` to `new_path`, used when a file is renamed or moved.
    /// Silently succeeds if no comment exists for `old_path`.
    pub fn move_comment(
        &self,
        old_path: &std::path::Path,
        new_path: &std::path::Path,
    ) -> Result<(), AfpError> {
        let old_key = old_path.to_string_lossy();
        if let Some(data) = self.comments.remove(old_key.as_bytes()).map_err(|e| {
            error!("Failed to remove old comment key: {}", e);
            AfpError::AccessDenied
        })? {
            let new_key = new_path.to_string_lossy();
            self.comments.insert(new_key.as_bytes(), data).map_err(|e| {
                error!("Failed to insert comment at new key: {}", e);
                AfpError::AccessDenied
            })?;
        }
        Ok(())
    }

    /// Copy a comment from `src_path` to `dst_path`, used when a file is copied.
    /// Silently succeeds if no comment exists for `src_path`.
    pub fn copy_comment(
        &self,
        src_path: &std::path::Path,
        dst_path: &std::path::Path,
    ) -> Result<(), AfpError> {
        let src_key = src_path.to_string_lossy();
        if let Some(data) = self.comments.get(src_key.as_bytes()).map_err(|e| {
            error!("Failed to read comment for copy: {}", e);
            AfpError::AccessDenied
        })? {
            let dst_key = dst_path.to_string_lossy();
            self.comments.insert(dst_key.as_bytes(), data).map_err(|e| {
                error!("Failed to insert copied comment: {}", e);
                AfpError::AccessDenied
            })?;
        }
        Ok(())
    }

    /// Update the stored path in every APPL entry that matches `old_path`, used when
    /// a file is renamed or moved.  Silently succeeds if no matching entry exists.
    pub fn move_appl_path(
        &self,
        old_path: &str,
        new_path: &str,
        old_dir_id: u32,
        new_dir_id: u32,
    ) -> Result<(), AfpError> {
        let old_dir_bytes = old_dir_id.to_be_bytes();
        let old_path_bytes = old_path.as_bytes();

        let matches: Vec<(sled::IVec, sled::IVec)> = self.appls
            .iter()
            .filter_map(|r| r.ok())
            .filter(|(_, v)| {
                v.len() >= 5
                    && v[0..4] == old_dir_bytes
                    && {
                        let path_len = v[4] as usize;
                        v.len() >= 5 + path_len && &v[5..5 + path_len] == old_path_bytes
                    }
            })
            .collect();

        let new_path_bytes = new_path.as_bytes();
        let new_dir_bytes = new_dir_id.to_be_bytes();
        for (key, _) in matches {
            let mut value = Vec::with_capacity(5 + new_path_bytes.len());
            value.extend_from_slice(&new_dir_bytes);
            value.push(new_path_bytes.len() as u8);
            value.extend_from_slice(new_path_bytes);
            self.appls.insert(key, value).map_err(|e| {
                error!("Failed to update APPL path: {}", e);
                AfpError::AccessDenied
            })?;
        }
        Ok(())
    }

    /// Copy APPL entries from `src_path` to `dst_path`, used when a file is copied.
    /// Silently succeeds if no matching entry exists.
    pub fn copy_appl(
        &self,
        src_path: &str,
        dst_path: &str,
        src_dir_id: u32,
        dst_dir_id: u32,
    ) -> Result<(), AfpError> {
        let src_dir_bytes = src_dir_id.to_be_bytes();
        let src_path_bytes = src_path.as_bytes();

        let matches: Vec<(sled::IVec, sled::IVec)> = self.appls
            .iter()
            .filter_map(|r| r.ok())
            .filter(|(_, v)| {
                v.len() >= 5
                    && v[0..4] == src_dir_bytes
                    && {
                        let path_len = v[4] as usize;
                        v.len() >= 5 + path_len && &v[5..5 + path_len] == src_path_bytes
                    }
            })
            .collect();

        let dst_path_bytes = dst_path.as_bytes();
        let dst_dir_bytes = dst_dir_id.to_be_bytes();
        for (key, _) in matches {
            let mut value = Vec::with_capacity(5 + dst_path_bytes.len());
            value.extend_from_slice(&dst_dir_bytes);
            value.push(dst_path_bytes.len() as u8);
            value.extend_from_slice(dst_path_bytes);
            self.appls.insert(key, value).map_err(|e| {
                error!("Failed to insert copied APPL: {}", e);
                AfpError::AccessDenied
            })?;
        }
        Ok(())
    }

    /// Remove all APPL entries whose stored path matches `path` and directory ID matches
    /// `dir_id`. Used when a file is deleted. Silently succeeds if no match exists.
    pub fn delete_appls_for_path(&self, dir_id: u32, path: &str) -> Result<(), AfpError> {
        let dir_bytes = dir_id.to_be_bytes();
        let path_bytes = path.as_bytes();

        let keys: Vec<sled::IVec> = self.appls
            .iter()
            .filter_map(|r| r.ok())
            .filter(|(_, v)| {
                v.len() >= 5
                    && v[0..4] == dir_bytes
                    && {
                        let path_len = v[4] as usize;
                        v.len() >= 5 + path_len && &v[5..5 + path_len] == path_bytes
                    }
            })
            .map(|(k, _)| k)
            .collect();

        for key in keys {
            self.appls.remove(key).map_err(|e| {
                error!("Failed to remove APPL entry: {}", e);
                AfpError::AccessDenied
            })?;
        }
        Ok(())
    }

    /// Register an application in the Desktop DB.
    ///
    /// Key: creator (4) + tag (4, big-endian) — one entry per (creator, tag) pair.
    /// Value: directory_id (4) + path_len (1) + path bytes.
    pub fn add_appl(
        &self,
        creator: [u8; 4],
        tag: u32,
        directory_id: u32,
        path: &str,
    ) -> Result<(), AfpError> {
        let mut key = [0u8; 8];
        key[0..4].copy_from_slice(&creator);
        key[4..8].copy_from_slice(&tag.to_be_bytes());

        let path_bytes = path.as_bytes();
        if path_bytes.len() > 255 {
            return Err(AfpError::ParamError);
        }
        let mut value = Vec::with_capacity(5 + path_bytes.len());
        value.extend_from_slice(&directory_id.to_be_bytes());
        value.push(path_bytes.len() as u8);
        value.extend_from_slice(path_bytes);

        self.appls.insert(key, value).map_err(|e| {
            error!("Failed to insert APPL: {}", e);
            AfpError::AccessDenied
        })?;
        Ok(())
    }

    /// Deregister an application identified by (creator, directory_id, path).
    pub fn remove_appl(
        &self,
        creator: [u8; 4],
        directory_id: u32,
        path: &str,
    ) -> Result<(), AfpError> {
        let dir_bytes = directory_id.to_be_bytes();
        let path_bytes = path.as_bytes();

        for result in self.appls.scan_prefix(creator) {
            let (key, value) = result.map_err(|e| {
                error!("Failed to scan APPLs: {}", e);
                AfpError::AccessDenied
            })?;

            if value.len() >= 5 {
                let path_len = value[4] as usize;
                if value[0..4] == dir_bytes
                    && value.len() >= 5 + path_len
                    && &value[5..5 + path_len] == path_bytes
                {
                    self.appls.remove(&key).map_err(|e| {
                        error!("Failed to remove APPL: {}", e);
                        AfpError::AccessDenied
                    })?;
                    return Ok(());
                }
            }
        }

        Err(AfpError::ItemNotFound)
    }

    /// Retrieve a registered application by creator and 1-based index.
    ///
    /// Returns (tag, directory_id, path).
    pub fn get_appl(
        &self,
        creator: [u8; 4],
        index: u16,
    ) -> Result<(u32, u32, String), AfpError> {
        let target = index.saturating_sub(1) as usize;
        for (i, result) in self.appls.scan_prefix(creator).enumerate() {
            let (key, value) = result.map_err(|e| {
                error!("Failed to scan APPLs: {}", e);
                AfpError::AccessDenied
            })?;

            if i == target {
                if key.len() < 8 || value.len() < 5 {
                    return Err(AfpError::ItemNotFound);
                }
                let tag = u32::from_be_bytes(key[4..8].try_into().unwrap());
                let directory_id = u32::from_be_bytes(value[0..4].try_into().unwrap());
                let path_len = value[4] as usize;
                let path = if value.len() >= 5 + path_len {
                    String::from_utf8_lossy(&value[5..5 + path_len]).into_owned()
                } else {
                    String::new()
                };
                return Ok((tag, directory_id, path));
            }
        }

        Err(AfpError::ItemNotFound)
    }
}