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
// @Author: Lashermes Ronan <ronan>
// @Date:   04-07-2017
// @Email:  ronan.lashermes@inria.fr
// @Last modified by:   ronan
// @Last modified time: 25-07-2017
// @License: MIT

use packer::{PackFile, AppData, ManifestParameters, ManifestNode, PackParameters};
use packer::packer_functions::{action_builder, ActionContext, ActionType};

use tempdir::TempDir;
use rand;
use rand::Rng;
use rayon::prelude::*;
use serde_json;
use tar::{Builder, Header, Archive};
use xz2;
use fs_extra::dir::{copy, CopyOptions, create_all};
use base64::{encode};
use ring::hmac::VerificationKey;
use app_dirs::*;
use file_fetcher;


use std::fs::File;
use std::fs;
use std::path::{Path, PathBuf};
use std::collections::HashMap;
use std::io::Read;

use key_mgr::{KeyFile};
use key_mgr::hmac_helpers::{derive_hmac_verification_key, hmac_verify_file};
use helpers::{store_data_in_file, read_data_from_file};
use errors::*;

const MANIFEST_FILENAME: &str = "manifest.json";
const MANIFEST_SIG_FILENAME: &str = "manifest.json.sig";
const UNPACK_FILES_FILENAME: &str = "unpack_files.tar";
const UNINSTALL: &str = "uninstall";
const UNINSTALL_FILES_FILENAME: &str = "uninstall_files.tar";

const TEMP_FILE_LEN: usize = 20;

pub struct Packer {
    files: Vec<PackFile>
}

impl Packer {
    pub fn from_files(pack_files: Vec<PackFile>) -> Packer {
        Packer { files: pack_files }
    }

    ///Uninstall an application from its name
    pub fn uninstall(app_name: &str, keep_user_data: bool) -> Result<()> {
        //find uninstall info
        let app_info = OwnedAppInfo { name: app_name.to_string(), author: String::from("maj") };
        let mut archive_path = get_app_root(AppDataType::SharedConfig, &app_info)
                                .or(get_app_root(AppDataType::UserConfig, &app_info))?;
        archive_path.push(UNINSTALL);
        archive_path.push(UNINSTALL_FILES_FILENAME);

        //if no uninstall info -> error
        if archive_path.exists() == false {
            return Err(format!("No uninstallation data at {}, maybe another user or sudo is required?", archive_path.display()).into());
        }

        //load uninstall files
        let uninstall_files = Packer::load_pack_files(&archive_path)?;

        //temp dir may be necessary in the future
        if let Ok(dir) = TempDir::new("maj") {
            let tmp_dir_path = dir.path().to_path_buf();

            let root_path = fs::canonicalize("./")?;
            //execute uninstall operations
            let _ = Packer::execute_actions(
                &ActionContext::new(ActionType::Uninstall, &app_info, &root_path, keep_user_data),
                &tmp_dir_path, &uninstall_files);

            //delete temp dir here
            // dir.close().map_err(|e|e.to_string())?;
        }

        Packer::clean_app_dirs(&app_info, keep_user_data);

        Ok(())
    }

    //delete all or non-user app_dirs
    fn clean_app_dirs(app_info: &OwnedAppInfo, keep_user_data: bool) {
        let shared_dirs = vec![
                            get_app_root(AppDataType::SharedConfig, app_info),
                            get_app_root(AppDataType::SharedData, app_info)
                            ];

        let user_dirs = vec![
                            get_app_root(AppDataType::UserCache, app_info),
                            get_app_root(AppDataType::UserConfig, app_info),
                            get_app_root(AppDataType::UserData, app_info),
                            ];

        for dir_res in shared_dirs {
            if let Ok(dir) = dir_res {
                let _ = fs::remove_dir_all(dir);//silent fail, dir may not exist
            }

        }

        if keep_user_data == false {
            for dir_res in user_dirs {
                if let Ok(dir) = dir_res {
                    let _ = fs::remove_dir_all(dir);//silent fail, dir may not exist
                }

            }
        }
    }

    pub fn install_remote_package(url: &str, public_key_bytes: &[u8], keep_user_data: bool) -> Result<()> {
        let reader = file_fetcher::open_str(url)?;
        Packer::install(reader, public_key_bytes, keep_user_data)
    }

