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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Code for creating filesystem servers.
//! 
//! The [FsProvider] trait defines the interface that a filesystem server
//! must implement.
//! A new server can be created using the [new_fs_server] function.
use crate::msg::{Read as ReadMsg, *};

use btlib::{crypto::Creds, BlockPath, Result};
use bttp::{MsgCallback, MsgReceived, Receiver};
use core::future::Future;
use std::{net::IpAddr, ops::Deref, sync::Arc};

/// Trait for types which act as filesystem servers.
pub trait FsProvider: Send + Sync {
    type LookupFut<'c>: Send + Future<Output = Result<LookupReply>>
    where
        Self: 'c;
    fn lookup<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Lookup<'c>) -> Self::LookupFut<'c>;

    type CreateFut<'c>: Send + Future<Output = Result<CreateReply>>
    where
        Self: 'c;
    fn create<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Create<'c>) -> Self::CreateFut<'c>;

    type OpenFut<'c>: Send + Future<Output = Result<OpenReply>>
    where
        Self: 'c;
    fn open<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Open) -> Self::OpenFut<'c>;

    type ReadGuard: Send + Sync + Deref<Target = [u8]>;
    type ReadFut<'c>: Send + Future<Output = Result<Self::ReadGuard>>
    where
        Self: 'c;
    /// Reads from the file specified in the given message.
    /// ### WARNING
    /// The returned guard must be dropped before another method is called on this provider.
    /// Otherwise deadlock _will_ occur.
    fn read<'c>(&'c self, from: &'c Arc<BlockPath>, msg: ReadMsg) -> Self::ReadFut<'c>;

    type WriteFut<'r>: Send + Future<Output = Result<WriteReply>>
    where
        Self: 'r;
    fn write<'c>(&'c self, from: &'c Arc<BlockPath>, write: Write<&'c [u8]>) -> Self::WriteFut<'c>;

    type FlushFut<'c>: Send + Future<Output = Result<()>>
    where
        Self: 'c;
    fn flush<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Flush) -> Self::FlushFut<'c>;

    type ReadDirFut<'c>: Send + Future<Output = Result<ReadDirReply>>
    where
        Self: 'c;
    fn read_dir<'c>(&'c self, from: &'c Arc<BlockPath>, msg: ReadDir) -> Self::ReadDirFut<'c>;

    type LinkFut<'c>: Send + Future<Output = Result<LinkReply>>
    where
        Self: 'c;
    fn link<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Link<'c>) -> Self::LinkFut<'c>;

    type UnlinkFut<'c>: Send + Future<Output = Result<()>>
    where
        Self: 'c;
    fn unlink<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Unlink<'c>) -> Self::UnlinkFut<'c>;

    type ReadMetaFut<'c>: Send + Future<Output = Result<ReadMetaReply>>
    where
        Self: 'c;
    fn read_meta<'c>(&'c self, from: &'c Arc<BlockPath>, msg: ReadMeta) -> Self::ReadMetaFut<'c>;

    type WriteMetaFut<'c>: Send + Future<Output = Result<WriteMetaReply>>
    where
        Self: 'c;
    fn write_meta<'c>(&'c self, from: &'c Arc<BlockPath>, msg: WriteMeta)
        -> Self::WriteMetaFut<'c>;

    type AllocateFut<'c>: Send + Future<Output = Result<()>>
    where
        Self: 'c;
    fn allocate<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Allocate) -> Self::AllocateFut<'c>;

    type CloseFut<'c>: Send + Future<Output = Result<()>>
    where
        Self: 'c;
    fn close<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Close) -> Self::CloseFut<'c>;

    type ForgetFut<'c>: Send + Future<Output = Result<()>>
    where
        Self: 'c;
    fn forget<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Forget) -> Self::ForgetFut<'c>;

    type LockFut<'c>: Send + Future<Output = Result<()>>
    where
        Self: 'c;
    fn lock<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Lock) -> Self::LockFut<'c>;

    type UnlockFut<'c>: Send + Future<Output = Result<()>>
    where
        Self: 'c;
    fn unlock<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Unlock) -> Self::UnlockFut<'c>;

    type AddReacapFut<'c>: Send + Future<Output = Result<()>>
    where
        Self: 'c;
    fn add_readcap<'c>(
        &'c self,
        from: &'c Arc<BlockPath>,
        msg: AddReadcap,
    ) -> Self::AddReacapFut<'c>;

    type GrantAccessFut<'c>: Send + Future<Output = Result<()>>
    where
        Self: 'c;
    fn grant_access<'c>(
        &'c self,
        from: &'c Arc<BlockPath>,
        msg: GrantAccess,
    ) -> Self::GrantAccessFut<'c>;
}

