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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
// Take a look at the license at the top of the repository in the LICENSE file.
use crate::Cancellable;
use crate::Socket;
use crate::SocketAddress;
use glib::object::{Cast, IsA};
use glib::translate::*;
use std::cell::RefCell;
use std::mem::transmute;
#[cfg(all(not(unix), feature = "dox"))]
use std::os::raw::c_int;
#[cfg(all(not(windows), feature = "dox"))]
use std::os::raw::c_void;
use std::pin::Pin;
use std::ptr;
use futures_core::stream::Stream;
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
impl Socket {
/// Creates a new [`Socket`][crate::Socket] from a native file descriptor
/// or winsock SOCKET handle.
///
/// This reads all the settings from the file descriptor so that
/// all properties should work. Note that the file descriptor
/// will be set to non-blocking mode, independent on the blocking
/// mode of the [`Socket`][crate::Socket].
///
/// On success, the returned [`Socket`][crate::Socket] takes ownership of `fd`. On failure, the
/// caller must close `fd` themselves.
///
/// Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
/// descriptor. Instead, a GError will be set with code [`IOErrorEnum::Failed`][crate::IOErrorEnum::Failed]
/// ## `fd`
/// a native socket file descriptor.
///
/// # Returns
///
/// a [`Socket`][crate::Socket] or [`None`] on error.
/// Free the returned object with `g_object_unref()`.
#[cfg(any(unix, feature = "dox"))]
pub unsafe fn from_fd(fd: impl IntoRawFd) -> Result<Socket, glib::Error> {
let fd = fd.into_raw_fd();
let mut error = ptr::null_mut();
let ret = ffi::g_socket_new_from_fd(fd, &mut error);
if error.is_null() {
Ok(from_glib_full(ret))
} else {
Err(from_glib_full(error))
}
}
#[cfg(any(windows, feature = "dox"))]
pub unsafe fn from_socket(socket: impl IntoRawSocket) -> Result<Socket, glib::Error> {
let socket = socket.into_raw_socket();
let mut error = ptr::null_mut();
let ret = ffi::g_socket_new_from_fd(socket as i32, &mut error);
if error.is_null() {
Ok(from_glib_full(ret))
} else {
Err(from_glib_full(error))
}
}
}
#[cfg(any(unix, feature = "dox"))]
impl AsRawFd for Socket {
fn as_raw_fd(&self) -> RawFd {
unsafe { ffi::g_socket_get_fd(self.to_glib_none().0) as _ }
}
}
#[cfg(any(windows, feature = "dox"))]
impl AsRawSocket for Socket {
fn as_raw_socket(&self) -> RawSocket {
unsafe { ffi::g_socket_get_fd(self.to_glib_none().0) as _ }
}
}
pub trait SocketExtManual: Sized {
/// Receive data (up to `size` bytes) from a socket. This is mainly used by
/// connection-oriented sockets; it is identical to [`SocketExtManual::receive_from()`][crate::prelude::SocketExtManual::receive_from()]
/// with `address` set to [`None`].
///
/// For [`SocketType::Datagram`][crate::SocketType::Datagram] and [`SocketType::Seqpacket`][crate::SocketType::Seqpacket] sockets,
/// [`SocketExtManual::receive()`][crate::prelude::SocketExtManual::receive()] will always read either 0 or 1 complete messages from
/// the socket. If the received message is too large to fit in `buffer`, then
/// the data beyond `size` bytes will be discarded, without any explicit
/// indication that this has occurred.
///
/// For [`SocketType::Stream`][crate::SocketType::Stream] sockets, [`SocketExtManual::receive()`][crate::prelude::SocketExtManual::receive()] can return any
/// number of bytes, up to `size`. If more than `size` bytes have been
/// received, the additional data will be returned in future calls to
/// [`SocketExtManual::receive()`][crate::prelude::SocketExtManual::receive()].
///
/// If the socket is in blocking mode the call will block until there
/// is some data to receive, the connection is closed, or there is an
/// error. If there is no data available and the socket is in
/// non-blocking mode, a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error will be
/// returned. To be notified when data is available, wait for the
/// [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition.
///
/// On error -1 is returned and `error` is set accordingly.
/// ## `cancellable`
/// a `GCancellable` or [`None`]
///
/// # Returns
///
/// Number of bytes read, or 0 if the connection was closed by
/// the peer, or -1 on error
///
/// ## `buffer`
///
/// a buffer to read data into (which should be at least `size` bytes long).
#[doc(alias = "g_socket_receive")]
fn receive<B: AsMut<[u8]>, C: IsA<Cancellable>>(
&self,
buffer: B,
cancellable: Option<&C>,
) -> Result<usize, glib::Error>;
/// Receive data (up to `size` bytes) from a socket.
///
/// If `address` is non-[`None`] then `address` will be set equal to the
/// source address of the received packet.
/// `address` is owned by the caller.
///
/// See [`SocketExtManual::receive()`][crate::prelude::SocketExtManual::receive()] for additional information.
/// ## `cancellable`
/// a `GCancellable` or [`None`]
///
/// # Returns
///
/// Number of bytes read, or 0 if the connection was closed by
/// the peer, or -1 on error
///
/// ## `address`
/// a pointer to a [`SocketAddress`][crate::SocketAddress]
/// pointer, or [`None`]
///
/// ## `buffer`
///
/// a buffer to read data into (which should be at least `size` bytes long).
#[doc(alias = "g_socket_receive_from")]
fn receive_from<B: AsMut<[u8]>, C: IsA<Cancellable>>(
&self,
buffer: B,
cancellable: Option<&C>,
) -> Result<(usize, SocketAddress), glib::Error>;
/// This behaves exactly the same as [`SocketExtManual::receive()`][crate::prelude::SocketExtManual::receive()], except that
/// the choice of blocking or non-blocking behavior is determined by
/// the `blocking` argument rather than by `self`'s properties.
/// ## `blocking`
/// whether to do blocking or non-blocking I/O
/// ## `cancellable`
/// a `GCancellable` or [`None`]
///
/// # Returns
///
/// Number of bytes read, or 0 if the connection was closed by
/// the peer, or -1 on error
///
/// ## `buffer`
///
/// a buffer to read data into (which should be at least `size` bytes long).
#[doc(alias = "g_socket_receive_with_blocking")]
fn receive_with_blocking<B: AsMut<[u8]>, C: IsA<Cancellable>>(
&self,
buffer: B,
blocking: bool,
cancellable: Option<&C>,
) -> Result<usize, glib::Error>;
/// Tries to send `size` bytes from `buffer` on the socket. This is
/// mainly used by connection-oriented sockets; it is identical to
/// [`SocketExtManual::send_to()`][crate::prelude::SocketExtManual::send_to()] with `address` set to [`None`].
///
/// If the socket is in blocking mode the call will block until there is
/// space for the data in the socket queue. If there is no space available
/// and the socket is in non-blocking mode a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error
/// will be returned. To be notified when space is available, wait for the
/// [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition. Note though that you may still receive
/// [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] from [`SocketExtManual::send()`][crate::prelude::SocketExtManual::send()] even if you were previously
/// notified of a [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition. (On Windows in particular, this is
/// very common due to the way the underlying APIs work.)
///
/// On error -1 is returned and `error` is set accordingly.
/// ## `buffer`
/// the buffer
/// containing the data to send.
/// ## `cancellable`
/// a `GCancellable` or [`None`]
///
/// # Returns
///
/// Number of bytes written (which may be less than `size`), or -1
/// on error
#[doc(alias = "g_socket_send")]
fn send<B: AsRef<[u8]>, C: IsA<Cancellable>>(
&self,
buffer: B,
cancellable: Option<&C>,
) -> Result<usize, glib::Error>;
/// Tries to send `size` bytes from `buffer` to `address`. If `address` is
/// [`None`] then the message is sent to the default receiver (set by
/// [`SocketExt::connect()`][crate::prelude::SocketExt::connect()]).
///
/// See [`SocketExtManual::send()`][crate::prelude::SocketExtManual::send()] for additional information.
/// ## `address`
/// a [`SocketAddress`][crate::SocketAddress], or [`None`]
/// ## `buffer`
/// the buffer
/// containing the data to send.
/// ## `cancellable`
/// a `GCancellable` or [`None`]
///
/// # Returns
///
/// Number of bytes written (which may be less than `size`), or -1
/// on error
#[doc(alias = "g_socket_send_to")]
fn send_to<B: AsRef<[u8]>, P: IsA<SocketAddress>, C: IsA<Cancellable>>(
&self,
address: Option<&P>,
buffer: B,
cancellable: Option<&C>,
) -> Result<usize, glib::Error>;
/// This behaves exactly the same as [`SocketExtManual::send()`][crate::prelude::SocketExtManual::send()], except that
/// the choice of blocking or non-blocking behavior is determined by
/// the `blocking` argument rather than by `self`'s properties.
/// ## `buffer`
/// the buffer
/// containing the data to send.
/// ## `blocking`
/// whether to do blocking or non-blocking I/O
/// ## `cancellable`
/// a `GCancellable` or [`None`]
///
/// # Returns
///
/// Number of bytes written (which may be less than `size`), or -1
/// on error
#[doc(alias = "g_socket_send_with_blocking")]
fn send_with_blocking<B: AsRef<[u8]>, C: IsA<Cancellable>>(
&self,
buffer: B,
blocking: bool,
cancellable: Option<&C>,
) -> Result<usize, glib::Error>;
/// Returns the underlying OS socket object. On unix this
/// is a socket file descriptor, and on Windows this is
/// a Winsock2 SOCKET handle. This may be useful for
/// doing platform specific or otherwise unusual operations
/// on the socket.
///
/// # Returns
///
/// the file descriptor of the socket.
#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
#[doc(alias = "get_fd")]
#[doc(alias = "g_socket_get_fd")]
fn fd<T: FromRawFd>(&self) -> T;
#[cfg(any(windows, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(windows)))]
#[doc(alias = "get_socket")]
#[doc(alias = "g_socket_get_fd")]
fn socket<T: FromRawSocket>(&self) -> T;
#[doc(alias = "g_socket_create_source")]
fn create_source<F, C>(
&self,
condition: glib::IOCondition,
cancellable: Option<&C>,
name: Option<&str>,
priority: glib::Priority,
func: F,
) -> glib::Source
where
F: FnMut(&Self, glib::IOCondition) -> glib::Continue + 'static,
C: IsA<Cancellable>;
fn create_source_future<C: IsA<Cancellable>>(
&self,
condition: glib::IOCondition,
cancellable: Option<&C>,
priority: glib::Priority,
) -> Pin<Box<dyn std::future::Future<Output = glib::IOCondition> + 'static>>;
fn create_source_stream<C: IsA<Cancellable>>(
&self,
condition: glib::IOCondition,
cancellable: Option<&C>,
priority: glib::Priority,
) -> Pin<Box<dyn Stream<Item = glib::IOCondition> + 'static>>;
}
impl<O: IsA<Socket>> SocketExtManual for O {
fn receive<B: AsMut<[u8]>, C: IsA<Cancellable>>(
&self,
mut buffer: B,
cancellable: Option<&C>,
) -> Result<usize, glib::Error> {
let cancellable = cancellable.map(|c| c.as_ref());
let gcancellable = cancellable.to_glib_none();
let buffer = buffer.as_mut();
let buffer_ptr = buffer.as_mut_ptr();
let count = buffer.len();
unsafe {
let mut error = ptr::null_mut();
let ret = ffi::g_socket_receive(
self.as_ref().to_glib_none().0,
buffer_ptr,
count,
gcancellable.0,
&mut error,
);
if error.is_null() {
Ok(ret as usize)
} else {
Err(from_glib_full(error))
}
}
}
fn receive_from<B: AsMut<[u8]>, C: IsA<Cancellable>>(
&self,
mut buffer: B,
cancellable: Option<&C>,
) -> Result<(usize, SocketAddress), glib::Error> {
let cancellable = cancellable.map(|c| c.as_ref());
let gcancellable = cancellable.to_glib_none();
let buffer = buffer.as_mut();
let buffer_ptr = buffer.as_mut_ptr();
let count = buffer.len();
unsafe {
let mut error = ptr::null_mut();
let mut addr_ptr = ptr::null_mut();
let ret = ffi::g_socket_receive_from(
self.as_ref().to_glib_none().0,
&mut addr_ptr,
buffer_ptr,
count,
gcancellable.0,
&mut error,
);
if error.is_null() {
Ok((ret as usize, from_glib_full(addr_ptr)))
} else {
Err(from_glib_full(error))
}
}
}
fn receive_with_blocking<B: AsMut<[u8]>, C: IsA<Cancellable>>(
&self,
mut buffer: B,
blocking: bool,
cancellable: Option<&C>,
) -> Result<usize, glib::Error> {
let cancellable = cancellable.map(|c| c.as_ref());
let gcancellable = cancellable.to_glib_none();
let buffer = buffer.as_mut();
let buffer_ptr = buffer.as_mut_ptr();
let count = buffer.len();
unsafe {
let mut error = ptr::null_mut();
let ret = ffi::g_socket_receive_with_blocking(
self.as_ref().to_glib_none().0,
buffer_ptr,
count,
blocking.into_glib(),
gcancellable.0,
&mut error,
);
if error.is_null() {
Ok(ret as usize)
} else {
Err(from_glib_full(error))
}
}
}
fn send<B: AsRef<[u8]>, C: IsA<Cancellable>>(
&self,
buffer: B,
cancellable: Option<&C>,
) -> Result<usize, glib::Error> {
let cancellable = cancellable.map(|c| c.as_ref());
let gcancellable = cancellable.to_glib_none();
let (count, buffer_ptr) = {
let slice = buffer.as_ref();
(slice.len(), slice.as_ptr())
};
unsafe {
let mut error = ptr::null_mut();
let ret = ffi::g_socket_send(
self.as_ref().to_glib_none().0,
mut_override(buffer_ptr),
count,
gcancellable.0,
&mut error,
);
if error.is_null() {
Ok(ret as usize)
} else {
Err(from_glib_full(error))
}
}
}
fn send_to<B: AsRef<[u8]>, P: IsA<SocketAddress>, C: IsA<Cancellable>>(
&self,
address: Option<&P>,
buffer: B,
cancellable: Option<&C>,
) -> Result<usize, glib::Error> {
let cancellable = cancellable.map(|c| c.as_ref());
let gcancellable = cancellable.to_glib_none();
let (count, buffer_ptr) = {
let slice = buffer.as_ref();
(slice.len(), slice.as_ptr())
};
unsafe {
let mut error = ptr::null_mut();
let ret = ffi::g_socket_send_to(
self.as_ref().to_glib_none().0,
address.map(|p| p.as_ref()).to_glib_none().0,
mut_override(buffer_ptr),
count,
gcancellable.0,
&mut error,
);
if error.is_null() {
Ok(ret as usize)
} else {
Err(from_glib_full(error))
}
}
}
fn send_with_blocking<B: AsRef<[u8]>, C: IsA<Cancellable>>(
&self,
buffer: B,
blocking: bool,
cancellable: Option<&C>,
) -> Result<usize, glib::Error> {
let cancellable = cancellable.map(|c| c.as_ref());
let gcancellable = cancellable.to_glib_none();
let (count, buffer_ptr) = {
let slice = buffer.as_ref();
(slice.len(), slice.as_ptr())
};
unsafe {
let mut error = ptr::null_mut();
let ret = ffi::g_socket_send_with_blocking(
self.as_ref().to_glib_none().0,
mut_override(buffer_ptr),
count,
blocking.into_glib(),
gcancellable.0,
&mut error,
);
if error.is_null() {
Ok(ret as usize)
} else {
Err(from_glib_full(error))
}
}
}
#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
fn fd<T: FromRawFd>(&self) -> T {
unsafe { FromRawFd::from_raw_fd(ffi::g_socket_get_fd(self.as_ref().to_glib_none().0)) }
}
#[cfg(any(windows, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(windows)))]
fn socket<T: FromRawSocket>(&self) -> T {
unsafe {
FromRawSocket::from_raw_socket(ffi::g_socket_get_fd(self.as_ref().to_glib_none().0) as _)
}
}
fn create_source<F, C>(
&self,
condition: glib::IOCondition,
cancellable: Option<&C>,
name: Option<&str>,
priority: glib::Priority,
func: F,
) -> glib::Source
where
F: FnMut(&Self, glib::IOCondition) -> glib::Continue + 'static,
C: IsA<Cancellable>,
{
unsafe extern "C" fn trampoline<
O: IsA<Socket>,
F: FnMut(&O, glib::IOCondition) -> glib::Continue + 'static,
>(
socket: *mut ffi::GSocket,
condition: glib::ffi::GIOCondition,
func: glib::ffi::gpointer,
) -> glib::ffi::gboolean {
let func: &RefCell<F> = &*(func as *const RefCell<F>);
let mut func = func.borrow_mut();
(*func)(
Socket::from_glib_borrow(socket).unsafe_cast_ref(),
from_glib(condition),
)
.into_glib()
}
unsafe extern "C" fn destroy_closure<O, F>(ptr: glib::ffi::gpointer) {
let _ = Box::<RefCell<F>>::from_raw(ptr as *mut _);
}
let cancellable = cancellable.map(|c| c.as_ref());
let gcancellable = cancellable.to_glib_none();
unsafe {
let source = ffi::g_socket_create_source(
self.as_ref().to_glib_none().0,
condition.into_glib(),
gcancellable.0,
);
let trampoline = trampoline::<O, F> as glib::ffi::gpointer;
glib::ffi::g_source_set_callback(
source,
Some(transmute::<
_,
unsafe extern "C" fn(glib::ffi::gpointer) -> glib::ffi::gboolean,
>(trampoline)),
Box::into_raw(Box::new(RefCell::new(func))) as glib::ffi::gpointer,
Some(destroy_closure::<O, F>),
);
glib::ffi::g_source_set_priority(source, priority.into_glib());
if let Some(name) = name {
glib::ffi::g_source_set_name(source, name.to_glib_none().0);
}
from_glib_full(source)
}
}
fn create_source_future<C: IsA<Cancellable>>(
&self,
condition: glib::IOCondition,
cancellable: Option<&C>,
priority: glib::Priority,
) -> Pin<Box<dyn std::future::Future<Output = glib::IOCondition> + 'static>> {
let cancellable: Option<Cancellable> = cancellable.map(|c| c.as_ref()).cloned();
let obj = self.clone();
Box::pin(glib::SourceFuture::new(move |send| {
let mut send = Some(send);
obj.create_source(
condition,
cancellable.as_ref(),
None,
priority,
move |_, condition| {
let _ = send.take().unwrap().send(condition);
glib::Continue(false)
},
)
}))
}
fn create_source_stream<C: IsA<Cancellable>>(
&self,
condition: glib::IOCondition,
cancellable: Option<&C>,
priority: glib::Priority,
) -> Pin<Box<dyn Stream<Item = glib::IOCondition> + 'static>> {
let cancellable: Option<Cancellable> = cancellable.map(|c| c.as_ref()).cloned();
let obj = self.clone();
Box::pin(glib::SourceStream::new(move |send| {
let send = Some(send);
obj.create_source(
condition,
cancellable.as_ref(),
None,
priority,
move |_, condition| {
if send.as_ref().unwrap().unbounded_send(condition).is_err() {
glib::Continue(false)
} else {
glib::Continue(true)
}
},
)
}))
}
}
#[cfg(all(not(unix), feature = "dox"))]
pub trait IntoRawFd {
fn into_raw_fd(self) -> c_int;
}
#[cfg(all(not(unix), feature = "dox"))]
pub trait FromRawFd {
unsafe fn from_raw_fd(fd: c_int) -> Self;
}
#[cfg(all(not(unix), feature = "dox"))]
pub trait AsRawFd {
fn as_raw_fd(&self) -> RawFd;
}
#[cfg(all(not(unix), feature = "dox"))]
pub type RawFd = c_int;
#[cfg(all(not(windows), feature = "dox"))]
pub trait IntoRawSocket {
fn into_raw_socket(self) -> u64;
}
#[cfg(all(not(windows), feature = "dox"))]
pub trait FromRawSocket {
unsafe fn from_raw_socket(sock: u64) -> Self;
}
#[cfg(all(not(windows), feature = "dox"))]
pub trait AsRawSocket {
fn as_raw_socket(&self) -> RawSocket;
}
#[cfg(all(not(windows), feature = "dox"))]
pub type RawSocket = *mut c_void;