    pub fn install_local_package<T: AsRef<Path>>(package_file_path: T, public_key_bytes: &[u8], keep_user_data: bool) -> Result<()> {
        let file = File::open(package_file_path)?;
        Packer::install(file, public_key_bytes, keep_user_data)
    }

    ///Unpack a package given as a reader.
    pub fn install<T: Read>(package_file_reader: T, public_key_bytes: &[u8], keep_user_data: bool) -> Result<()> {
        if let Ok(dir) = TempDir::new("maj") {
            let tmp_dir_path = dir.path().to_path_buf();


            //open package and fill tmp_dir
            Packer::open_package(package_file_reader, &tmp_dir_path)?;

            //load signature
            let mut signature_path = tmp_dir_path.clone();
            signature_path.push(MANIFEST_SIG_FILENAME);
            let manifest_signature = read_data_from_file(signature_path)?;

            //get manifest path
            let mut manifest_path = tmp_dir_path.clone();
            manifest_path.push(MANIFEST_FILENAME);

            //check manifest signature
            if KeyFile::pk_verify_file(public_key_bytes, &manifest_path, &manifest_signature)? == false {
                return Err("Manifest file is not authentic! Aborting.".into());
            }
            else {
                info!("Manifest signature successfully verified.");
            }

            //open manifest
            let manifest = ManifestNode::open_from_file(&manifest_path)?;
            debug!("Manifest opened.");
            let hmac_key = derive_hmac_verification_key(
                &manifest.get_hmac_key().ok_or("No hmac key in the manifest.")?
            );
            let hmac_hashmap = manifest.get_hmac_hashmap()?;
            let app_data = manifest.get_app_data()?;

            //validate hmacs
            Packer::validate_file_hmacs(&tmp_dir_path, &hmac_hashmap, &hmac_key)?;

            //get unpack files (describing actions to perform)
            let mut archive_path = tmp_dir_path.to_path_buf();
            archive_path.push(UNPACK_FILES_FILENAME);
            let unpack_files = Packer::load_pack_files(&archive_path)?;

            //execute unpacking actions with source files in tmp_dir
            //and save corresponding uninstalling actions
            let mut app_info = app_data.to_owned_app_info();
            app_info.author = String::from("maj");
            let root_path = fs::canonicalize("./")?;
            let uninstall_file_results = Packer::execute_actions(
                &ActionContext::new(ActionType::Unpack, &app_info, &root_path, keep_user_data),
                &tmp_dir_path, &unpack_files);

            //save uninstall instructions in dedicated location
            let mut archive_path = get_app_root(AppDataType::SharedConfig, &app_info)
                                    .or(get_app_root(AppDataType::UserConfig, &app_info))?;
            archive_path.push(UNINSTALL);
            archive_path.push(UNINSTALL_FILES_FILENAME);
            Packer::save_pack_files(&archive_path, uninstall_file_results)?;

            //delete temp dir here
            // dir.close().map_err(|e|e.to_string())?;
        }
        Ok(())
    }



    pub fn get_remote_appdata(url: &str, public_key_bytes: &[u8]) -> Result<AppData> {
        let reader = file_fetcher::open_str(url)?;
        Packer::get_appdata(reader, public_key_bytes)
    }

    pub fn get_local_appdata<T: AsRef<Path>>(package_file_path: T, public_key_bytes: &[u8]) -> Result<AppData> {
        let file = File::open(package_file_path)?;
        Packer::get_appdata(file, public_key_bytes)
    }

