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
// Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement.  This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// 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 GROUP_SIZE;
use cache::Cache;
use config_handler::{self, Config};
use error::InternalError;
use personas::data_manager::DataManager;
#[cfg(feature = "use-mock-crust")]
use personas::data_manager::IdAndVersion;
use personas::maid_manager::MaidManager;
use routing::{Authority, Data, EventStream, NodeBuilder, Request, Response, RoutingTable, XorName};
use rust_sodium;
use rust_sodium::crypto::sign::PublicKey;
use std::env;
use std::path::Path;

pub const CHUNK_STORE_DIR: &'static str = "safe_vault_chunk_store";
const DEFAULT_MAX_CAPACITY: u64 = 2 * 1024 * 1024 * 1024;

pub use routing::Event;
pub use routing::Node as RoutingNode;

/// Main struct to hold all personas and Routing instance
pub struct Vault {
    maid_manager: MaidManager,
    data_manager: DataManager,
    routing_node: RoutingNode,
}

impl Vault {
    /// Creates a network Vault instance.
    pub fn new(first_vault: bool, use_cache: bool) -> Result<Self, InternalError> {
        let config = match config_handler::read_config_file() {
            Ok(cfg) => cfg,
            Err(InternalError::FileHandler(e)) => {
                error!("Config file could not be parsed: {:?}", e);
                return Err(From::from(e));
            }
            Err(e) => return Err(From::from(e)),
        };
        let builder = RoutingNode::builder()
            .first(first_vault)
            .deny_other_local_nodes();
        match Self::vault_with_config(builder, use_cache, config.clone()) {
            Ok(vault) => Ok(vault),
            Err(InternalError::ChunkStore(e)) => {
                error!("Incorrect path {:?} for chunk_store_root: {:?}",
                       config.chunk_store_root,
                       e);
                Err(From::from(e))
            }
            Err(e) => Err(From::from(e)),
        }
    }

    /// Allow construct vault with config for mock-crust tests.
    #[cfg(feature = "use-mock-crust")]
    pub fn new_with_config(first_vault: bool,
                           use_cache: bool,
                           config: Config)
                           -> Result<Self, InternalError> {
        Self::vault_with_config(RoutingNode::builder().first(first_vault), use_cache, config)
    }

    /// Allow construct vault with config for mock-crust tests.
    fn vault_with_config(builder: NodeBuilder,
                         use_cache: bool,
                         config: Config)
                         -> Result<Self, InternalError> {
        rust_sodium::init();

        let mut chunk_store_root = match config.chunk_store_root {
            Some(path_str) => Path::new(&path_str).to_path_buf(),
            None => env::temp_dir(),
        };
        chunk_store_root.push(CHUNK_STORE_DIR);

        let routing_node = if use_cache {
            builder.cache(Box::new(Cache::new())).create(GROUP_SIZE)
        } else {
            builder.create(GROUP_SIZE)
        }?;

        Ok(Vault {
               maid_manager: MaidManager::new(config.invite_key.map(PublicKey)),
               data_manager: DataManager::new(chunk_store_root,
                                              config.max_capacity.unwrap_or(DEFAULT_MAX_CAPACITY))?,
               routing_node: routing_node,
           })

    }

    /// Run the event loop, processing events received from Routing.
    pub fn run(&mut self) -> Result<bool, InternalError> {
        while let Ok(ev) = self.routing_node.next_ev() {
            if let Some(terminate) = self.process_event(ev) {
                return Ok(terminate);
            }
        }
        // FIXME: decide if we want to restart here (in which case return `Ok(false)`).
        Ok(true)
    }

    /// Non-blocking call to process any events in the event queue, returning true if
    /// any received, otherwise returns false.
    #[cfg(feature = "use-mock-crust")]
    pub fn poll(&mut self) -> bool {
        let mut ev_processed = self.routing_node.poll();

        while let Ok(ev) = self.routing_node.try_next_ev() {
            let _ = self.process_event(ev);
            ev_processed = true;
        }

        ev_processed
    }

    /// Get the names of all the data chunks stored in a personas' chunk store.
    #[cfg(feature = "use-mock-crust")]
    pub fn get_stored_names(&self) -> Vec<IdAndVersion> {
        self.data_manager.get_stored_names()
    }

