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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Client side GIOP connections.
//!
//! A [`Connection`] owns one TCP stream. Requests are written under a lock,
//! and a reader task takes every message off the stream, joins fragments
//! and hands each `Reply` or `LocateReply` to the caller waiting for its
//! request id. A caller that is the only one waiting reads its reply
//! itself instead ([`Connection::read_reply_here`]). A connection to a
//! TLS endpoint does both through [`Tls`].
use std::collections::HashMap;
use std::io::{self, IoSlice};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::{Duration, Instant};
use rustorb_cdr::ByteOrder;
use rustorb_giop::{Message, MessageEncoder, OutMessage, Version};
use tokio::io::AsyncWriteExt;
use tokio::net::TcpSocket;
use tokio::net::tcp::OwnedWriteHalf;
use tokio::sync::oneshot;
use crate::idle::Stamp;
use crate::tls::{self, Tls};
use crate::trace;
use crate::wire::{Here, Inbound, ReadError};
use crate::{CodeSets, OrbOptions};
/// Why a connection stopped delivering replies.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Closed {
/// The server sent `CloseConnection`: requests without a reply were
/// not processed and may be sent again.
Orderly,
/// The stream failed, or a message could not be read.
Failed(String),
}
/// At most this many pieces go into one vectored write.
const MAX_SLICES: usize = 64;
/// How long [`Connection::close`] waits to write `CloseConnection`.
const CLOSE_TIME: Duration = Duration::from_secs(2);
/// Why [`Connection::send`] did not write a message. Either way the
/// server cannot have read the whole of it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SendError {
/// The deadline passed first.
TimedOut,
/// The stream failed; the connection is closed.
Failed,
/// The connection is being closed and took nothing: the message may
/// go on a new connection.
Closing,
}
/// What the ORB pools connections by: host, port, and whether the
/// connection uses TLS.
pub(crate) type EndpointKey = (String, u16, bool);
/// The ORB's client connections, one per endpoint.
pub(crate) type ConnectionPool = Mutex<HashMap<EndpointKey, Arc<Connection>>>;
/// What a waiting caller receives.
pub(crate) type Delivery = Result<Message, Closed>;
#[derive(Debug)]
struct Pending {
waiters: HashMap<u32, oneshot::Sender<Delivery>>,
closed: Option<Closed>,
}
/// One client connection to a server endpoint.
#[derive(Debug)]
pub(crate) struct Connection {
endpoint: EndpointKey,
inbound: Inbound,
writer: tokio::sync::Mutex<OwnedWriteHalf>,
tls: Option<Arc<Tls>>,
pending: Mutex<Pending>,
next_request_id: AtomicU32,
/// The code sets of the first request with a code set context; `None`
/// until one was sent.
code_sets: Mutex<Option<CodeSets>>,
/// Set under the `pending` lock (by [`close`](Self::close) too), so
/// that an idle connection takes no new request once chosen to close.
closing: AtomicBool,
/// When a request or reply last went over the connection.
last_used: Stamp,
/// The pool the connection leaves when it ends.
pool: Weak<ConnectionPool>,
}
impl Connection {
/// Connects to `host:port`, with TLS when `tls` is given, and starts
/// the reader task on the current runtime. The socket buffers are set
/// before connecting, so that the window scale fits them.
pub(crate) async fn connect(
host: &str,
port: u16,
tls: Option<Arc<rustls::ClientConfig>>,
options: &OrbOptions,
pool: Weak<ConnectionPool>,
) -> io::Result<Arc<Connection>> {
let max_message_size = options.max_message_size;
let mut last = io::Error::new(io::ErrorKind::NotFound, "no address");
let mut connected = None;
for addr in tokio::net::lookup_host((host, port)).await? {
let socket = if addr.is_ipv4() {
TcpSocket::new_v4()?
} else {
TcpSocket::new_v6()?
};
if let Some(size) = options.socket_send_buffer {
socket.set_send_buffer_size(u32::try_from(size).unwrap_or(u32::MAX))?;
}
if let Some(size) = options.socket_receive_buffer {
socket.set_recv_buffer_size(u32::try_from(size).unwrap_or(u32::MAX))?;
}
match socket.connect(addr).await {
Ok(stream) => {
connected = Some(stream);
break;
}
Err(e) => {
trace::info!("could not connect to {addr} ({host}:{port}): {e}");
last = e;
}
}
}
let stream = connected.ok_or(last)?;
stream.set_nodelay(true)?;
let session = match tls {
Some(config) => match tls::connect(&stream, config, host).await {
Ok(session) => Some(session),
Err(e) => {
trace::info!("TLS handshake with {host}:{port} failed: {e}");
return Err(e);
}
},
None => None,
};
trace::info!(
"connected to {host}:{port}{}",
if session.is_some() { " with TLS" } else { "" }
);
let (reader, writer) = stream.into_split();
let conn = Arc::new(Connection {
endpoint: (host.to_owned(), port, session.is_some()),
inbound: Inbound::new(reader, session.clone(), max_message_size),
writer: tokio::sync::Mutex::new(writer),
tls: session,
pending: Mutex::new(Pending {
waiters: HashMap::new(),
closed: None,
}),
next_request_id: AtomicU32::new(0),
code_sets: Mutex::new(None),
closing: AtomicBool::new(false),
last_used: Stamp::new(),
pool,
});
tokio::spawn(read_loop(Arc::clone(&conn)));
Ok(conn)
}
pub(crate) fn endpoint(&self) -> &EndpointKey {
&self.endpoint
}
/// Whether the connection can take new requests.
pub(crate) fn is_usable(&self) -> bool {
!self.closing.load(Ordering::Acquire) && self.pending.lock().unwrap().closed.is_none()
}
pub(crate) fn next_request_id(&self) -> u32 {
self.next_request_id.fetch_add(1, Ordering::Relaxed)
}
/// The code sets already announced on this connection, if any.
pub(crate) fn code_sets(&self) -> Option<CodeSets> {
*self.code_sets.lock().unwrap()
}
/// Fixes the code sets of the connection to `proposed` unless an
/// earlier request fixed them, and returns the ones in force.
pub(crate) fn claim_code_sets(&self, proposed: CodeSets) -> CodeSets {
*self.code_sets.lock().unwrap().get_or_insert(proposed)
}
/// Registers a caller waiting for the reply to `request_id`.
pub(crate) fn expect_reply(
&self,
request_id: u32,
) -> Result<oneshot::Receiver<Delivery>, Closed> {
let mut pending = self.pending.lock().unwrap();
if let Some(closed) = &pending.closed {
return Err(closed.clone());
}
if self.closing.load(Ordering::Acquire) {
// Closed by this side with nothing outstanding: the request
// was not sent, and goes on a new connection.
return Err(Closed::Orderly);
}
self.last_used.touch();
let (tx, rx) = oneshot::channel();
pending.waiters.insert(request_id, tx);
Ok(rx)
}
/// Reads the reply to `request_id` on the calling thread, if it is the
/// only reply waited for: one thread hand-over less than through the
/// reader task. Replies to requests sent meanwhile are handed to their
/// callers. `None` when the caller is to wait for the reader task
/// after all (others wait too, the task is reading, or the connection
/// ended); `Some(None)` when `deadline` passed.
///
/// Blocks the thread; the caller is a thread of its own (the sync API
/// runs the call with `block_on` outside the runtime).
pub(crate) fn read_reply_here(
&self,
request_id: u32,
deadline: Option<Instant>,
) -> Option<Option<Message>> {
{
let pending = self.pending.lock().unwrap();
if pending.closed.is_some()
|| pending.waiters.len() != 1
|| !pending.waiters.contains_key(&request_id)
{
return None;
}
}
if !self.inbound.claim() {
return None;
}
// The reader task may have delivered the reply between the check
// above and the claim; it reads no more now.
if !self
.pending
.lock()
.unwrap()
.waiters
.contains_key(&request_id)
{
self.inbound.release();
return None;
}
loop {
let (version, message) = match self.inbound.read_here(deadline) {
Here::Message(version, message) => (version, message),
Here::TimedOut => return Some(None),
Here::HandedBack => return None,
};
let id = match &message {
Message::Reply { header, .. } => header.request_id,
Message::LocateReply { header, .. } => header.request_id,
_ => {
self.inbound.give_back(version, message);
return None;
}
};
if id == request_id {
self.inbound.release();
self.forget(request_id);
return Some(Some(message));
}
self.deliver(id, message);
}
}
/// Stops waiting for `request_id`, after a timeout.
pub(crate) fn forget(&self, request_id: u32) {
self.pending.lock().unwrap().waiters.remove(&request_id);
self.last_used.touch();
}
/// Chooses the connection to close if no reply is awaited, nothing
/// was sent or received for `timeout`, and no reply is being read.
/// From then on it takes no request ([`expect_reply`] and [`send`]
/// refuse them, to go on a new connection); the caller closes it
/// with [`close`](Self::close).
///
/// [`expect_reply`]: Self::expect_reply
/// [`send`]: Self::send
pub(crate) fn choose_idle(&self, timeout: Duration) -> bool {
let pending = self.pending.lock().unwrap();
if pending.closed.is_some()
|| !pending.waiters.is_empty()
|| self.closing.load(Ordering::Acquire)
|| self.last_used.idle_for() < timeout
|| self.inbound.mid_message()
{
return false;
}
self.closing.store(true, Ordering::Release);
true
}
/// Writes one whole message, giving up at `deadline`. A message cut
/// short by the deadline leaves the stream unusable, so the connection
/// is then closed; one not started leaves it as it was.
pub(crate) async fn send(
&self,
msg: &OutMessage,
deadline: Option<Instant>,
) -> Result<(), SendError> {
let mut writer = match deadline {
Some(at) => match tokio::time::timeout_at(at.into(), self.writer.lock()).await {
Ok(writer) => writer,
Err(_) => return Err(SendError::TimedOut),
},
None => self.writer.lock().await,
};
if self.closing.load(Ordering::Acquire) {
return Err(SendError::Closing);
}
self.last_used.touch();
trace::trace!("sent {} to {}", summary(msg), self.peer());
if let Some(tls) = &self.tls {
return self.send_tls(tls, &writer, msg, deadline).await;
}
let mut written = 0;
while written < msg.len() {
let (one, many);
let slices: &[IoSlice<'_>] = match msg.as_single() {
Some(bytes) => {
one = [IoSlice::new(&bytes[written..])];
&one
}
None => {
many = msg.slices_from(written, MAX_SLICES);
&many
}
};
let write = writer.write_vectored(slices);
let result = match deadline {
Some(at) => match tokio::time::timeout_at(at.into(), write).await {
Ok(result) => result,
Err(_) if written == 0 => return Err(SendError::TimedOut),
Err(_) => {
let _ = writer.shutdown().await;
drop(writer);
self.fail(Closed::Failed("write timed out".into()));
return Err(SendError::TimedOut);
}
},
None => write.await,
};
match result {
Ok(0) => {
drop(writer);
self.fail(Closed::Failed("write failed: stream closed".into()));
return Err(SendError::Failed);
}
Ok(n) => written += n,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => {
drop(writer);
self.fail(Closed::Failed(format!("write failed: {e}")));
return Err(SendError::Failed);
}
}
}
Ok(())
}
/// [`send`](Self::send) over TLS. The whole message is encrypted at
/// once and cannot be taken back, so a deadline passing before it is
/// written closes the connection: the server never gets the rest of
/// its last record.
async fn send_tls(
&self,
tls: &Tls,
writer: &OwnedWriteHalf,
msg: &OutMessage,
deadline: Option<Instant>,
) -> Result<(), SendError> {
tls.encrypt(msg, 0);
loop {
match tls.flush(|bytes| writer.try_write(bytes)) {
Ok(true) => return Ok(()),
Ok(false) => {}
Err(e) => {
self.fail(Closed::Failed(format!("write failed: {e}")));
return Err(SendError::Failed);
}
}
let writable = match deadline {
Some(at) => match tokio::time::timeout_at(at.into(), writer.writable()).await {
Ok(result) => result,
Err(_) => {
self.fail(Closed::Failed("write timed out".into()));
return Err(SendError::TimedOut);
}
},
None => writer.writable().await,
};
if let Err(e) = writable {
self.fail(Closed::Failed(format!("write failed: {e}")));
return Err(SendError::Failed);
}
}
}
/// Sends `CloseConnection` (when `version` is given) and shuts the
/// stream down. Requests issued afterwards use a new connection.
/// A peer that stopped reading gets [`CLOSE_TIME`] before the stream
/// is dropped without it.
///
/// An idle connection is closed without `CloseConnection`, which a
/// client sends only from GIOP 1.2 on: the server sees the stream end
/// with nothing outstanding, the orderly close of a client.
pub(crate) async fn close(&self, close_connection: Option<(Version, ByteOrder)>) {
self.closing.store(true, Ordering::Release);
trace::info!("closing the connection to {}", self.peer());
let msg = match close_connection {
Some((version, order)) => match MessageEncoder::close_connection(version, order) {
Ok(msg) => Some(msg),
Err(_) => return,
},
None => None,
};
let _ = tokio::time::timeout(CLOSE_TIME, async {
let mut writer = self.writer.lock().await;
match &self.tls {
Some(tls) => {
if let Some(msg) = msg {
tls.encrypt(&msg.into(), 0);
}
tls.close_notify();
while let Ok(false) = tls.flush(|bytes| writer.try_write(bytes)) {
if writer.writable().await.is_err() {
break;
}
}
}
None => {
if let Some(msg) = msg {
let _ = writer.write_all(&msg).await;
}
}
}
let _ = writer.shutdown().await;
})
.await;
}
/// Marks the connection closed and wakes every waiting caller.
fn fail(&self, why: Closed) {
let waiters = {
let mut pending = self.pending.lock().unwrap();
if pending.closed.is_none() {
pending.closed = Some(why.clone());
match &why {
_ if self.closing.load(Ordering::Acquire) => {
trace::info!("connection to {} closed", self.peer());
}
Closed::Orderly => {
trace::info!("{} closed the connection (CloseConnection)", self.peer())
}
Closed::Failed(e) => trace::info!("connection to {} lost: {e}", self.peer()),
}
}
std::mem::take(&mut pending.waiters)
};
// Ends the wait of a caller reading its reply.
self.inbound.shutdown();
for (_, tx) in waiters {
let _ = tx.send(Err(why.clone()));
}
}
/// `host:port` of the server, for trace lines.
fn peer(&self) -> Peer<'_> {
Peer(&self.endpoint)
}
fn deliver(&self, request_id: u32, msg: Message) {
self.last_used.touch();
let tx = self.pending.lock().unwrap().waiters.remove(&request_id);
if let Some(tx) = tx {
let _ = tx.send(Ok(msg));
}
}
}
/// The server of a connection in trace lines.
struct Peer<'a>(&'a EndpointKey);
impl std::fmt::Display for Peer<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (host, port, _) = self.0;
write!(f, "{host}:{port}")
}
}
/// The type, version and size of an outgoing message, for trace lines.
pub(crate) fn summary(msg: &OutMessage) -> trace::MessageSummary<'_> {
let head = msg.pieces().next().unwrap_or(&[]);
trace::MessageSummary(head, msg.len())
}
async fn read_loop(conn: Arc<Connection>) {
let why = match read_messages(&conn).await {
Ok(why) => why,
Err(e) => Closed::Failed(e),
};
conn.fail(why);
let _ = conn.writer.lock().await.shutdown().await;
// The socket closes once the last caller holding the connection is
// done with it.
if let Some(pool) = conn.pool.upgrade() {
let mut conns = pool.lock().unwrap();
if conns
.get(&conn.endpoint)
.is_some_and(|c| Arc::ptr_eq(c, &conn))
{
conns.remove(&conn.endpoint);
}
}
}
/// Reads messages until the stream ends. Returns how it ended.
async fn read_messages(conn: &Connection) -> Result<Closed, String> {
loop {
let (_, message) = match conn.inbound.next().await {
Ok(read) => read,
Err(ReadError::Closed(e)) if e.kind() == io::ErrorKind::UnexpectedEof => {
return Err("connection closed by the server".into());
}
Err(ReadError::Closed(e) | ReadError::Truncated(e)) => {
return Err(format!("read failed: {e}"));
}
Err(ReadError::BadHeader(e) | ReadError::Malformed(_, e)) => return Err(e),
Err(ReadError::TooLarge(total, _)) => {
return Err(format!("message of {total} bytes exceeds the limit"));
}
};
match message {
Message::Reply { ref header, .. } => conn.deliver(header.request_id, message),
Message::LocateReply { ref header, .. } => conn.deliver(header.request_id, message),
Message::CloseConnection => return Ok(Closed::Orderly),
Message::MessageError => return Err("the server sent MessageError".into()),
// A client connection is not bidirectional: requests from the
// server are not expected and are dropped.
Message::Request { .. }
| Message::LocateRequest(_)
| Message::CancelRequest(_)
| Message::Fragment { .. } => {}
}
}
}