    pub fn get_appdata<T: Read>(package_file_reader: T, public_key_bytes: &[u8]) -> Result<AppData> {
        if let Ok(dir) = TempDir::new("maj") {
            let tmp_dir_path = dir.path().to_path_buf();


            //open package and fill tmp_dir
            Packer::open_package(package_file_reader, &tmp_dir_path)?;

            //load signature
            let mut signature_path = tmp_dir_path.clone();
            signature_path.push(MANIFEST_SIG_FILENAME);
            let manifest_signature = read_data_from_file(signature_path)?;

            //get manifest path
            let mut manifest_path = tmp_dir_path.clone();
            manifest_path.push(MANIFEST_FILENAME);

            //check manifest signature
            if KeyFile::pk_verify_file(public_key_bytes, &manifest_path, &manifest_signature)? == false {
                return Err("Manifest file is not authentic! Aborting.".into());
            }
            else {
                info!("Manifest signature successfully verified.");
            }

            //open manifest
            let manifest = ManifestNode::open_from_file(&manifest_path)?;
            debug!("Manifest opened.");
            let app_data = manifest.get_app_data()?;

            //delete temp dir here
            // dir.close().map_err(|e|e.to_string())?;

            Ok(app_data)
        }
        else {
            Err("Cannot open package.".into())
        }
    }

    pub fn create_package(&mut self, pack_params: &PackParameters, key_file: KeyFile) -> Result<()> {
        if let Ok(dir) = TempDir::new("maj") {
            let tmp_dir_path = dir.path().to_path_buf();
            let app_info = pack_params.get_app_data().to_owned_app_info();
            let root_path = pack_params.get_root_path().to_path_buf();

            //execute packing actions with resulting files in tmp_dir
            //and save corresponding unpacking actions in unpack files
            let unpack_file_results = Packer::execute_actions(
                &ActionContext::new(ActionType::Pack, &app_info, &root_path, false),//keep user data has no meaning at pack
                &tmp_dir_path,
                &self.files);

            //save all unpack files in tmp_dir
            let mut archive_path = tmp_dir_path.clone();
            archive_path.push(UNPACK_FILES_FILENAME);
            Packer::save_pack_files(&archive_path, unpack_file_results)?;

            //get manifest parameters
            let manifest_params = ManifestParameters::new(key_file.clone(),
                                                tmp_dir_path.clone(),
                                                pack_params.get_app_data().clone());
            //generate manifest
            let manifest = ManifestNode::create_package_manifest(&manifest_params)?;

            //save manifest
            let mut manifest_path = tmp_dir_path.clone();
            manifest_path.push(MANIFEST_FILENAME);
            manifest.save_to_file(&manifest_path)?;

            //security operation: sign manifest
            let manifest_sig = key_file.pk_sign_file(&manifest_path)?;
            let mut signature_path = tmp_dir_path.clone();
            signature_path.push(format!("{}.sig", MANIFEST_FILENAME));
            store_data_in_file(&manifest_sig, &signature_path)?;

            //save package as a file, compress with xz-5
            let _ = Packer::save_package(   &tmp_dir_path,
                                    pack_params.get_package_output_path(),
                                    pack_params.get_app_data())?;

            //optionnally save the whole dir (to allow for file picking in the future)
            if pack_params.get_keep_dir() {
                Packer::save_package_dir(   &tmp_dir_path,
                                            pack_params.get_package_output_path(),
                                            pack_params.get_app_data())?;
            }

            //delete temp dir here
            // dir.close().map_err(|e|e.to_string())?;
        }
        Ok(())
    }

    fn validate_file_hmacs(tmp_dir_path: &Path, hmac_hashmap: &HashMap<String, Vec<u8>>, hmac_key: &VerificationKey) -> Result<()> {
        //check all files against hmac values in manifest
        for file_path_res in fs::read_dir(tmp_dir_path)? {
            if let Ok(file_path) = file_path_res {
                if let Some(filename) = file_path.file_name().to_str() {
                    if filename != MANIFEST_FILENAME && filename != MANIFEST_SIG_FILENAME {
                        let signature = hmac_hashmap.get(filename).ok_or(format!("No signature in manifest for {}", filename))?;
                        if hmac_verify_file(hmac_key, &file_path.path(), signature)? == false {
                            return Err(format!("{} has an incorrect signature ({}). File as been tempered with!",
                            filename,
                            encode(&signature)).into());
                        }
                        else {
                            info!("{} integrity has been successfully verified.", filename);
                        }
                    }
                }
                else {
                    return Err(format!("{:?} cannot be read.", file_path).into());
                }
            }
            else {
                return Err("Error while reading files in package.".into());
            }
        }

        Ok(())
    }

