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
#![warn(missing_docs)]

//! # Shell Link parser and writer for Rust.

//! Works on any OS - although only really useful in Windows, this library can parse and write

//! .lnk files, a shell link, that can be understood by Windows.

//!

//! To get started, see the [ShellLink](struct.ShellLink.html) struct.

//!

//! The full specification of these files can be found at

//! [Microsoft's Website](https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-shllink/16cb4ca1-9339-4d0c-a68d-bf1d6cc0f943).

//!

//! ## Example

//! A simple example appears as follows:

//! ```rust

//! use lnk::ShellLink;

//! // ...

//! ShellLink::new_simple(std::path::Path::new(r"C:\Windows\System32\notepad.exe"));

//! ```


use byteorder::{ByteOrder, LE};
#[allow(unused)]
use log::{debug, error, info, trace, warn};

use std::fs::File;
use std::io::{prelude::*, BufReader, BufWriter};
use std::path::Path;
use std::convert::TryFrom;

mod header;
pub use header::{
    FileAttributeFlags, HotkeyFlags, HotkeyKey, HotkeyModifiers, LinkFlags, ShellLinkHeader,
    ShowCommand,
};

mod linktarget;
pub use linktarget::LinkTargetIdList;

mod linkinfo;
pub use linkinfo::LinkInfo;

mod stringdata;

mod extradata;
pub use extradata::ExtraData;

/// The error type for shell link parsing errors.

#[derive(Debug)]
pub enum Error {
    /// An IO error occurred.

    IoError(std::io::Error),
    /// The parsed file isn't a shell link.

    NotAShellLinkError,
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::IoError(e)
    }
}

/// A shell link

#[derive(Clone, Debug)]
pub struct ShellLink {
    shell_link_header: header::ShellLinkHeader,
    linktarget_id_list: Option<linktarget::LinkTargetIdList>,
    link_info: Option<linkinfo::LinkInfo>,
    name_string: Option<String>,
    relative_path: Option<String>,
    working_dir: Option<String>,
    command_line_arguments: Option<String>,
    icon_location: Option<String>,
    extra_data: Vec<extradata::ExtraData>,
}

impl Default for ShellLink {
    /// Create a new ShellLink, left blank for manual configuration.

    /// For those who are not familar with the Shell Link specification, I

    /// suggest you look at the [`new_simple`](#method.new_simple) method.

    fn default() -> Self {
        Self {
            shell_link_header: header::ShellLinkHeader::default(),
            linktarget_id_list: None,
            link_info: None,
            name_string: None,
            relative_path: None,
            working_dir: None,
            command_line_arguments: None,
            icon_location: None,
            extra_data: vec![],
        }
    }
}

impl ShellLink {
    /// Create a new ShellLink pointing to a location, with otherwise default settings.

    pub fn new_simple<P: AsRef<Path>>(to: P) -> std::io::Result<Self> {
        use std::fs;

        let meta = fs::metadata(&to)?;
        let canonical = fs::canonicalize(to)?.into_boxed_path();

        let mut sl = Self::default();

        let mut flags = LinkFlags::IS_UNICODE;
        sl.header_mut().set_link_flags(flags);
        if meta.is_dir() {
            sl.header_mut()
                .set_file_attributes(FileAttributeFlags::FILE_ATTRIBUTE_DIRECTORY);
        } else {
            flags |= LinkFlags::HAS_WORKING_DIR | LinkFlags::HAS_RELATIVE_PATH;
            sl.header_mut().set_link_flags(flags);
            let mut ances = canonical.ancestors();
            sl.set_relative_path(Some(format!(
                "./{}",
                canonical.file_name().unwrap().to_str().unwrap()
            )));
            sl.set_working_dir(Some(ances.next().unwrap().to_str().unwrap().to_string()));
            sl.header_mut().set_file_size(meta.len() as u32);
        }

        Ok(sl)
    }

    /// Save a shell link.

    ///

    /// Note that this doesn't save any [`ExtraData`](struct.ExtraData.html) entries.

