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
//! The one-way stream of a push: the messages of a session in one direction,
//! with no reply. [`Repo::receive_stream`] and
//! [`Repo::receive_stream_to_commit`] read it.
use std::pin::Pin;
use futures_io::{AsyncBufRead, AsyncRead};
use futures_lite::io::BufReader;
use super::StreamPolicy;
use super::core::SessionCore;
use super::session::{Failure, ReceiveReport, STREAM_BUFFER, next, out_of_order};
use crate::error::{Error, Result};
use crate::remote::proto::{CommitRequest, FrameReader, Message};
use crate::remote::{self, Expected};
use crate::repo::Repo;
/// Methods that receive a one-way stream.
impl Repo {
/// Reads one one-way stream from `input` into one transaction.
///
/// A one-way stream holds the messages of a push session in one direction.
/// The call sends no message, and returns the result in place of a reply.
/// The stream holds these messages, in this order:
///
/// 1. One `Hello` with `one-way` true.
/// 2. Zero or more object streams, each one closed by `ObjectsEnd`.
/// 3. One `Commit`.
/// 4. The end of `input`.
///
/// [`Repo::receive_stream_to_commit`] reads the same stream, and stops at
/// `Commit`.
///
/// # Hello
///
/// The frame limit and the chunk limit are 1 MiB
/// ([`MAX_FRAME`](crate::remote::proto::MAX_FRAME)). A `bare-split-xattrs`
/// repository is `mode-refused`. A `bare` repository is `mode-refused`
/// unless the process runs as root. The call accepts a repository with
/// `[core] locking=false`.
///
/// The size of a `HelloReply` does not bound the ref names of `Hello`,
/// because the stream gets no reply.
///
/// # Objects
///
/// The call stages the objects as [`Repo::receive`] does. Before the
/// stage, it verifies the checksum of each object and checks the content
/// rules of the repository mode and of `policy`.
///
/// # Locks
///
/// The session transaction holds the repository lock shared from `Hello`
/// to the end. Under `[core] locking=false`, it holds no lock. The commit
/// takes the update lock, which ignores `[core] locking`.
///
/// # Commit
///
/// `Commit` runs the checks and the steps of [`Repo::receive`], with four
/// differences:
///
/// - The rule of each update is the rule that
/// [`StreamPolicy::rule_for`](super::StreamPolicy::rule_for) selects. An
/// update that no rule covers, and an update whose rule has `accept`
/// false, are `ref-denied`. A delete of a ref that is present needs
/// `allow_delete`. An update that is not a fast-forward needs `force`
/// and `allow_non_fast_forward`. With
/// [`ReceiveVerify::Keys`](super::ReceiveVerify::Keys), each new commit
/// must pass the verification of the rule of each of its updates, and a
/// commit with no signature fails. A commit that no update names gets
/// no verification, a dependency included.
/// - The call ignores the `signers` of each rule, `summary_signers`, and
/// `update_summary` of `policy`. As a result, the commit adds no server
/// signature, writes no anchor commit, and does not regenerate the
/// summary.
/// - A ref update whose expected state is [`Expected::Commit`] is
/// `protocol`. A ref update with no new commit, and a server commit,
/// are also `protocol`.
/// - The commit checks run only after `input` reaches its end. A byte
/// after `Commit` is `protocol`. [`Repo::receive_stream_to_commit`]
/// runs them at `Commit`, and starts no read of `input` after it.
///
/// The reply limit of the two-way session also applies to the ref updates
/// of `Commit`.
///
/// # Errors
///
/// A failure before the transaction commit aborts the transaction, and the
/// repository does not change. A failure of the transaction commit can
/// leave the detached metadata and some refs written. The call returns a
/// wire code inside [`Error::Remote`]. It returns each other error as it is.
///
/// - [`remote::Error::Protocol`] if the first message is not `Hello`, if
/// `Hello` does not have `one-way` true, or if `Hello` names a
/// collection. A one-way stream writes the local refs and the remote
/// refs alone.
/// - [`remote::Error::Protocol`] if a message comes out of order. `Have` and
/// an `Abort` frame between two objects are out of order.
/// - [`remote::Error::VersionUnsupported`] if `Hello` states another
/// protocol version.
/// - [`remote::Error::ModeRefused`] if the repository mode is
/// `bare-split-xattrs`, or if it is `bare` and the process does not run
/// as root.
/// - [`remote::Error::InvalidRef`] if `Hello` names a ref that is not valid.
/// - The errors of [`Repo::transaction`] if the session transaction cannot
/// open. These include [`Error::LockTimeout`] for the repository lock.
/// - [`Error::Core`] or [`Error::InvalidFormat`] if `[core] fsync`,
/// `[core] per-object-fsync`, `[ex-integrity] fsverity`,
/// `[ex-ostrya] keep-detached-related`, or `[archive] zlib-level` is
/// malformed.
/// - The errors of an object stream that [`Repo::receive`] lists:
/// `checksum-mismatch`, `mode-refused`, `limit-exceeded`, `protocol`,
/// and the wire code of the frame decoder.
/// - [`remote::Error::Protocol`] if an update of `Commit` expects a commit
/// or has no new commit, if `Commit` holds a server commit, or if a byte
/// follows `Commit`.
/// - At `Commit`, the errors of
/// [`ReceiveService::commit`](super::ReceiveService::commit), other than
/// the errors of steps in flight and of hooks. These include
/// [`Error::LockTimeout`] for the update lock.
/// - [`remote::Error::Aborted`] inside [`Error::Remote`] if the sender
/// abandons an object: the abandon marker and then `Abort` inside the
/// object.
/// - [`Error::Io`] of kind `UnexpectedEof` if `input` ends before
/// `Commit` is complete.
/// - [`Error::Io`] if a read of `input` fails.
/// - An I/O error from the file system, if a step of the transaction
/// fails.
pub async fn receive_stream<R>(&self, input: R, policy: &StreamPolicy) -> Result<ReceiveReport>
where
R: AsyncRead + Unpin + Send,
{
let reader = FrameReader::new(BufReader::with_capacity(STREAM_BUFFER, input));
// A failure drops the transaction here, which removes its staging
// directory and releases the repository lock.
run(self, policy, reader, AfterCommit::CheckEnd)
.await
.map_err(stream_error)
}
/// Reads one one-way stream from `input` into one transaction, and stops
/// at `Commit`.
///
/// The call reads the stream as [`Repo::receive_stream`] does, with one
/// difference. It runs the commit checks when it has read the `Commit`
/// frame, and starts no read of `input` after that frame. A byte after
/// `Commit` is not `protocol`.
///
/// The call reads `input` through a buffer, and a read of `input` returns
/// the bytes that are ready. A read that completes the `Commit` frame can
/// also get bytes after the frame. The call discards these bytes with no
/// check, and a later reader of `input` does not get them.
///
/// Use this call on a channel that gives no end of input, for example a
/// virtio-serial port. On such a channel, [`Repo::receive_stream`] waits
/// until the writer closes the channel or writes one more byte.
///
/// # Errors
///
/// The errors of [`Repo::receive_stream`], with one difference: a byte
/// after `Commit` is not an error. These include [`Error::Io`] of kind
/// `UnexpectedEof` if `input` ends before `Commit` is complete.
pub async fn receive_stream_to_commit<R>(
&self,
input: R,
policy: &StreamPolicy,
) -> Result<ReceiveReport>
where
R: AsyncRead + Unpin + Send,
{
let reader = FrameReader::new(BufReader::with_capacity(STREAM_BUFFER, input));
run(self, policy, reader, AfterCommit::Stop)
.await
.map_err(stream_error)
}
}
/// What the receive does with `input` after the `Commit` frame.
#[derive(Clone, Copy, PartialEq, Eq)]
enum AfterCommit {
/// Read to the end of `input`. A byte there is `protocol`.
CheckEnd,
/// Start no read, and discard the bytes in the buffer with no check.
Stop,
}
/// Returns the error of the call for `failure`.
fn stream_error(failure: Failure) -> Error {
match failure {
Failure::Wire(e) => Error::Remote(e),
Failure::Internal(e) | Failure::Silent(e) => e,
}
}
async fn run<R>(
repo: &Repo,
policy: &StreamPolicy,
mut reader: FrameReader<BufReader<R>>,
after: AfterCommit,
) -> std::result::Result<ReceiveReport, Failure>
where
R: AsyncRead + Unpin + Send,
{
let core = match next(&mut reader).await? {
Message::Hello(hello) => SessionCore::open_one_way(repo.clone(), policy, hello).await?,
other => return Err(out_of_order(&other)),
};
let mut buf = Vec::new();
let request = loop {
match next(&mut reader).await? {
Message::ObjectHeader(header) => {
core.objects(Some(header), &mut reader, &mut buf).await?;
}
Message::ObjectsEnd => {
core.objects(None, &mut reader, &mut buf).await?;
}
Message::Commit(request) => break request,
other => return Err(out_of_order(&other)),
}
};
check_updates(&request)?;
let mut rest = reader.into_inner();
if after == AfterCommit::CheckEnd {
// Any byte after `Commit` is `protocol`, also bytes that do not make
// a whole frame. The `fill_buf` future of `futures-lite` polls the
// reader a second time after a ready poll, and panics if that poll is
// `Pending`. A reader that reads on a blocking pool returns `Pending`
// when a read follows the end of input, so the check polls the reader
// once for each wake.
let end = std::future::poll_fn(|cx| {
Pin::new(&mut rest)
.poll_fill_buf(cx)
.map_ok(|bytes| bytes.is_empty())
})
.await;
match end {
Ok(true) => {}
Ok(false) => {
return Err(Failure::Wire(remote::Error::Protocol(
"bytes follow Commit in a one-way stream".into(),
)));
}
Err(e) => return Err(Failure::Silent(Error::Io(e))),
}
}
// Under `AfterCommit::Stop`, the drop discards the bytes after `Commit`
// that the buffer holds, with no check.
drop(rest);
drop(buf);
core.finish(request).await
}
/// Checks that `request` holds no server commit, and that each update of
/// `request` expects its ref absent or takes any state, and sets a new
/// commit.
///
/// A one-way sender cannot learn the current tips of the refs, and the
/// server makes no commit for it.
fn check_updates(request: &CommitRequest) -> std::result::Result<(), Failure> {
if request.server_commit.is_some() {
return Err(Failure::Wire(remote::Error::Protocol(
"a one-way stream carries no server commit".into(),
)));
}
for update in &request.updates {
if let Expected::Commit(_) = update.expected {
return Err(Failure::Wire(remote::Error::Protocol(format!(
"the update of '{}' expects a commit, which a one-way stream cannot state",
update.name
))));
}
if update.new.is_none() {
return Err(Failure::Wire(remote::Error::Protocol(format!(
"the update of '{}' deletes the ref, which a one-way stream cannot do",
update.name
))));
}
}
Ok(())
}
// A compile-time check that the future of a one-way stream is `Send`, so
// that it can run on a thread pool.
const _: fn() = || {
fn assert_send<T: Send>(_: T) {}
let _ = |repo: &Repo, policy: &StreamPolicy| {
assert_send(repo.receive_stream(futures_lite::io::empty(), policy));
assert_send(repo.receive_stream_to_commit(futures_lite::io::empty(), policy))
};
};