    fn save_package_dir(tmp_dir_path: &Path, output_path: &Path, app_data: &AppData) -> Result<()> {
        let mut output_pathbuf = output_path.to_path_buf();
        let output_dir = output_pathbuf.clone();
        output_pathbuf.push(format!("{}.{}.package", app_data.get_app_name(), app_data.get_version()));

        let mut copy_options = CopyOptions::new();
        copy_options.overwrite = true;
        create_all(&output_pathbuf, true)?;
        copy(tmp_dir_path, &output_dir, &copy_options)?;

        Ok(())
    }

    fn save_package(tmp_dir_path: &Path, output_path: &Path, app_data: &AppData) -> Result<PathBuf> {
        //save package, compress with xz-5
        let mut output_pathbuf = output_path.to_path_buf();
        output_pathbuf.push(format!("{}.{}.package.tar.xz", app_data.get_app_name(), app_data.get_version()));
        let package_file = File::create(&output_pathbuf)?;
        let encoder = xz2::write::XzEncoder::new(package_file, 5);
        let mut package_archive = Builder::new(encoder);
        package_archive.append_dir_all(/*app_data.get_app_name()*/"", tmp_dir_path)?;
        package_archive.finish()?;
        Ok(output_pathbuf)
    }

    fn open_package<T: Read>(package_file_reader: T, tmp_dir_path: &Path) -> Result<()> {
        let decoder = xz2::read::XzDecoder::new(package_file_reader);
        let mut ar = Archive::new(decoder);
        ar.unpack(tmp_dir_path)?;
        Ok(())
    }

    fn execute_actions(ctx: &ActionContext, tmp_dir_path: &Path, pack_files: &Vec<PackFile>) -> Vec<Result<PackFile>> {
        //for each pack file (containing instructions for packing...)
        //execute pack action and save corresponding unpack action
        pack_files.par_iter().map(|file| -> Result<PackFile> {
            let mut unpack_file = PackFile::new();
            //for each action in this pack file
            for action in file.get_actions().iter() {

                //instantiate the action
                let pf = action_builder(action)?;
                //execute it
                let unpack_action = pf.exec(ctx, tmp_dir_path)?;
                //save the corresponding unpack action
                unpack_file.add_actions(unpack_action);
            }
            Ok(unpack_file)
        }).collect()
    }

    fn load_pack_files(archive_path: &Path) -> Result<Vec<PackFile>> {
        //load pack files archive
        let archive_file = File::open(archive_path)?;
        let mut archive = Archive::new(&archive_file);
        let mut pack_files: Vec<PackFile> = Vec::new();
        for pack_file_res in archive.entries().map_err(|_|"Cannot list files in unpack archive.")? {
            if let Ok(pack_file) = pack_file_res {
                let pack_deser: PackFile = serde_json::from_reader(pack_file)?;
                pack_files.push(pack_deser);
            }
        }

        Ok(pack_files)
    }

    fn save_pack_files(archive_path: &Path, pack_file_results: Vec<Result<PackFile>>) -> Result<()> {

        //save all unpack files
        //create archive where to put the unpack files
        let parent_dir = archive_path.parent().ok_or("Cannot find dir to save pack files")?;
        fs::create_dir_all(&parent_dir).map_err(|e|format!("Cannot create dir for pack files: {}", e.to_string()))?;
        let archive_file = File::create(archive_path)
                .map_err(|e|format!("Cannot create {}: {}", archive_path.display(), e.to_string()))?;
        let mut archive = Builder::new(&archive_file);
        //if we got an error, we quit
        for res in pack_file_results {
            let unpack_file = res?;
            let serialized = serde_json::to_string(&unpack_file)?;
            let ser_len = serialized.len();//byte len

            //gen random name for unpack file
            let temp_file_handle: String = rand::thread_rng().gen_ascii_chars().take(TEMP_FILE_LEN).collect();
            //gen header for this file
            let mut header = Header::new_gnu();
            header.set_path(&temp_file_handle)?;
            header.set_size(ser_len as u64);
            header.set_cksum();

            //add unpack file to archive
            archive.append(&mut header, serialized.as_bytes())?;
        }
        archive.finish()?;

        Ok(())
    }
}