    /// Get the number of put requests the network processed for the given client.
    #[cfg(feature = "use-mock-crust")]
    pub fn get_maid_manager_put_count(&self, client_name: &XorName) -> Option<u64> {
        self.maid_manager.get_put_count(client_name)
    }

    /// Resend all unacknowledged messages.
    #[cfg(feature = "use-mock-crust")]
    pub fn resend_unacknowledged(&mut self) -> bool {
        self.routing_node.resend_unacknowledged()
    }

    /// Clear routing node state.
    #[cfg(feature = "use-mock-crust")]
    pub fn clear_state(&mut self) {
        self.routing_node.clear_state()
    }

    /// Vault node name
    #[cfg(feature = "use-mock-crust")]
    pub fn name(&self) -> XorName {
        unwrap!(self.routing_node.name())
    }

    /// Vault routing_table
    #[cfg(feature = "use-mock-crust")]
    pub fn routing_table(&self) -> RoutingTable<XorName> {
        unwrap!(self.routing_node.routing_table())
    }

    fn process_event(&mut self, event: Event) -> Option<bool> {
        let mut ret = None;

        if let Err(error) = match event {
               Event::Request { request, src, dst } => self.on_request(request, src, dst),
               Event::Response { response, src, dst } => self.on_response(response, src, dst),
               Event::NodeAdded(node_added, routing_table) => {
                   self.on_node_added(node_added, routing_table)
               }
               Event::NodeLost(node_lost, routing_table) => {
                   self.on_node_lost(node_lost, routing_table)
               }
               Event::RestartRequired => {
            warn!("Restarting Vault");
            ret = Some(false);
            Ok(())
        }
               Event::Terminate => {
            ret = Some(true);
            Ok(())
        }
               Event::SectionSplit(_prefix) |
               Event::SectionMerge(_prefix) => Ok(()),
               Event::Connected | Event::Tick => Ok(()),
           } {
            debug!("Failed to handle event: {:?}", error);
        }

        self.data_manager.check_timeouts(&mut self.routing_node);
        ret
    }

    fn on_request(&mut self,
                  request: Request,
                  src: Authority<XorName>,
                  dst: Authority<XorName>)
                  -> Result<(), InternalError> {
        match (src, dst, request) {
            // ================== Get ==================
            (src @ Authority::Client { .. },
             dst @ Authority::NaeManager(_),
             Request::Get(data_id, msg_id)) |
            (src @ Authority::ManagedNode(_),
             dst @ Authority::ManagedNode(_),
             Request::Get(data_id, msg_id)) => {
                self.data_manager
                    .handle_get(&mut self.routing_node, src, dst, data_id, msg_id)
            }
            // ================== Put ==================
            (src @ Authority::Client { .. },
             dst @ Authority::ClientManager(_),
             Request::Put(data, msg_id)) => {
                self.maid_manager
                    .handle_put(&mut self.routing_node, src, dst, data, msg_id)
            }
            (src @ Authority::ClientManager(_),
             dst @ Authority::NaeManager(_),
             Request::Put(data, msg_id)) => {
                self.data_manager
                    .handle_put(&mut self.routing_node, src, dst, data, msg_id)
            }
            // ================== Post ==================
            (src @ Authority::ClientManager(_),
             dst @ Authority::NaeManager(_),
             Request::Post(data, msg_id)) |
            (src @ Authority::Client { .. },
             dst @ Authority::NaeManager(_),
             Request::Post(data, msg_id)) => {
                self.data_manager
                    .handle_post(&mut self.routing_node, src, dst, data, msg_id)
            }
            // ================== Delete ==================
            (src @ Authority::Client { .. },
             dst @ Authority::NaeManager(_),
             Request::Delete(Data::Structured(data), msg_id)) => {
                self.data_manager
                    .handle_delete(&mut self.routing_node, src, dst, data, msg_id)
            }
            // ================== Append ==================
            (src @ Authority::Client { .. },
             dst @ Authority::NaeManager(_),
             Request::Append(wrapper, msg_id)) => {
                self.data_manager
                    .handle_append(&mut self.routing_node, src, dst, wrapper, msg_id)
            }
            // ================== GetAccountInfo ==================
            (src @ Authority::Client { .. },
             dst @ Authority::ClientManager(_),
             Request::GetAccountInfo(msg_id)) => {
                self.maid_manager
                    .handle_get_account_info(&mut self.routing_node, src, dst, msg_id)
            }
            // ================== Refresh ==================
            (Authority::ClientManager(_),
             Authority::ClientManager(_),
             Request::Refresh(serialised_msg, _)) => {
                self.maid_manager
                    .handle_refresh(&mut self.routing_node, &serialised_msg)
            }
            (Authority::ManagedNode(src_name),
             Authority::ManagedNode(_),
             Request::Refresh(serialised_msg, _)) |
            (Authority::ManagedNode(src_name),
             Authority::NaeManager(_),
             Request::Refresh(serialised_msg, _)) => {
                self.data_manager
                    .handle_refresh(&mut self.routing_node, src_name, &serialised_msg)
            }
            (Authority::NaeManager(_),
             Authority::NaeManager(_),
             Request::Refresh(serialised_msg, _)) => {
                self.data_manager
                    .handle_group_refresh(&mut self.routing_node, &serialised_msg)
            }
            // ================== Invalid Request ==================
            (_, _, request) => Err(InternalError::UnknownRequestType(request)),
        }
    }

