summaryrefslogtreecommitdiffstats
path: root/src/package/source.rs
blob: a9ee08358481c64693a55e54f0152636d2cc4e17 (plain)
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
//
// Copyright (c) 2020-2021 science+computing ag and other contributors
//
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//

use anyhow::anyhow;
use anyhow::Context;
use anyhow::Result;
use getset::Getters;
use log::trace;
use serde::Deserialize;
use serde::Serialize;
use url::Url;

#[derive(Clone, Debug, Serialize, Deserialize, Getters)]
pub struct Source {
    #[getset(get = "pub")]
    url: Url,
    #[getset(get = "pub")]
    hash: SourceHash,
    #[getset(get = "pub")]
    download_manually: bool,
}

impl Source {
    #[cfg(test)]
    pub fn new(url: Url, hash: SourceHash) -> Self {
        Source {
            url,
            hash,
            download_manually: false,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, Getters)]
pub struct SourceHash {
    #[serde(rename = "type")]
    #[getset(get = "pub")]
    hashtype: HashType,

    #[serde(rename = "hash")]
    #[getset(get = "pub")]
    value: HashValue,
}

impl SourceHash {
    pub async fn matches_hash_of<R: tokio::io::AsyncRead + Unpin>(&self, reader: R) -> Result<()> {
        trace!("Hashing buffer with: {:?}", self.hashtype);
        let h = self.hashtype
            .hash_from_reader(reader)
            .await
            .context("Hashing failed")?;
        trace!("Hashing buffer with: {} finished", self.hashtype);

        if h == self.value {
            trace!("Hash matches expected hash");
            Ok(())
        } else {
            trace!("Hash mismatch expected hash");
            Err(anyhow!(
                "Hash mismatch, expected '{}', got '{}'",
                self.value,
                h
            ))
        }
    }

    #[cfg(test)]
    pub fn new(hashtype: HashType, value: HashValue) -> Self {
        SourceHash { hashtype, value }
    }
}

#[derive(parse_display::Display, Clone, Debug, Serialize, Deserialize)]
pub enum HashType {
    #[serde(rename = "sha1")]
    #[display("sha1")]
    Sha1,

    #[serde(rename = "sha256")]
    #[display("sha256")]
    Sha256,

    #[serde(rename = "sha512")]
    #[display("sha512")]
    Sha512,
}

impl HashType {
    async fn hash_from_reader<R: tokio::io::AsyncRead + Unpin>(&self, mut reader: R) -> Result<HashValue> {
        use tokio::io::AsyncReadExt;

        let mut buffer = [0; 1024];

        match self {
            HashType::Sha1 => {
                use sha1::Digest;

                trace!("SHA1 hashing buffer");
                let mut m = sha1::Sha1::new();
                loop {
                    trace!("Reading");
                    let count = reader.read(&mut buffer)
                        .await
                        .context("Reading buffer failed")?;
                    trace!("Read {} bytes", count);

                    if count == 0 {
                        trace!("ready");
                        break;
                    }

                    trace!("Updating buffer");
                    m.update(&buffer[..count]);
                }
                Ok(HashValue(format!("{:x}", m.finalize())))
            }
            HashType::Sha256 => {
                use sha2::Digest;

                trace!("SHA256 hashing buffer");
                let mut m = sha2::Sha256::new();
                loop {
                    trace!("Reading");
                    let count = reader.read(&mut buffer)
                        .await
                        .context("Reading buffer failed")?;
                    trace!("Read {} bytes", count);

                    if count == 0 {
                        trace!("ready");
                        break;
                    }

                    trace!("Updating buffer");
                    m.update(&buffer[..count]);
                }
                let h = format!("{:x}", m.finalize());
                trace!("Hash = {:?}", h);
                Ok(HashValue(h))
            }
            HashType::Sha512 => {
                use sha2::Digest;

                trace!("SHA512 hashing buffer");
                let mut m = sha2::Sha512::new();
                loop {
                    trace!("Reading");
                    let count = reader.read(&mut buffer)
                        .await
                        .context("Reading buffer failed")?;
                    trace!("Read {} bytes", count);

                    if count == 0 {
                        trace!("ready");
                        break;
                    }

                    trace!("Updating buffer");
                    m.update(&buffer[..count]);
                }
                Ok(HashValue(String::from_utf8(m.finalize()[..].to_vec())?))
            }
        }
    }
}

#[derive(parse_display::Display, Serialize, Deserialize, Clone, Debug, Hash, Eq, PartialEq)]
#[serde(transparent)]
#[display("{0}")]
pub struct HashValue(String);

#[cfg(test)]
impl From<String> for HashValue {
    fn from(s: String) -> Self {
        HashValue(s)
    }
}