ctb_formats_lnk/lnk.rs
1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from lnk_rs: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program. If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Copyright (c) 2023 Lily Hopkins
22// From https://github.com/lilopkins/lnk-rs
23
24// See additional licensing details at end of file.
25
26//! Windows Shell Link (.lnk) binary file format parsing utilities.
27
28#[allow(
29 unused_imports,
30 clippy::wildcard_imports,
31 reason = "Standard workspace crate prelude"
32)]
33pub(crate) use ctb_utilities::*;
34
35use binrw::{BinReaderExt, BinWrite};
36use ctb_utilities::anyhow::anyhow;
37use std::io::Cursor;
38use std::path::{self, Path, PathBuf};
39
40pub use lnk::encoding;
41use lnk::{
42 LinkFlags, LinkInfo, LinkTargetIdList, ShellLink, ShellLinkHeader,
43 StringData, StringEncoding,
44};
45
46#[cfg(test)]
47pub(crate) fn get_lnk_data(key: &str) -> Option<Vec<u8>> {
48 ctb_utilities::load_manifest_fixture(env!("CARGO_MANIFEST_DIR"), key)
49}
50
51fn split_windowsish_path(path: &str) -> (Option<&str>, &str) {
52 let sep_index = path.rfind('\\').into_iter().chain(path.rfind('/')).max();
53
54 let Some(sep_index) = sep_index else {
55 return (None, path);
56 };
57
58 let working_dir = path.get(..sep_index).filter(|d| !d.is_empty());
59 // Reason for fallback: if sep_index + 1 exceeds path length, fallback to whole path as file name.
60 let file_name = path.get(sep_index.saturating_add(1)..).unwrap_or(path);
61
62 (working_dir, file_name)
63}
64
65pub fn create_simple_lnk<P: AsRef<std::path::Path>>(
66 target_path: P,
67 name: Option<&str>,
68) -> Result<Vec<u8>> {
69 // NOTE: `ShellLink::new_simple` touches the filesystem (metadata + canonicalize).
70 // This helper is meant to be purely in-memory, so we construct a default link and
71 // populate the relevant StringData fields ourselves.
72 let target = target_path.as_ref().to_string_lossy();
73 let (working_dir, file_name) = split_windowsish_path(&target);
74
75 // Reason for fallback: working directory defaults to current directory '.' if no path separator was present in target path.
76 let working_dir = working_dir.unwrap_or(".");
77 let relative_name = if file_name.is_empty() {
78 target.as_ref()
79 } else {
80 file_name
81 };
82 let relative_path = format!(".\\{relative_name}");
83
84 let mut lnk = ShellLink::default().with_encoding(&StringEncoding::Unicode);
85 if let Some(name) = name {
86 lnk.set_name(Some(name.to_owned()));
87 } else {
88 lnk.set_name(None);
89 }
90 lnk.set_relative_path(Some(relative_path));
91 lnk.set_working_dir(Some(working_dir.to_string()));
92 let mut buffer: Vec<u8> = Vec::new();
93
94 let mut w = Cursor::new(&mut buffer);
95
96 debug!("Writing header...");
97 // Invoke binwrite
98 lnk.header()
99 .write_le(&mut w)
100 .context("Failed to write LNK header")?;
101
102 let link_flags = *lnk.header().link_flags();
103 debug!("Writing StringData...");
104 lnk.string_data()
105 .write_le_args(&mut w, (link_flags, encoding::UTF_16LE))
106 .context("Failed to write LNK string data")?;
107
108 // if link_flags.contains(LinkFlags::HAS_LINK_TARGET_ID_LIST) {
109 // if let None = lnk.linktarget_id_list {
110 // error!("LinkTargetIDList not specified but expected!")
111 // }
112 // debug!("A LinkTargetIDList is marked as present. Writing.");
113 // let mut data: Vec<u8> = lnk.linktarget_id_list.clone().unwrap().into();
114 // w.write_all(&mut data)?;
115 // }
116
117 // if link_flags.contains(LinkFlags::HAS_LINK_INFO) {
118 // if let None = lnk.link_info {
119 // error!("LinkInfo not specified but expected!")
120 // }
121 // debug!("LinkInfo is marked as present. Writing.");
122 // let mut data: Vec<u8> = lnk.link_info.clone().unwrap().into();
123 // w.write_all(&mut data)?;
124 // }
125
126 // if link_flags.contains(LinkFlags::HAS_NAME) {
127 // if lnk.name_string == None {
128 // error!("Name not specified but expected!")
129 // }
130 // debug!("Name is marked as present. Writing.");
131 // w.write_all(&stringdata::to_data(
132 // lnk.name_string.as_ref().unwrap(),
133 // link_flags,
134 // ))?;
135 // }
136
137 // if link_flags.contains(LinkFlags::HAS_RELATIVE_PATH) {
138 // if lnk.relative_path == None {
139 // error!("Relative path not specified but expected!")
140 // }
141 // debug!("Relative path is marked as present. Writing.");
142 // w.write_all(&stringdata::to_data(
143 // lnk.relative_path.as_ref().unwrap(),
144 // link_flags,
145 // ))?;
146 // }
147
148 // if link_flags.contains(LinkFlags::HAS_WORKING_DIR) {
149 // if lnk.working_dir == None {
150 // error!("Working Directory not specified but expected!")
151 // }
152 // debug!("Working dir is marked as present. Writing.");
153 // w.write_all(&stringdata::to_data(
154 // lnk.working_dir.as_ref().unwrap(),
155 // link_flags,
156 // ))?;
157 // }
158
159 // if link_flags.contains(LinkFlags::HAS_ARGUMENTS) {
160 // if lnk.icon_location == None {
161 // error!("Arguments not specified but expected!")
162 // }
163 // debug!("Arguments are marked as present. Writing.");
164 // w.write_all(&stringdata::to_data(
165 // lnk.command_line_arguments.as_ref().unwrap(),
166 // link_flags,
167 // ))?;
168 // }
169
170 // if link_flags.contains(LinkFlags::HAS_ICON_LOCATION) {
171 // if lnk.icon_location == None {
172 // error!("Icon Location not specified but expected!")
173 // }
174 // debug!("Icon Location is marked as present. Writing.");
175 // w.write_all(&stringdata::to_data(
176 // lnk.icon_location.as_ref().unwrap(),
177 // link_flags,
178 // ))?;
179 // }
180
181 Ok(buffer)
182}
183
184/// Open and parse a shell link
185///
186/// All string which are stored in the `lnk` file are encoded with either
187/// Unicode (UTF-16LE) of any of the Windows code pages. Which of both is
188/// being used is specified by the [`LinkFlags::IS_UNICODE`] flag. Microsoft
189/// documents this as follows:
190///
191/// > If this bit is set, the StringData section contains Unicode-encoded
192/// > strings; otherwise, it contains strings that are encoded using the
193/// > system default code page.
194/// >
195/// > (<https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-shllink/ae350202-3ba9-4790-9e9e-98935f4ee5af>)
196///
197/// The system default code page is stored in
198/// `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage\ACP`
199///
200/// Because we do not know what the system default code page was, you must
201/// specify this using the `encoding` parameter (see below). If you you do
202/// not know the system default code page either, you're lost. There is no
203/// way to correctly guess the used code page from the data in the `lnk`
204/// file.
205///
206/// * `path` - path of the `lnk` file to be analyzed
207/// * `encoding` - character encoding to be used if the `lnk` file is not
208/// Unicode encoded
209pub fn read_path_from_lnk<P: AsRef<Path>>(
210 lnk_path: P,
211 encoding: lnk::Encoding,
212) -> Result<path::PathBuf> {
213 let bytes = std::fs::read(lnk_path.as_ref()).with_context(|| {
214 format!("Failed to read lnk file {}", lnk_path.as_ref().display())
215 })?;
216 read_path_from_lnk_bytes(&bytes, encoding)
217}
218
219pub fn read_path_from_lnk_bytes(
220 bytes: &[u8],
221 encoding: lnk::Encoding,
222) -> Result<PathBuf> {
223 let mut reader = Cursor::new(bytes);
224 let header: ShellLinkHeader =
225 reader.read_le().context("Failed to parse LNK header")?;
226 let link_flags = *header.link_flags();
227
228 if link_flags.contains(LinkFlags::HAS_LINK_TARGET_ID_LIST) {
229 let _: LinkTargetIdList = reader
230 .read_le()
231 .context("Failed to parse LinkTargetIdList")?;
232 }
233
234 let link_info = if link_flags.contains(LinkFlags::HAS_LINK_INFO) {
235 Some(
236 reader
237 .read_le_args((encoding,))
238 .context("Failed to parse LinkInfo")?,
239 )
240 } else {
241 None
242 };
243
244 let string_data: StringData = reader
245 .read_le_args((link_flags, encoding))
246 .context("Failed to parse StringData")?;
247
248 if let Some(info) = link_info.as_ref() {
249 return build_path_from_link_info(info);
250 }
251
252 build_path_from_string_data(&string_data)
253}
254
255fn build_path_from_link_info(info: &LinkInfo) -> Result<PathBuf> {
256 let mut base_path = if info
257 .link_info_flags()
258 .has_common_network_relative_link_and_path_suffix()
259 {
260 let common = info
261 .common_network_relative_link()
262 .as_ref()
263 .context("Missing CommonNetworkRelativeLink in LinkInfo")?;
264 std::panic::catch_unwind(|| common.name()).map_err(|panic_payload| {
265 // Reason for fallback: default description used when catch_unwind panic payload is not a str or String.
266 let payload_msg = panic_payload
267 .downcast_ref::<&str>()
268 .map(|s| (*s).to_string())
269 .or_else(|| panic_payload.downcast_ref::<String>().cloned())
270 .unwrap_or_else(|| "non-string panic payload".to_string());
271 anyhow!(
272 "Failed to read CommonNetworkRelativeLink name: {payload_msg}"
273 )
274 })?
275 } else {
276 let base_path = if let Some(local_base_path_unicode) =
277 info.local_base_path_unicode().as_ref()
278 {
279 local_base_path_unicode.as_str()
280 } else if let Some(local_base_path) = info.local_base_path() {
281 local_base_path
282 } else {
283 bail!("Missing local base path in LinkInfo");
284 };
285
286 base_path.to_string()
287 };
288
289 let common_path = if let Some(common_path_suffix_unicode) =
290 info.common_path_suffix_unicode()
291 {
292 common_path_suffix_unicode.as_str()
293 } else {
294 info.common_path_suffix()
295 };
296
297 if !common_path.is_empty() {
298 if !base_path.ends_with('\\') {
299 base_path.push('\\');
300 }
301 base_path.push_str(common_path);
302 }
303
304 Ok(PathBuf::from(base_path))
305}
306
307fn build_path_from_string_data(string_data: &StringData) -> Result<PathBuf> {
308 let relative_path = string_data
309 .relative_path()
310 .as_ref()
311 .context("Missing RelativePath in StringData")?;
312 // Reason for fallback: if relative path has no './' or '.\\' prefix, original relative path is retained.
313 let relative_path = relative_path
314 .strip_prefix(".\\")
315 .or(relative_path.strip_prefix("./"))
316 .unwrap_or(relative_path);
317
318 if let Some(working_dir) = string_data.working_dir().as_ref() {
319 let mut path = PathBuf::from(working_dir);
320 path.push(relative_path);
321 return Ok(path);
322 }
323
324 Ok(PathBuf::from(relative_path))
325}
326
327#[cfg(test)]
328#[allow(
329 clippy::panic,
330 clippy::expect_used,
331 clippy::unwrap_used,
332 clippy::unwrap_in_result,
333 clippy::panic_in_result_fn,
334 clippy::indexing_slicing,
335 clippy::arithmetic_side_effects,
336 reason = "Standard repository test boilerplate"
337)]
338mod tests {
339 use std::path::PathBuf;
340 use std::sync::atomic::{AtomicU64, Ordering};
341
342 use super::*;
343 use binrw::BinReaderExt;
344
345 static NEXT_TEST_LNK_ID: AtomicU64 = AtomicU64::new(0);
346
347 #[crate::ctb_test]
348 fn test_create_lnk_doesnt_explode() {
349 create_simple_lnk(
350 PathBuf::from(r"C:\Windows\System32\notepad.exe"),
351 Some("Notepad"),
352 )
353 .unwrap();
354 create_simple_lnk(
355 PathBuf::from(r"C:\Windows\System32\notepad.exe"),
356 None,
357 )
358 .unwrap();
359 }
360
361 #[crate::ctb_test]
362 fn test_create_lnk_contains_header_and_string_data() {
363 let bytes = create_simple_lnk(
364 PathBuf::from(r"C:\Windows\System32\notepad.exe"),
365 Some("Notepad"),
366 )
367 .unwrap();
368
369 let mut reader = Cursor::new(&bytes);
370 let header: ShellLinkHeader = reader.read_le().unwrap();
371 let link_flags = *header.link_flags();
372 assert!(link_flags.contains(LinkFlags::HAS_NAME));
373 assert!(link_flags.contains(LinkFlags::HAS_RELATIVE_PATH));
374 assert!(link_flags.contains(LinkFlags::HAS_WORKING_DIR));
375
376 let string_data: StringData = reader
377 .read_le_args((link_flags, encoding::UTF_16LE))
378 .unwrap();
379 assert_eq!(string_data.name_string().as_deref(), Some("Notepad"));
380 }
381
382 #[crate::ctb_test]
383 fn test_read_path_from_lnk_bytes_matches_lnk_rs() {
384 /* FIXME: Maybe flaky - this test crashed once with this message:
385
386 thread 'tests::test_read_path_from_lnk_matches_lnk_rs' (207123) panicked at src/formats/lnk/lnk.rs:364:14:
387 called `Result::unwrap()` on an `Err` value: BinReadError("LinkInfo",
388 ╺━━━━━━━━━━━━━━━━━━━━┅ Backtrace ┅━━━━━━━━━━━━━━━━━━━━╸
389
390 0: Error: failed to fill whole buffer
391 While parsing field 'volume_id_size' in VolumeID
392 at ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/lnk-0.6.4/src/linkinfo.rs:350
393 1: While parsing field 'volume_id' in LinkInfo
394 at ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/lnk-0.6.4/src/linkinfo.rs:205
395
396 */
397 let bytes = test_lnk();
398 let file_path = test_lnk_path();
399
400 let expected = ShellLink::open(&file_path, encoding::WINDOWS_1252)
401 .unwrap()
402 .link_target()
403 .expect("Expected LinkInfo-based target path");
404 let actual =
405 read_path_from_lnk_bytes(&bytes, encoding::WINDOWS_1252).unwrap();
406
407 assert_eq!(actual, PathBuf::from(expected));
408 }
409
410 #[crate::ctb_test]
411 fn test_read_path_from_lnk_matches_lnk_rs() {
412 /* FIXME: Maybe flaky - this test crashed once with this message:
413
414 [2026-06-08T05:20:56.742761Z TRACE ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/lnk-0.6.4/src/lib.rs:330 log workspace:1156279/workspace] test_read_path_from_lnk_bytes_matches_lnk_rs: Reading file.
415
416 thread 'tests::test_read_path_from_lnk_bytes_matches_lnk_rs' (1156282) panicked at src/formats/lnk/lnk.rs:364:14:
417 called `Result::unwrap()` on an `Err` value: BinReadError("ShellLinkHeader",
418 ╺━━━━━━━━━━━━━━━━━━━━┅ Backtrace ┅━━━━━━━━━━━━━━━━━━━━╸
419
420 0: Error: failed to fill whole buffer
421 While parsing field 'header_size' in ShellLinkHeader
422 at ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/lnk-0.6.4/src/header.rs:32
423
424
425 */
426 let lnk_path = test_lnk_path();
427 let expected = ShellLink::open(&lnk_path, encoding::WINDOWS_1252)
428 .unwrap()
429 .link_target()
430 .expect("Expected LinkInfo-based target path");
431
432 let actual =
433 read_path_from_lnk(&lnk_path, encoding::WINDOWS_1252).unwrap();
434 assert_eq!(actual, PathBuf::from(expected));
435 }
436
437 fn test_lnk() -> Vec<u8> {
438 get_lnk_data("fixtures/test.lnk").expect("Failed to get test lnk data")
439 }
440
441 fn test_lnk_path() -> PathBuf {
442 let lnk = test_lnk();
443 let unique_id = NEXT_TEST_LNK_ID.fetch_add(1, Ordering::Relaxed);
444 let path = std::env::temp_dir().join(format!(
445 "ctoolbox-test-{}-{}.lnk",
446 std::process::id(),
447 unique_id
448 ));
449 std::fs::write(&path, &lnk).expect("Failed to write test lnk file");
450 path
451 }
452}
453
454/*
455
456// From lnk-rs:
457
458MIT License
459
460Copyright (c) 2023 Lily Hopkins
461
462Permission is hereby granted, free of charge, to any person obtaining a copy
463of this software and associated documentation files (the "Software"), to deal
464in the Software without restriction, including without limitation the rights
465to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
466copies of the Software, and to permit persons to whom the Software is
467furnished to do so, subject to the following conditions:
468
469The above copyright notice and this permission notice shall be included in all
470copies or substantial portions of the Software.
471
472THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
473IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
474FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
475AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
476LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
477OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
478SOFTWARE.
479*/