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
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

use crate::client::{Client, MDataInfo};
use crate::crypto::shared_secretbox;
use crate::errors::CoreError;
use crate::nfs::{File, Mode, NfsError, NfsFuture, Reader, Writer};
use crate::self_encryption_storage::SelfEncryptionStorage;
use crate::utils::FutureExt;
use bincode::{deserialize, serialize};
use futures::{Future, IntoFuture};
use safe_nd::{Error as SndError, MDataSeqEntryActions};
use serde::{Deserialize, Serialize};

/// Enum specifying which version should be used in places where a version is required.
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub enum Version {
    /// Query the network for the next version.
    GetNext,
    /// Use the specified version.
    Custom(u64),
}

/// Insert the file into the directory.
pub fn insert<S>(client: impl Client, parent: MDataInfo, name: S, file: &File) -> Box<NfsFuture<()>>
where
    S: AsRef<str>,
{
    let name = name.as_ref();
    trace!("Inserting file with name '{}'", name);

    serialize(&file)
        .map_err(From::from)
        .and_then(|encoded| {
            let key = parent.enc_entry_key(name.as_bytes())?;
            let value = parent.enc_entry_value(&encoded)?;

            Ok((key, value))
        })
        .into_future()
        .and_then(move |(key, value)| {
            client.mutate_seq_mdata_entries(
                parent.name(),
                parent.type_tag(),
                MDataSeqEntryActions::new().ins(key, value, 0),
            )
        })
        .map_err(From::from)
        .into_box()
}

/// Get a file and its version from the directory.
pub fn fetch<S>(client: impl Client, parent: MDataInfo, name: S) -> Box<NfsFuture<(u64, File)>>
where
    S: AsRef<str>,
{
    parent
        .enc_entry_key(name.as_ref().as_bytes())
        .into_future()
        .and_then(move |key| {
            client
                .get_seq_mdata_value(parent.name(), parent.type_tag(), key)
                .map(move |value| (value, parent))
        })
        .and_then(move |(value, parent)| {
            let plaintext = parent.decrypt(&value.data)?;
            let file = deserialize(&plaintext)?;
            Ok((value.version, file))
        })
        .map_err(convert_error)
        .into_box()
}

/// Return a Reader for reading the file contents.
pub fn read<C: Client>(
    client: C,
    file: &File,
    encryption_key: Option<shared_secretbox::Key>,
) -> Box<NfsFuture<Reader<C>>> {
    trace!("Reading file {:?}", file);
    Reader::new(
        client.clone(),
        SelfEncryptionStorage::new(client, file.published()),
        file,
        encryption_key,
    )
}

/// Delete a file from the directory.
///
/// If `version` is `Version::GetNext`, the current version is first retrieved from the network, and
/// that version incremented by one is then used as the actual version.
// Allow pass by value for consistency with other functions.
#[allow(clippy::needless_pass_by_value)]
pub fn delete<S>(
    client: impl Client,
    parent: MDataInfo,
    name: S,
    published: bool,
    version: Version,
) -> Box<NfsFuture<u64>>
where
    S: AsRef<str>,
{
    let name = name.as_ref();
    let name2 = name.to_owned().clone();
    let client2 = client.clone();
    let client3 = client.clone();
    let parent2 = parent.clone();
    trace!("Deleting file with name {}.", name);

    let key = fry!(parent.enc_entry_key(name.as_bytes()));

    let version_fut = match version {
        Version::GetNext => client
            .get_seq_mdata_value(parent.name(), parent.type_tag(), key.clone())
            .map(move |value| (value.version + 1))
            .into_box(),
        Version::Custom(version) => ok!(version),
    }
    .map_err(NfsError::from);

    version_fut
        .and_then(move |version| {
            if !published {
                fetch(client, parent2, name2)
                    .and_then(move |(_, file)| {
                        client2
                            .del_unpub_idata(*file.data_map_name())
                            .map(move |_| version)
                            .map_err(NfsError::from)
                    })
                    .into_box()
            } else {
                ok!(version)
            }
        })
        .and_then(move |version| {
            client3
                .mutate_seq_mdata_entries(
                    parent.name(),
                    parent.type_tag(),
                    MDataSeqEntryActions::new().del(key, version),
                )
                .map(move |()| version)
                .map_err(convert_error)
        })
        .into_box()
}

/// Update the file.
///
/// If `version` is `Version::GetNext`, the current version is first retrieved from the network, and
/// that version incremented by one is then used as the actual version.
pub fn update<S>(
    client: impl Client,
    parent: MDataInfo,
    name: S,
    file: &File,
    version: Version,
) -> Box<NfsFuture<u64>>
where
    S: AsRef<str>,
{
    let name = name.as_ref();
    trace!("Updating file with name '{}'", name);

    let client2 = client.clone();

    serialize(&file)
        .map_err(From::from)
        .and_then(|encoded| {
            let key = parent.enc_entry_key(name.as_bytes())?;
            let content = parent.enc_entry_value(&encoded)?;

            Ok((key, content))
        })
        .into_future()
        .and_then(move |(key, content)| match version {
            Version::GetNext => client
                .get_seq_mdata_value(parent.name(), parent.type_tag(), key.clone())
                .map(move |value| (key, content, value.version + 1, parent))
                .into_box(),
            Version::Custom(version) => ok!((key, content, version, parent)),
        })
        .and_then(move |(key, content, version, parent)| {
            client2
                .mutate_seq_mdata_entries(
                    parent.name(),
                    parent.type_tag(),
                    MDataSeqEntryActions::new().update(key, content, version),
                )
                .map(move |()| version)
        })
        .map_err(convert_error)
        .into_box()
}

/// Helper function to update content of a file in a directory. A Writer
/// object is returned, through which the data for the file can be written to
/// the network. The file is actually saved in the directory listing only after
/// `writer.close()` is invoked.
pub fn write<C: Client>(
    client: C,
    file: File,
    mode: Mode,
    encryption_key: Option<shared_secretbox::Key>,
) -> Box<NfsFuture<Writer<C>>> {
    trace!("Creating a writer for a file");

    Writer::new(
        &client.clone(),
        SelfEncryptionStorage::new(client, file.published()),
        file,
        mode,
        encryption_key,
    )
}

// This is different from `impl From<CoreError> for NfsError`, because it maps
// `NoSuchEntry` to `FileNotFound`.
// TODO:  consider performing such conversion directly in the mentioned `impl From`.
fn convert_error(err: CoreError) -> NfsError {
    match err {
        CoreError::DataError(SndError::NoSuchEntry) => NfsError::FileNotFound,
        _ => NfsError::from(err),
    }
}