impl<P: 'static + ?Sized + FsProvider, Ptr: Send + Sync + Deref<Target = P>> FsProvider for Ptr {
    type LookupFut<'c> = P::LookupFut<'c> where Self: 'c;
    fn lookup<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Lookup<'c>) -> Self::LookupFut<'c> {
        self.deref().lookup(from, msg)
    }

    type CreateFut<'c> = P::CreateFut<'c> where Self: 'c;
    fn create<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Create<'c>) -> Self::CreateFut<'c> {
        self.deref().create(from, msg)
    }

    type OpenFut<'c> = P::OpenFut<'c> where Self: 'c;
    fn open<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Open) -> Self::OpenFut<'c> {
        self.deref().open(from, msg)
    }

    type ReadGuard = P::ReadGuard;
    type ReadFut<'c> = P::ReadFut<'c> where Self: 'c;
    fn read<'c>(&'c self, from: &'c Arc<BlockPath>, msg: ReadMsg) -> Self::ReadFut<'c> {
        self.deref().read(from, msg)
    }

    type WriteFut<'r> = P::WriteFut<'r> where Self: 'r;
    fn write<'c>(&'c self, from: &'c Arc<BlockPath>, write: Write<&'c [u8]>) -> Self::WriteFut<'c> {
        self.deref().write(from, write)
    }

    type FlushFut<'c> = P::FlushFut<'c> where Self: 'c;
    fn flush<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Flush) -> Self::FlushFut<'c> {
        self.deref().flush(from, msg)
    }

    type ReadDirFut<'c> = P::ReadDirFut<'c> where Self: 'c;
    fn read_dir<'c>(&'c self, from: &'c Arc<BlockPath>, msg: ReadDir) -> Self::ReadDirFut<'c> {
        self.deref().read_dir(from, msg)
    }

    type LinkFut<'c> = P::LinkFut<'c> where Self: 'c;
    fn link<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Link<'c>) -> Self::LinkFut<'c> {
        self.deref().link(from, msg)
    }

    type UnlinkFut<'c> = P::UnlinkFut<'c> where Self: 'c;
    fn unlink<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Unlink<'c>) -> Self::UnlinkFut<'c> {
        self.deref().unlink(from, msg)
    }

    type ReadMetaFut<'c> = P::ReadMetaFut<'c> where Self: 'c;
    fn read_meta<'c>(&'c self, from: &'c Arc<BlockPath>, msg: ReadMeta) -> Self::ReadMetaFut<'c> {
        self.deref().read_meta(from, msg)
    }

    type WriteMetaFut<'c> = P::WriteMetaFut<'c> where Self: 'c;
    fn write_meta<'c>(
        &'c self,
        from: &'c Arc<BlockPath>,
        msg: WriteMeta,
    ) -> Self::WriteMetaFut<'c> {
        self.deref().write_meta(from, msg)
    }

    type AllocateFut<'c> = P::AllocateFut<'c> where Self: 'c;
    fn allocate<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Allocate) -> Self::AllocateFut<'c> {
        self.deref().allocate(from, msg)
    }

    type CloseFut<'c> = P::CloseFut<'c> where Self: 'c;
    fn close<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Close) -> Self::CloseFut<'c> {
        self.deref().close(from, msg)
    }

    type ForgetFut<'c> = P::ForgetFut<'c> where Self: 'c;
    fn forget<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Forget) -> Self::ForgetFut<'c> {
        self.deref().forget(from, msg)
    }

    type LockFut<'c> = P::LockFut<'c> where Self: 'c;
    fn lock<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Lock) -> Self::LockFut<'c> {
        self.deref().lock(from, msg)
    }

    type UnlockFut<'c> = P::UnlockFut<'c> where Self: 'c;
    fn unlock<'c>(&'c self, from: &'c Arc<BlockPath>, msg: Unlock) -> Self::UnlockFut<'c> {
        self.deref().unlock(from, msg)
    }

    type AddReacapFut<'c> = P::AddReacapFut<'c> where Self: 'c;
    fn add_readcap<'c>(
        &'c self,
        from: &'c Arc<BlockPath>,
        msg: AddReadcap,
    ) -> Self::AddReacapFut<'c> {
        self.deref().add_readcap(from, msg)
    }

    type GrantAccessFut<'c> = P::GrantAccessFut<'c> where Self: 'c;
    fn grant_access<'c>(
        &'c self,
        from: &'c Arc<BlockPath>,
        msg: GrantAccess,
    ) -> Self::GrantAccessFut<'c> {
        self.deref().grant_access(from, msg)
    }
}

