hpkg 0.0.3

A native Rust crate to parse Haiku's binary package and repo formats
Documentation
/*
 * Copyright, 2017-2020, Alexander von Gluck IV. All rights reserved.
 * Released under the terms of the MIT license.
 *
 * vim: set noai noet ts=4 sw=4:
 *
 * Authors:
 *   Alexander von Gluck IV <kallisti5@unixzen.com>
 */

use std::fmt;
use std::path::Path;
use std::fs::File;
use std::io;
use std::io::{Read,Seek,SeekFrom,BufReader};
use std::error;
use std::slice;

// heap_compression
pub const B_HPKG_COMPRESSION_NONE: u16 = 0;
pub const B_HPKG_COMPRESSION_ZLIB: u16 = 1;
pub const B_HPKG_COMPRESSION_ZSTD: u16 = 2;

#[derive(Debug, Clone)]
#[repr(C)]
pub struct RepositoryHeaderV2 {
	pub magic: u32,				// HPKR
	pub header_size: u16,		// Header size, absolute offset of heap
	pub version: u16,			// Version (current is 2)
	pub total_size: u64,		// Total file size
	pub minor_version: u16,		// Minor Version (current is 0)

	// Heap
	pub heap_compression: u16,	// 0 uncompressed, 1 ZLIB, 2 ZSTD (not used)
	pub heap_chunk_size: u32,
	pub heap_size_compressed: u64, 
	pub heap_size_uncompressed: u64,

	// Repository info section
	pub info_length: u32,
	pub reserved1: u32,

	// Package attributes section
	pub package_length: u64,
	pub package_strings_length: u64,
	pub package_strings_count: u64,
}


#[derive(Debug, Clone)]
pub struct Repository {
	pub header: Option<RepositoryHeaderV2>,

	pub name: Option<String>,
	pub url: Option<String>,
	pub base_url: Option<String>,
	pub vendor: Option<String>,
	pub summary: Option<String>,
	pub priority: Option<i32>,
	pub architecture: Option<String>,
	pub license_name: Option<String>,
	pub license_text: Option<String>,
}

fn read_struct<T, R: Read>(mut read: R) -> io::Result<T> {
	let num_bytes = ::std::mem::size_of::<T>();
	unsafe {
		let mut s = ::std::mem::zeroed();
		let buffer = slice::from_raw_parts_mut(&mut s as *mut T as *mut u8, num_bytes);
		match read.read_exact(buffer) {
			Ok(()) => Ok(s),
			Err(e) => {
				Err(e)
			}
		}
	}
}

fn parse_header<P: AsRef<Path>>(repo_file: P)
	-> Result<RepositoryHeaderV2, Box<dyn error::Error>> {

	let mut f = File::open(repo_file.as_ref())?;
	f.seek(SeekFrom::Start(0))?;
	let reader = BufReader::new(f);

	let mut header = read_struct::<RepositoryHeaderV2, _>(reader)?;
	let magic_bytes = header.magic.to_ne_bytes();
	if magic_bytes != [b'h', b'p', b'k', b'r'] {
		return Err(From::from(format!("Unknown magic: {:?}", magic_bytes)));
	}

	// Endian Adjustments (are there better ways to do this?)
	header.header_size = u16::from_be(header.header_size);
	header.version = u16::from_be(header.version);
	header.total_size = u64::from_be(header.total_size);
	header.minor_version = u16::from_be(header.minor_version);
	header.heap_compression = u16::from_be(header.heap_compression);
	header.heap_chunk_size = u32::from_be(header.heap_chunk_size);
	header.heap_size_compressed = u64::from_be(header.heap_size_compressed);
	header.heap_size_uncompressed = u64::from_be(header.heap_size_uncompressed);
	header.info_length = u32::from_be(header.info_length);
	header.reserved1 = u32::from_be(header.reserved1);
	header.package_length = u64::from_be(header.package_length);
	header.package_strings_length = u64::from_be(header.package_strings_length);
	header.package_strings_count = u64::from_be(header.package_strings_count);

	// We don't really care about v1 since it saw such minor rollout
	if header.version != 2 {
		return Err(From::from(format!("Unknown repo version: {}", header.version)));
	}

	// If the minor version of a package/repository file is greater than the
	// current one unknown attributes are ignored without error.

	Ok(header)
}

impl fmt::Display for Repository {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		write!(f, "repository. Name {:?}, Url(virtual) {:?}, Vendor {:?}, Summary {:?}, Arch {:?}",
			self.name, self.url, self.vendor, self.summary, self.architecture)
	}
}

impl Repository {
	pub fn new() -> Repository {
		Repository {
			header: None,
			name: None,
			url: None,
			base_url: None,
			vendor: None,
			summary: None,
			priority: None,
			architecture: None,
			license_name: None,
			license_text: None,
		}
	}

	pub fn load<P: AsRef<Path>>(repo_file: P)
		-> Result<Repository, Box<dyn error::Error>> {

		let mut f = File::open(repo_file.as_ref())?;
		f.seek(SeekFrom::Start(0))?;

		let mut repo = Repository::new();
		repo.header = Some(self::parse_header(repo_file)?);

		//f.seek(SeekFrom::Start(

		return Ok(repo);
	}
}


#[test]
/// Test creating a new empty repository definition
fn test_new_repository() {
	let _repo = Repository::new();
}

#[test]
/// Test loading a valid repository from disk
fn test_load_valid_repository() {
	let repo = match Repository::load("sample/repo") {
		Ok(o) => o,
		Err(e) => {
			println!("ERROR: {}", e);
			assert!(false);
			return;
		},
	};
	assert!(repo.header.is_some());
}

#[test]
/// Test loading an invalid repository from disk
fn test_load_invalid_repository() {
	assert!(Repository::load("sample/not-repo").is_err());
}

#[test]
/// Test total size compared to header
fn test_total_size() {
	let metadata = match std::fs::metadata("sample/repo") {
		Ok(o) => o,
		Err(e) => {
			println!("ERROR: {}", e);
			assert!(false);
			return;
		},
	};
	let hpkr = match Repository::load("sample/repo") {
		Ok(o) => o,
		Err(e) => {
			println!("ERROR: {}", e);
			assert!(false);
			return;
		},
	};
	let header = match hpkr.header {
		Some(o) => o,
		None => {
			println!("ERROR: Invalid Header!");
			assert!(false);
			return;
		},
	};
	assert_eq!(metadata.len(), header.total_size);
}


#[test]
/// Dump repository info
fn test_dump_repository_info() {
	let repo = match Repository::load("sample/repo") {
		Ok(o) => o,
		Err(e) => {
			println!("ERROR: {}", e);
			assert!(false);
			return;
		},
	};
	println!("{:?}", repo);
}