    fn on_response(&mut self,
                   response: Response,
                   src: Authority<XorName>,
                   dst: Authority<XorName>)
                   -> Result<(), InternalError> {
        match (src, dst, response) {
            // ================== GetSuccess ==================
            (Authority::ManagedNode(src_name),
             Authority::ManagedNode(_),
             Response::GetSuccess(data, _)) => {
                self.data_manager
                    .handle_get_success(&mut self.routing_node, src_name, data)
            }
            // ================== GetFailure ==================
            (Authority::ManagedNode(src_name),
             Authority::ManagedNode(_),
             Response::GetFailure { data_id, .. }) => {
                self.data_manager
                    .handle_get_failure(&mut self.routing_node, src_name, data_id)
            }
            // ================== PutSuccess ==================
            (Authority::NaeManager(_),
             Authority::ClientManager(_),
             Response::PutSuccess(data_id, msg_id)) => {
                self.maid_manager
                    .handle_put_success(&mut self.routing_node, data_id, msg_id)
            }
            // ================== PutFailure ==================
            (Authority::NaeManager(_),
             Authority::ClientManager(_),
             Response::PutFailure {
                 id,
                 external_error_indicator,
                 data_id,
             }) => {
                self.maid_manager
                    .handle_put_failure(&mut self.routing_node,
                                        id,
                                        data_id,
                                        &external_error_indicator)
            }
            // ================== PostSuccess ==================
            (Authority::NaeManager(_),
             Authority::ClientManager(client_name),
             Response::PostSuccess(_, msg_id)) => {
                self.maid_manager
                    .handle_post_success(&mut self.routing_node, msg_id, client_name)
            }
            // ================== PostFailure ==================
            (Authority::NaeManager(_),
             Authority::ClientManager(_),
             Response::PostFailure {
                 id,
                 external_error_indicator,
                 ..
             }) => {
                self.maid_manager
                    .handle_post_failure(&mut self.routing_node, id, &external_error_indicator)
            }
            // ================== Invalid Response ==================
            (_, _, response) => Err(InternalError::UnknownResponseType(response)),
        }
    }

    fn on_node_added(&mut self,
                     node_added: XorName,
                     routing_table: RoutingTable<XorName>)
                     -> Result<(), InternalError> {
        self.maid_manager
            .handle_node_added(&mut self.routing_node, &node_added, &routing_table);
        self.data_manager
            .handle_node_added(&mut self.routing_node, &node_added, &routing_table);
        Ok(())
    }

    fn on_node_lost(&mut self,
                    node_lost: XorName,
                    routing_table: RoutingTable<XorName>)
                    -> Result<(), InternalError> {
        self.maid_manager
            .handle_node_lost(&mut self.routing_node, &node_lost);
        self.data_manager
            .handle_node_lost(&mut self.routing_node, &node_lost, &routing_table);
        Ok(())
    }
}