struct ServerCallback<P> {
    provider: Arc<P>,
}

impl<P> ServerCallback<P> {
    fn new(provider: Arc<P>) -> Self {
        Self { provider }
    }
}

impl<P> Clone for ServerCallback<P> {
    fn clone(&self) -> Self {
        Self {
            provider: self.provider.clone(),
        }
    }
}

impl<P: 'static + Send + Sync + FsProvider> MsgCallback for ServerCallback<P> {
    type Arg<'de> = FsMsg<'de>;
    type CallFut<'de> = impl 'de + Future<Output = btlib::Result<()>>;
    fn call<'de>(&'de self, arg: MsgReceived<FsMsg<'de>>) -> Self::CallFut<'de> {
        async move {
            let (from, body, replier) = arg.into_parts();
            let provider = self.provider.as_ref();
            let reply = match body {
                FsMsg::Lookup(lookup) => FsReply::Lookup(provider.lookup(&from, lookup).await?),
                FsMsg::Create(create) => FsReply::Create(provider.create(&from, create).await?),
                FsMsg::Open(open) => FsReply::Open(provider.open(&from, open).await?),
                FsMsg::Read(read) => {
                    let guard = provider.read(&from, read).await?;
                    let mut replier = replier.unwrap();
                    replier
                        .reply(FsReply::Read(ReadReply { data: &guard }))
                        .await?;
                    return Ok(());
                }
                FsMsg::Write(write) => FsReply::Write(provider.write(&from, write).await?),
                FsMsg::Flush(flush) => FsReply::Ack(provider.flush(&from, flush).await?),
                FsMsg::ReadDir(read_dir) => {
                    FsReply::ReadDir(provider.read_dir(&from, read_dir).await?)
                }
                FsMsg::Link(link) => FsReply::Link(provider.link(&from, link).await?),
                FsMsg::Unlink(unlink) => FsReply::Ack(provider.unlink(&from, unlink).await?),
                FsMsg::ReadMeta(read_meta) => {
                    FsReply::ReadMeta(provider.read_meta(&from, read_meta).await?)
                }
                FsMsg::WriteMeta(write_meta) => {
                    FsReply::WriteMeta(provider.write_meta(&from, write_meta).await?)
                }
                FsMsg::Allocate(allocate) => {
                    FsReply::Ack(provider.allocate(&from, allocate).await?)
                }
                FsMsg::Close(close) => FsReply::Ack(provider.close(&from, close).await?),
                FsMsg::Forget(forget) => FsReply::Ack(provider.forget(&from, forget).await?),
                FsMsg::Lock(lock) => FsReply::Ack(provider.lock(&from, lock).await?),
                FsMsg::Unlock(unlock) => FsReply::Ack(provider.unlock(&from, unlock).await?),
                FsMsg::AddReadcap(add_readcap) => {
                    FsReply::Ack(provider.add_readcap(&from, add_readcap).await?)
                }
                FsMsg::GrantAccess(grant_access) => {
                    FsReply::Ack(provider.grant_access(&from, grant_access).await?)
                }
            };
            replier.unwrap().reply(reply).await
        }
    }
}

/// Creates a new filesystem server by creating a [Receiver] which uses the given [FsProvider] to
/// handle filesystem access requests.
/// The server listens on `ip_addr` and uses `creds` to authenticate itself to clients.
pub fn new_fs_server<C, P>(ip_addr: IpAddr, creds: Arc<C>, provider: Arc<P>) -> Result<Receiver>
where
    C: 'static + Creds,
    P: 'static + FsProvider,
{
    Receiver::new(ip_addr, creds, ServerCallback::new(provider))
}