    pub fn save<P: AsRef<std::path::Path>>(&self, path: P) -> std::io::Result<()> {
        let mut w = BufWriter::new(File::create(path)?);

        debug!("Writing header...");
        let header_data: [u8; 0x4c] = self.shell_link_header.into();
        w.write_all(&header_data)?;

        let link_flags = *self.header().link_flags();

        if link_flags.contains(LinkFlags::HAS_LINK_TARGET_ID_LIST) {
            if let None = self.linktarget_id_list {
                error!("LinkTargetIDList not specified but expected!")
            }
            debug!("A LinkTargetIDList is marked as present. Writing.");
            let mut data: Vec<u8> = self.linktarget_id_list.clone().unwrap().into();
            w.write_all(&mut data)?;
        }

        if link_flags.contains(LinkFlags::HAS_LINK_INFO) {
            if let None = self.link_info {
                error!("LinkInfo not specified but expected!")
            }
            debug!("LinkInfo is marked as present. Writing.");
            let mut data: Vec<u8> = self.link_info.clone().unwrap().into();
            w.write_all(&mut data)?;
        }

        if link_flags.contains(LinkFlags::HAS_NAME) {
            if self.name_string == None {
                error!("Name not specified but expected!")
            }
            debug!("Name is marked as present. Writing.");
            w.write_all(&stringdata::to_data(
                self.name_string.as_ref().unwrap(),
                link_flags,
            ))?;
        }

        if link_flags.contains(LinkFlags::HAS_RELATIVE_PATH) {
            if self.relative_path == None {
                error!("Relative path not specified but expected!")
            }
            debug!("Relative path is marked as present. Writing.");
            w.write_all(&stringdata::to_data(
                self.relative_path.as_ref().unwrap(),
                link_flags,
            ))?;
        }

        if link_flags.contains(LinkFlags::HAS_WORKING_DIR) {
            if self.working_dir == None {
                error!("Working Directory not specified but expected!")
            }
            debug!("Working dir is marked as present. Writing.");
            w.write_all(&stringdata::to_data(
                self.working_dir.as_ref().unwrap(),
                link_flags,
            ))?;
        }

        if link_flags.contains(LinkFlags::HAS_ARGUMENTS) {
            if self.icon_location == None {
                error!("Arguments not specified but expected!")
            }
            debug!("Arguments are marked as present. Writing.");
            w.write_all(&stringdata::to_data(
                self.command_line_arguments.as_ref().unwrap(),
                link_flags,
            ))?;
        }

        if link_flags.contains(LinkFlags::HAS_ICON_LOCATION) {
            if self.icon_location == None {
                error!("Icon Location not specified but expected!")
            }
            debug!("Icon Location is marked as present. Writing.");
            w.write_all(&stringdata::to_data(
                self.icon_location.as_ref().unwrap(),
                link_flags,
            ))?;
        }

        Ok(())
    }

    /// Open and parse a shell link

    pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Self, Error> {
        debug!("Opening {:?}", path.as_ref());
        let mut r = BufReader::new(File::open(path)?);
        let mut data = vec![];
        trace!("Reading file.");
        r.read_to_end(&mut data)?;

        trace!("Parsing shell header.");
        if data.len() < 0x4c {
            return Err(Error::NotAShellLinkError);
        }
        let shell_link_header = header::ShellLinkHeader::try_from(&data[0..0x4c])?;
        debug!("Shell header: {:#?}", shell_link_header);

        let mut cursor = 0x4c;

        let mut linktarget_id_list = None;
        let link_flags = *shell_link_header.link_flags();
        if link_flags.contains(LinkFlags::HAS_LINK_TARGET_ID_LIST) {
            debug!("A LinkTargetIDList is marked as present. Parsing now.");
            debug!("Cursor position: 0x{:x}", cursor);
            let list = linktarget::LinkTargetIdList::from(&data[cursor..]);
            debug!("{:?}", list);
            cursor += list.size as usize + 2; // add LinkTargetSize size

            linktarget_id_list = Some(list);
        }

        let mut link_info = None;
        if link_flags.contains(LinkFlags::HAS_LINK_INFO) {
            debug!("LinkInfo is marked as present. Parsing now.");
            debug!("Cursor position: 0x{:x}", cursor);
            let info = linkinfo::LinkInfo::from(&data[cursor..]);
            debug!("{:?}", info);
            cursor += info.size as usize;
            link_info = Some(info);
        }

        let mut name_string = None;
        let mut relative_path = None;
        let mut working_dir = None;
        let mut command_line_arguments = None;
        let mut icon_location = None;

        if link_flags.contains(LinkFlags::HAS_NAME) {
            debug!("Name is marked as present. Parsing now.");
            debug!("Cursor position: 0x{:x}", cursor);
            let (len, data) = stringdata::parse_string(&data[cursor..], link_flags);
            name_string = Some(data);
            cursor += len; // add len bytes

        }

        if link_flags.contains(LinkFlags::HAS_RELATIVE_PATH) {
            debug!("Relative path is marked as present. Parsing now.");
            debug!("Cursor position: 0x{:x}", cursor);
            let (len, data) = stringdata::parse_string(&data[cursor..], link_flags);
            relative_path = Some(data);
            cursor += len; // add len bytes

        }

        if link_flags.contains(LinkFlags::HAS_WORKING_DIR) {
            debug!("Working dir is marked as present. Parsing now.");
            debug!("Cursor position: 0x{:x}", cursor);
            let (len, data) = stringdata::parse_string(&data[cursor..], link_flags);
            working_dir = Some(data);
            cursor += len; // add len bytes

        }

        if link_flags.contains(LinkFlags::HAS_ARGUMENTS) {
            debug!("Arguments are marked as present. Parsing now.");
            debug!("Cursor position: 0x{:x}", cursor);
            let (len, data) = stringdata::parse_string(&data[cursor..], link_flags);
            command_line_arguments = Some(data);
            cursor += len; // add len bytes

        }

        if link_flags.contains(LinkFlags::HAS_ICON_LOCATION) {
            debug!("Icon Location is marked as present. Parsing now.");
            debug!("Cursor position: 0x{:x}", cursor);
            let (len, data) = stringdata::parse_string(&data[cursor..], link_flags);
            icon_location = Some(data);
            cursor += len; // add len bytes

        }

        let mut extra_data = Vec::new();

        loop {
            if data[cursor..].len() < 4 {
                warn!("The ExtraData length is invalid.");
                break; // Probably an error?

            }
            debug!("Parsing ExtraData");
            debug!("Cursor position: 0x{:x}", cursor);
            let query = LE::read_u32(&data[cursor..]);
            if query < 0x04 {
                break;
            }
            extra_data.push(extradata::ExtraData::from(&data[cursor..]));
            cursor += query as usize;
        }

        let _remaining_data = &data[cursor..];

        Ok(Self {
            shell_link_header,
            linktarget_id_list,
            link_info,
            name_string,
            relative_path,
            working_dir,
            command_line_arguments,
            icon_location,
            extra_data,
        })
    }

    /// Get the header of the shell link

    pub fn header(&self) -> &ShellLinkHeader {
        &self.shell_link_header
    }

    /// Get a mutable instance of the shell link's header

    pub fn header_mut(&mut self) -> &mut ShellLinkHeader {
        &mut self.shell_link_header
    }

    /// Get the shell link's name, if set

    pub fn name(&self) -> &Option<String> {
        &self.name_string
    }

    /// Set the shell link's name

    pub fn set_name(&mut self, name: Option<String>) {
        self.header_mut()
            .update_link_flags(LinkFlags::HAS_NAME, name.is_some());
        self.name_string = name;
    }

    /// Get the shell link's relative path, if set

    pub fn relative_path(&self) -> &Option<String> {
        &self.relative_path
    }

    /// Set the shell link's relative path

    pub fn set_relative_path(&mut self, relative_path: Option<String>) {
        self.header_mut()
            .update_link_flags(LinkFlags::HAS_RELATIVE_PATH, relative_path.is_some());
        self.relative_path = relative_path;
    }

    /// Get the shell link's working directory, if set

    pub fn working_dir(&self) -> &Option<String> {
        &self.working_dir
    }

    /// Set the shell link's working directory

    pub fn set_working_dir(&mut self, working_dir: Option<String>) {
        self.header_mut()
            .update_link_flags(LinkFlags::HAS_WORKING_DIR, working_dir.is_some());
        self.working_dir = working_dir;
    }

    /// Get the shell link's arguments, if set

    pub fn arguments(&self) -> &Option<String> {
        &self.command_line_arguments
    }

    /// Set the shell link's arguments

    pub fn set_arguments(&mut self, arguments: Option<String>) {
        self.header_mut()
            .update_link_flags(LinkFlags::HAS_ARGUMENTS, arguments.is_some());
        self.command_line_arguments = arguments;
    }

    /// Get the shell link's icon location, if set

    pub fn icon_location(&self) -> &Option<String> {
        &self.icon_location
    }

    /// Set the shell link's icon location

    pub fn set_icon_location(&mut self, icon_location: Option<String>) {
        self.header_mut()
            .update_link_flags(LinkFlags::HAS_ICON_LOCATION, icon_location.is_some());
        self.icon_location = icon_location;
    }
}