unix_socket/lib.rs
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 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
//! Support for Unix domain socket clients and servers.
#![warn(missing_docs)]
#![doc(html_root_url="https://doc.rust-lang.org/unix-socket/doc/v0.5.0")]
extern crate libc;
use std::ascii;
use std::cmp::{self, Ordering};
use std::convert::AsRef;
use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::iter::IntoIterator;
use std::mem;
use std::net::Shutdown;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::{RawFd, AsRawFd, FromRawFd, IntoRawFd};
use std::path::Path;
use std::time::{Duration, Instant};
use libc::c_int;
fn sun_path_offset() -> usize {
unsafe {
// Work with an actual instance of the type since using a null pointer is UB
let addr: libc::sockaddr_un = mem::uninitialized();
let base = &addr as *const _ as usize;
let path = &addr.sun_path as *const _ as usize;
path - base
}
}
fn cvt(v: libc::c_int) -> io::Result<libc::c_int> {
if v < 0 {
Err(io::Error::last_os_error())
} else {
Ok(v)
}
}
fn cvt_s(v: libc::ssize_t) -> io::Result<libc::ssize_t> {
if v < 0 {
Err(io::Error::last_os_error())
} else {
Ok(v)
}
}
struct Inner(RawFd);
impl Drop for Inner {
fn drop(&mut self) {
unsafe {
libc::close(self.0);
}
}
}
impl Inner {
fn new(kind: libc::c_int) -> io::Result<Inner> {
unsafe { cvt(libc::socket(libc::AF_UNIX, kind, 0)).map(Inner) }
}
fn new_pair(kind: libc::c_int) -> io::Result<(Inner, Inner)> {
unsafe {
let mut fds = [0, 0];
try!(cvt(libc::socketpair(libc::AF_UNIX, kind, 0, fds.as_mut_ptr())));
Ok((Inner(fds[0]), Inner(fds[1])))
}
}
fn try_clone(&self) -> io::Result<Inner> {
unsafe { cvt(libc::dup(self.0)).map(Inner) }
}
fn shutdown(&self, how: Shutdown) -> io::Result<()> {
let how = match how {
Shutdown::Read => libc::SHUT_RD,
Shutdown::Write => libc::SHUT_WR,
Shutdown::Both => libc::SHUT_RDWR,
};
unsafe { cvt(libc::shutdown(self.0, how)).map(|_| ()) }
}
fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
let timeout = unsafe {
let mut timeout: libc::timeval = mem::zeroed();
let mut size = mem::size_of::<libc::timeval>() as libc::socklen_t;
try!(cvt(libc::getsockopt(self.0,
libc::SOL_SOCKET,
kind,
&mut timeout as *mut _ as *mut _,
&mut size as *mut _ as *mut _)));
timeout
};
if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
Ok(None)
} else {
Ok(Some(Duration::new(timeout.tv_sec as u64, (timeout.tv_usec as u32) * 1000)))
}
}
fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
let timeout = match dur {
Some(dur) => {
if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout"));
}
let (secs, usecs) = if dur.as_secs() > libc::time_t::max_value() as u64 {
(libc::time_t::max_value(), 999_999)
} else {
(dur.as_secs() as libc::time_t,
(dur.subsec_nanos() / 1000) as libc::suseconds_t)
};
let mut timeout = libc::timeval {
tv_sec: secs,
tv_usec: usecs,
};
if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
timeout.tv_usec = 1;
}
timeout
}
None => {
libc::timeval {
tv_sec: 0,
tv_usec: 0,
}
}
};
unsafe {
cvt(libc::setsockopt(self.0,
libc::SOL_SOCKET,
kind,
&timeout as *const _ as *const _,
mem::size_of::<libc::timeval>() as libc::socklen_t))
.map(|_| ())
}
}
fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
let mut nonblocking = nonblocking as libc::c_ulong;
unsafe { cvt(libc::ioctl(self.0, libc::FIONBIO, &mut nonblocking)).map(|_| ()) }
}
fn take_error(&self) -> io::Result<Option<io::Error>> {
let mut errno: libc::c_int = 0;
unsafe {
try!(cvt(libc::getsockopt(self.0,
libc::SOL_SOCKET,
libc::SO_ERROR,
&mut errno as *mut _ as *mut _,
&mut mem::size_of_val(&errno) as *mut _ as *mut _)));
}
if errno == 0 {
Ok(None)
} else {
Ok(Some(io::Error::from_raw_os_error(errno)))
}
}
}
unsafe fn sockaddr_un<P: AsRef<Path>>(path: P) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
let mut addr: libc::sockaddr_un = mem::zeroed();
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
let bytes = path.as_ref().as_os_str().as_bytes();
match (bytes.get(0), bytes.len().cmp(&addr.sun_path.len())) {
// Abstract paths don't need a null terminator
(Some(&0), Ordering::Greater) => {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"path must be no longer than SUN_LEN"));
}
(Some(&0), _) => {},
(_, Ordering::Greater) | (_, Ordering::Equal) => {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"path must be shorter than SUN_LEN"));
}
_ => {}
}
for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
*dst = *src as libc::c_char;
}
// null byte for pathname addresses is already there because we zeroed the
// struct
let mut len = sun_path_offset() + bytes.len();
match bytes.get(0) {
Some(&0) | None => {}
Some(_) => len += 1,
}
Ok((addr, len as libc::socklen_t))
}
enum AddressKind<'a> {
Unnamed,
Pathname(&'a Path),
Abstract(&'a [u8]),
}
/// An address associated with a Unix socket.
#[derive(Clone)]
pub struct SocketAddr {
addr: libc::sockaddr_un,
len: libc::socklen_t,
}
impl SocketAddr {
fn new<F>(f: F) -> io::Result<SocketAddr>
where F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int
{
unsafe {
let mut addr: libc::sockaddr_un = mem::zeroed();
let mut len = mem::size_of::<libc::sockaddr_un>() as libc::socklen_t;
try!(cvt(f(&mut addr as *mut _ as *mut _, &mut len)));
if len == 0 {
// When there is a datagram from unnamed unix socket
// linux returns zero bytes of address
len = sun_path_offset() as libc::socklen_t; // i.e. zero-length address
} else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"file descriptor did not correspond to a Unix socket"));
}
Ok(SocketAddr {
addr: addr,
len: len,
})
}
}
/// Returns true iff the address is unnamed.
pub fn is_unnamed(&self) -> bool {
if let AddressKind::Unnamed = self.address() {
true
} else {
false
}
}
/// Returns the contents of this address if it is a `pathname` address.
pub fn as_pathname(&self) -> Option<&Path> {
if let AddressKind::Pathname(path) = self.address() {
Some(path)
} else {
None
}
}
fn address<'a>(&'a self) -> AddressKind<'a> {
let len = self.len as usize - sun_path_offset();
let path = unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.addr.sun_path) };
// OSX seems to return a len of 16 and a zeroed sun_path for unnamed addresses
if len == 0 || (cfg!(not(target_os = "linux")) && self.addr.sun_path[0] == 0) {
AddressKind::Unnamed
} else if self.addr.sun_path[0] == 0 {
AddressKind::Abstract(&path[1..len])
} else {
AddressKind::Pathname(OsStr::from_bytes(&path[..len - 1]).as_ref())
}
}
}
impl fmt::Debug for SocketAddr {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.address() {
AddressKind::Unnamed => write!(fmt, "(unnamed)"),
AddressKind::Abstract(name) => write!(fmt, "{} (abstract)", AsciiEscaped(name)),
AddressKind::Pathname(path) => write!(fmt, "{:?} (pathname)", path),
}
}
}
struct AsciiEscaped<'a>(&'a [u8]);
impl<'a> fmt::Display for AsciiEscaped<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "\""));
for byte in self.0.iter().cloned().flat_map(ascii::escape_default) {
try!(write!(fmt, "{}", byte as char));
}
write!(fmt, "\"")
}
}
/// OS specific extension traits.
pub mod os {
/// Linux specific extension traits.
#[cfg(target_os = "linux")]
pub mod linux {
use {AddressKind, SocketAddr};
/// Linux specific extensions for the `SocketAddr` type.
pub trait SocketAddrExt {
/// Returns the contents of this address (without the leading
/// null byte) if it is an `abstract` address.
fn as_abstract(&self) -> Option<&[u8]>;
}
impl SocketAddrExt for SocketAddr {
fn as_abstract(&self) -> Option<&[u8]> {
if let AddressKind::Abstract(path) = self.address() {
Some(path)
} else {
None
}
}
}
}
}
/// A Unix stream socket.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
/// use std::io::prelude::*;
///
/// let mut stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// stream.write_all(b"hello world").unwrap();
/// let mut response = String::new();
/// stream.read_to_string(&mut response).unwrap();
/// println!("{}", response);
/// ```
pub struct UnixStream {
inner: Inner,
}
impl fmt::Debug for UnixStream {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut builder = fmt.debug_struct("UnixStream");
builder.field("fd", &self.inner.0);
if let Ok(addr) = self.local_addr() {
builder.field("local", &addr);
}
if let Ok(addr) = self.peer_addr() {
builder.field("peer", &addr);
}
builder.finish()
}
}
impl UnixStream {
/// Connects to the socket named by `path`.
///
/// Linux provides, as a nonportable extension, a separate "abstract"
/// address namespace as opposed to filesystem-based addressing. If `path`
/// begins with a null byte, it will be interpreted as an "abstract"
/// address. Otherwise, it will be interpreted as a "pathname" address,
/// corresponding to a path on the filesystem.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// ```
pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
unsafe {
let inner = try!(Inner::new(libc::SOCK_STREAM));
let (addr, len) = try!(sockaddr_un(path));
let ret = libc::connect(inner.0, &addr as *const _ as *const _, len);
if ret < 0 {
Err(io::Error::last_os_error())
} else {
Ok(UnixStream { inner: inner })
}
}
}
/// As `connect`, but time out after a specified duration.
pub fn connect_timeout<P: AsRef<Path>>(path: P, timeout: Duration) -> io::Result<UnixStream> {
let inner = try!(Inner::new(libc::SOCK_STREAM));
inner.set_nonblocking(true)?;
let r = unsafe {
let (addr, len) = try!(sockaddr_un(path));
let ret = libc::connect(inner.0, &addr as *const _ as *const _, len);
if ret < 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
};
inner.set_nonblocking(false)?;
match r {
Ok(_) => return Ok(UnixStream { inner: inner }),
// there's no ErrorKind for EINPROGRESS :(
Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
Err(e) => return Err(e),
}
let mut pollfd = libc::pollfd {
fd: inner.0,
events: libc::POLLOUT,
revents: 0,
};
if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
return Err(io::Error::new(io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout"));
}
let start = Instant::now();
loop {
let elapsed = start.elapsed();
if elapsed >= timeout {
return Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out"));
}
let timeout = timeout - elapsed;
let mut timeout = timeout.as_secs()
.saturating_mul(1_000)
.saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
if timeout == 0 {
timeout = 1;
}
let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int;
match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
-1 => {
let err = io::Error::last_os_error();
if err.kind() != io::ErrorKind::Interrupted {
return Err(err);
}
}
0 => {}
_ => {
// linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
// for POLLHUP rather than read readiness
if pollfd.revents & libc::POLLHUP != 0 {
let e = inner.take_error()?
.unwrap_or_else(|| {
io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
});
return Err(e);
}
return Ok(UnixStream { inner: inner });
}
}
}
}
/// Creates an unnamed pair of connected sockets.
///
/// Returns two `UnixStream`s which are connected to each other.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
///
/// let (stream1, stream2) = UnixStream::pair().unwrap();
/// ```
pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
let (i1, i2) = try!(Inner::new_pair(libc::SOCK_STREAM));
Ok((UnixStream { inner: i1 }, UnixStream { inner: i2 }))
}
/// Creates a new independently owned handle to the underlying socket.
///
/// The returned `UnixStream` is a reference to the same stream that this
/// object references. Both handles will read and write the same stream of
/// data, and options set on one stream will be propogated to the other
/// stream.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// let copy = stream.try_clone().unwrap();
/// ```
pub fn try_clone(&self) -> io::Result<UnixStream> {
Ok(UnixStream { inner: try!(self.inner.try_clone()) })
}
/// Returns the socket address of the local half of this connection.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// println!("{}", match stream.local_addr() {
/// Ok(addr) => format!("local address: {:?}", addr),
/// Err(_) => "no local address".to_owned(),
/// });
/// ```
pub fn local_addr(&self) -> io::Result<SocketAddr> {
SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.inner.0, addr, len) })
}
/// Returns the socket address of the remote half of this connection.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// println!("{}", match stream.peer_addr() {
/// Ok(addr) => format!("peer address: {:?}", addr),
/// Err(_) => "no peer address".to_owned(),
/// });
/// ```
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
SocketAddr::new(|addr, len| unsafe { libc::getpeername(self.inner.0, addr, len) })
}
/// Sets the read timeout for the socket.
///
/// If the provided value is `None`, then `read` calls will block
/// indefinitely. It is an error to pass the zero `Duration` to this
/// method.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
/// use std::time::Duration;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// stream.set_read_timeout(Some(Duration::from_millis(1500))).unwrap();
/// ```
pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
self.inner.set_timeout(timeout, libc::SO_RCVTIMEO)
}
/// Sets the write timeout for the socket.
///
/// If the provided value is `None`, then `write` calls will block
/// indefinitely. It is an error to pass the zero `Duration` to this
/// method.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
/// use std::time::Duration;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// stream.set_write_timeout(Some(Duration::from_millis(1500))).unwrap();
/// ```
pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
self.inner.set_timeout(timeout, libc::SO_SNDTIMEO)
}
/// Returns the read timeout of this socket.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// println!("{}", match stream.read_timeout() {
/// Ok(timeout) => format!("read timeout: {:?}", timeout),
/// Err(_) => "error".to_owned(),
/// });
/// ```
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
self.inner.timeout(libc::SO_RCVTIMEO)
}
/// Returns the write timeout of this socket.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// println!("{}", match stream.write_timeout() {
/// Ok(timeout) => format!("write timeout: {:?}", timeout),
/// Err(_) => "error".to_owned(),
/// });
/// ```
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
self.inner.timeout(libc::SO_SNDTIMEO)
}
/// Moves the socket into or out of nonblocking mode.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// stream.set_nonblocking(true).unwrap();
/// ```
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
self.inner.set_nonblocking(nonblocking)
}
/// Returns the value of the `SO_ERROR` option.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixStream;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// println!("{}", match stream.take_error() {
/// Ok(ret) => format!("error: {:?}", ret),
/// Err(_) => "error".to_owned(),
/// });
/// ```
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.inner.take_error()
}
/// Shuts down the read, write, or both halves of this connection.
///
/// This function will cause all pending and future I/O calls on the
/// specified portions to immediately return with an appropriate value
/// (see the documentation of `Shutdown`).
///
/// # Examples
///
/// ```rust,no_run
/// use std::net::Shutdown;
/// use unix_socket::UnixStream;
///
/// let stream = UnixStream::connect("/path/to/my/socket").unwrap();
/// stream.shutdown(Shutdown::Both).unwrap();
/// ```
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
self.inner.shutdown(how)
}
}
impl io::Read for UnixStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
io::Read::read(&mut &*self, buf)
}
}
impl<'a> io::Read for &'a UnixStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
unsafe {
cvt_s(libc::recv(self.inner.0, buf.as_mut_ptr() as *mut _, buf.len(), 0))
.map(|r| r as usize)
}
}
}
impl io::Write for UnixStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
io::Write::write(&mut &*self, buf)
}
fn flush(&mut self) -> io::Result<()> {
io::Write::flush(&mut &*self)
}
}
impl<'a> io::Write for &'a UnixStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
unsafe {
cvt_s(libc::send(self.inner.0, buf.as_ptr() as *const _, buf.len(), 0))
.map(|r| r as usize)
}
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl AsRawFd for UnixStream {
fn as_raw_fd(&self) -> RawFd {
self.inner.0
}
}
impl FromRawFd for UnixStream {
unsafe fn from_raw_fd(fd: RawFd) -> UnixStream {
UnixStream { inner: Inner(fd) }
}
}
impl IntoRawFd for UnixStream {
fn into_raw_fd(self) -> RawFd {
let fd = self.inner.0;
mem::forget(self);
fd
}
}
/// A structure representing a Unix domain socket server.
///
/// # Examples
///
/// ```rust,no_run
/// use std::thread;
/// use unix_socket::{UnixStream, UnixListener};
///
/// fn handle_client(stream: UnixStream) {
/// // ...
/// }
///
/// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
///
/// // accept connections and process them, spawning a new thread for each one
/// for stream in listener.incoming() {
/// match stream {
/// Ok(stream) => {
/// /* connection succeeded */
/// thread::spawn(|| handle_client(stream));
/// }
/// Err(err) => {
/// /* connection failed */
/// break;
/// }
/// }
/// }
///
/// // close the listener socket
/// drop(listener);
/// ```
pub struct UnixListener {
inner: Inner,
}
impl fmt::Debug for UnixListener {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut builder = fmt.debug_struct("UnixListener");
builder.field("fd", &self.inner.0);
if let Ok(addr) = self.local_addr() {
builder.field("local", &addr);
}
builder.finish()
}
}
impl UnixListener {
/// Creates a new `UnixListener` bound to the specified socket.
///
/// Linux provides, as a nonportable extension, a separate "abstract"
/// address namespace as opposed to filesystem-based addressing. If `path`
/// begins with a null byte, it will be interpreted as an "abstract"
/// address. Otherwise, it will be interpreted as a "pathname" address,
/// corresponding to a path on the filesystem.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixListener;
///
/// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
/// ```
pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
unsafe {
let inner = try!(Inner::new(libc::SOCK_STREAM));
let (addr, len) = try!(sockaddr_un(path));
try!(cvt(libc::bind(inner.0, &addr as *const _ as *const _, len)));
try!(cvt(libc::listen(inner.0, 128)));
Ok(UnixListener { inner: inner })
}
}
/// Accepts a new incoming connection to this listener.
///
/// This function will block the calling thread until a new Unix connection
/// is established. When established, the corersponding `UnixStream` and
/// the remote peer's address will be returned.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixListener;
///
/// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
/// let (client_stream, addr) = listener.accept().unwrap();
/// ```
pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
unsafe {
let mut fd = 0;
let addr = try!(SocketAddr::new(|addr, len| {
fd = libc::accept(self.inner.0, addr, len);
fd
}));
Ok((UnixStream { inner: Inner(fd) }, addr))
}
}
/// Creates a new independently owned handle to the underlying socket.
///
/// The returned `UnixListener` is a reference to the same socket that this
/// object references. Both handles can be used to accept incoming
/// connections and options set on one listener will affect the other.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixListener;
///
/// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
/// let copy = listener.try_clone().unwrap();
/// ```
pub fn try_clone(&self) -> io::Result<UnixListener> {
Ok(UnixListener { inner: try!(self.inner.try_clone()) })
}
/// Returns the local socket address of this listener.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixListener;
///
/// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
/// println!("{}", match listener.local_addr() {
/// Ok(addr) => format!("local address: {:?}", addr),
/// Err(_) => "no local address".to_owned(),
/// });
/// ```
pub fn local_addr(&self) -> io::Result<SocketAddr> {
SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.inner.0, addr, len) })
}
/// Moves the socket into or out of nonblocking mode.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixListener;
///
/// let mut listener = UnixListener::bind("/path/to/the/socket").unwrap();
/// listener.set_nonblocking(true).unwrap();
/// ```
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
self.inner.set_nonblocking(nonblocking)
}
/// Returns the value of the `SO_ERROR` option.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixListener;
///
/// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
/// println!("{}", match listener.take_error() {
/// Ok(ret) => format!("error: {:?}", ret),
/// Err(_) => "error".to_owned(),
/// });
/// ```
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.inner.take_error()
}
/// Returns an iterator over incoming connections.
///
/// The iterator will never return `None` and will also not yield the
/// peer's `SocketAddr` structure.
///
/// # Examples
///
/// ```rust,no_run
/// use std::thread;
/// use unix_socket::{UnixStream, UnixListener};
///
/// fn handle_client(stream: UnixStream) {
/// // ...
/// }
///
/// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
///
/// // accept connections and process them, spawning a new thread for each one
/// for stream in listener.incoming() {
/// match stream {
/// Ok(stream) => {
/// /* connection succeeded */
/// println!("incoming connection succeeded!");
/// thread::spawn(|| handle_client(stream));
/// }
/// Err(err) => {
/// /* connection failed */
/// println!("incoming connection failed...");
/// }
/// }
/// }
/// ```
pub fn incoming<'a>(&'a self) -> Incoming<'a> {
Incoming { listener: self }
}
}
impl AsRawFd for UnixListener {
fn as_raw_fd(&self) -> RawFd {
self.inner.0
}
}
impl FromRawFd for UnixListener {
unsafe fn from_raw_fd(fd: RawFd) -> UnixListener {
UnixListener { inner: Inner(fd) }
}
}
impl IntoRawFd for UnixListener {
fn into_raw_fd(self) -> RawFd {
let fd = self.inner.0;
mem::forget(self);
fd
}
}
impl<'a> IntoIterator for &'a UnixListener {
type Item = io::Result<UnixStream>;
type IntoIter = Incoming<'a>;
fn into_iter(self) -> Incoming<'a> {
self.incoming()
}
}
/// An iterator over incoming connections to a `UnixListener`.
///
/// It will never return `None`.
#[derive(Debug)]
pub struct Incoming<'a> {
listener: &'a UnixListener,
}
impl<'a> Iterator for Incoming<'a> {
type Item = io::Result<UnixStream>;
fn next(&mut self) -> Option<io::Result<UnixStream>> {
Some(self.listener.accept().map(|s| s.0))
}
fn size_hint(&self) -> (usize, Option<usize>) {
(usize::max_value(), None)
}
}
/// A Unix datagram socket.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// socket.send_to(b"hello world", "/path/to/other/socket").unwrap();
/// let mut buf = [0; 100];
/// let (count, address) = socket.recv_from(&mut buf).unwrap();
/// println!("socket {:?} sent us {:?}", address, &buf[..count]);
/// ```
pub struct UnixDatagram {
inner: Inner,
}
impl fmt::Debug for UnixDatagram {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let mut builder = fmt.debug_struct("UnixDatagram");
builder.field("fd", &self.inner.0);
if let Ok(addr) = self.local_addr() {
builder.field("local", &addr);
}
if let Ok(addr) = self.peer_addr() {
builder.field("peer", &addr);
}
builder.finish()
}
}
impl UnixDatagram {
/// Creates a Unix datagram socket bound to the given path.
///
/// Linux provides, as a nonportable extension, a separate "abstract"
/// address namespace as opposed to filesystem-based addressing. If `path`
/// begins with a null byte, it will be interpreted as an "abstract"
/// address. Otherwise, it will be interpreted as a "pathname" address,
/// corresponding to a path on the filesystem.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// ```
pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
unsafe {
let inner = try!(Inner::new(libc::SOCK_DGRAM));
let (addr, len) = try!(sockaddr_un(path));
try!(cvt(libc::bind(inner.0, &addr as *const _ as *const _, len)));
Ok(UnixDatagram { inner: inner })
}
}
/// Creates a Unix Datagram socket which is not bound to any address.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::unbound().unwrap();
/// ```
pub fn unbound() -> io::Result<UnixDatagram> {
let inner = try!(Inner::new(libc::SOCK_DGRAM));
Ok(UnixDatagram { inner: inner })
}
/// Create an unnamed pair of connected sockets.
///
/// Returns two `UnixDatagrams`s which are connected to each other.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let (socket1, socket2) = UnixDatagram::pair().unwrap();
/// ```
pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
let (i1, i2) = try!(Inner::new_pair(libc::SOCK_DGRAM));
Ok((UnixDatagram { inner: i1 }, UnixDatagram { inner: i2 }))
}
/// Connects the socket to the specified address.
///
/// The `send` method may be used to send data to the specified address.
/// `recv` and `recv_from` will only receive data from that address.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// socket.connect("/path/to/other/socket").unwrap();
/// ```
pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
unsafe {
let (addr, len) = try!(sockaddr_un(path));
try!(cvt(libc::connect(self.inner.0, &addr as *const _ as *const _, len)));
Ok(())
}
}
/// Creates a new independently owned handle to the underlying socket.
///
/// The returned `UnixListener` is a reference to the same socket that this
/// object references. Both handles can be used to accept incoming
/// connections and options set on one listener will affect the other.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::unbound().unwrap();
/// let copy = socket.try_clone().unwrap();
/// ```
pub fn try_clone(&self) -> io::Result<UnixDatagram> {
Ok(UnixDatagram { inner: try!(self.inner.try_clone()) })
}
/// Returns the address of this socket.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/the/socket").unwrap();
/// println!("{}", match socket.local_addr() {
/// Ok(addr) => format!("local address: {:?}", addr),
/// Err(_) => "no local address".to_owned(),
/// });
/// ```
pub fn local_addr(&self) -> io::Result<SocketAddr> {
SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.inner.0, addr, len) })
}
/// Returns the address of this socket's peer.
///
/// The `connect` method will connect the socket to a peer.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/the/socket").unwrap();
/// println!("{}", match socket.peer_addr() {
/// Ok(addr) => format!("peer address: {:?}", addr),
/// Err(_) => "no peer address".to_owned(),
/// });
/// ```
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
SocketAddr::new(|addr, len| unsafe { libc::getpeername(self.inner.0, addr, len) })
}
/// Receives data from the socket.
///
/// On success, returns the number of bytes read and the address from
/// whence the data came.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// let mut buf = [0; 100];
/// let (count, address) = socket.recv_from(&mut buf).unwrap();
/// println!("socket {:?} sent us {:?}", address, &buf[..count]);
/// ```
pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
let mut count = 0;
let addr = try!(SocketAddr::new(|addr, len| {
unsafe {
count = libc::recvfrom(self.inner.0,
buf.as_mut_ptr() as *mut _,
buf.len(),
0,
addr,
len);
if count > 0 {
1
} else if count == 0 {
0
} else {
-1
}
}
}));
Ok((count as usize, addr))
}
/// Receives data from the socket.
///
/// On success, returns the number of bytes read.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// socket.connect("/path/to/other/socket").unwrap();
/// let mut buf = [0; 100];
/// let count = socket.recv(&mut buf).unwrap();
/// println!("we received {:?}", &buf[..count]);
/// ```
pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
unsafe {
let count = try!(cvt_s(libc::recv(self.inner.0,
buf.as_mut_ptr() as *mut _,
buf.len(),
0)));
Ok(count as usize)
}
}
/// Sends data on the socket to the specified address.
///
/// On success, returns the number of bytes written.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
///
/// let mut data = b"hello world";
/// let mut sent = 0;
/// while sent < data.len() {
/// match socket.send_to(&data[sent..(data.len() - sent)], "/path/to/other/socket") {
/// Ok(data_sent) => { sent += data_sent; }
/// Err(_) => {
/// println!("an error occured while sending data...");
/// break;
/// }
/// }
/// }
/// ```
pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
unsafe {
let (addr, len) = try!(sockaddr_un(path));
let count = try!(cvt_s(libc::sendto(self.inner.0,
buf.as_ptr() as *const _,
buf.len(),
0,
&addr as *const _ as *const _,
len)));
Ok(count as usize)
}
}
/// Sends data on the socket to the socket's peer.
///
/// The peer address may be set by the `connect` method, and this method
/// will return an error if the socket has not already been connected.
///
/// On success, returns the number of bytes written.
///
/// # Examples
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// socket.connect("/path/to/other/socket").unwrap();
///
/// let mut data = b"hello world";
/// let mut sent = 0;
/// while sent < data.len() {
/// match socket.send(&data[sent..(data.len() - sent)]) {
/// Ok(data_sent) => { sent += data_sent; }
/// Err(_) => {
/// println!("an error occured while sending data...");
/// break;
/// }
/// }
/// }
/// ```
pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
unsafe {
let count = try!(cvt_s(libc::send(self.inner.0,
buf.as_ptr() as *const _,
buf.len(),
0)));
Ok(count as usize)
}
}
/// Sets the read timeout for the socket.
///
/// If the provided value is `None`, then `recv` and `recv_from` calls will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
/// use std::time::Duration;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// socket.set_read_timeout(Some(Duration::from_millis(1500))).unwrap();
/// ```
pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
self.inner.set_timeout(timeout, libc::SO_RCVTIMEO)
}
/// Sets the write timeout for the socket.
///
/// If the provided value is `None`, then `send` and `send_to` calls will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
/// use std::time::Duration;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// socket.set_write_timeout(Some(Duration::from_millis(1500))).unwrap();
/// ```
pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
self.inner.set_timeout(timeout, libc::SO_SNDTIMEO)
}
/// Returns the read timeout of this socket.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// println!("{}", match socket.read_timeout() {
/// Ok(timeout) => format!("read timeout: {:?}", timeout),
/// Err(_) => "error".to_owned(),
/// });
/// ```
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
self.inner.timeout(libc::SO_RCVTIMEO)
}
/// Returns the write timeout of this socket.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// println!("{}", match socket.write_timeout() {
/// Ok(timeout) => format!("write timeout: {:?}", timeout),
/// Err(_) => "error".to_owned(),
/// });
/// ```
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
self.inner.timeout(libc::SO_SNDTIMEO)
}
/// Moves the socket into or out of nonblocking mode.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// socket.set_nonblocking(true).unwrap();
/// ```
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
self.inner.set_nonblocking(nonblocking)
}
/// Returns the value of the `SO_ERROR` option.
///
/// # Example
///
/// ```rust,no_run
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/the/socket").unwrap();
/// println!("{}", match socket.take_error() {
/// Ok(ret) => format!("error: {:?}", ret),
/// Err(_) => "error".to_owned(),
/// });
/// ```
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.inner.take_error()
}
/// Shut down the read, write, or both halves of this connection.
///
/// This function will cause all pending and future I/O calls on the
/// specified portions to immediately return with an appropriate value
/// (see the documentation of `Shutdown`).
///
/// # Example
///
/// ```rust,no_run
/// use std::net::Shutdown;
/// use unix_socket::UnixDatagram;
///
/// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
/// socket.connect("/path/to/other/socket").unwrap();
/// socket.shutdown(Shutdown::Both).unwrap();
/// ```
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
self.inner.shutdown(how)
}
}
impl AsRawFd for UnixDatagram {
fn as_raw_fd(&self) -> RawFd {
self.inner.0
}
}
impl FromRawFd for UnixDatagram {
unsafe fn from_raw_fd(fd: RawFd) -> UnixDatagram {
UnixDatagram { inner: Inner(fd) }
}
}
impl IntoRawFd for UnixDatagram {
fn into_raw_fd(self) -> RawFd {
let fd = self.inner.0;
mem::forget(self);
fd
}
}
#[cfg(test)]
mod test {
extern crate tempdir;
extern crate libc;
use std::thread;
use std::io;
use std::io::prelude::*;
use std::time::Duration;
use self::tempdir::TempDir;
use std::net::Shutdown;
use super::*;
macro_rules! or_panic {
($e:expr) => {
match $e {
Ok(e) => e,
Err(e) => panic!("{}", e),
}
}
}
#[test]
fn basic() {
let dir = or_panic!(TempDir::new("unix_socket"));
let socket_path = dir.path().join("sock");
let msg1 = b"hello";
let msg2 = b"world!";
let listener = or_panic!(UnixListener::bind(&socket_path));
let thread = thread::spawn(move || {
let mut stream = or_panic!(listener.accept()).0;
let mut buf = [0; 5];
or_panic!(stream.read(&mut buf));
assert_eq!(&msg1[..], &buf[..]);
or_panic!(stream.write_all(msg2));
});
let mut stream = or_panic!(UnixStream::connect(&socket_path));
assert_eq!(Some(&*socket_path),
stream.peer_addr().unwrap().as_pathname());
or_panic!(stream.write_all(msg1));
let mut buf = vec![];
or_panic!(stream.read_to_end(&mut buf));
assert_eq!(&msg2[..], &buf[..]);
drop(stream);
thread.join().unwrap();
}
#[test]
fn pair() {
let msg1 = b"hello";
let msg2 = b"world!";
let (mut s1, mut s2) = or_panic!(UnixStream::pair());
let thread = thread::spawn(move || {
// s1 must be moved in or the test will hang!
let mut buf = [0; 5];
or_panic!(s1.read(&mut buf));
assert_eq!(&msg1[..], &buf[..]);
or_panic!(s1.write_all(msg2));
});
or_panic!(s2.write_all(msg1));
let mut buf = vec![];
or_panic!(s2.read_to_end(&mut buf));
assert_eq!(&msg2[..], &buf[..]);
drop(s2);
thread.join().unwrap();
}
#[test]
#[cfg(target_os = "linux")]
fn abstract_address() {
use os::linux::SocketAddrExt;
let socket_path = "\0the path";
let msg1 = b"hello";
let msg2 = b"world!";
let listener = or_panic!(UnixListener::bind(&socket_path));
let thread = thread::spawn(move || {
let mut stream = or_panic!(listener.accept()).0;
let mut buf = [0; 5];
or_panic!(stream.read(&mut buf));
assert_eq!(&msg1[..], &buf[..]);
or_panic!(stream.write_all(msg2));
});
let mut stream = or_panic!(UnixStream::connect(&socket_path));
assert_eq!(Some(&b"the path"[..]),
stream.peer_addr().unwrap().as_abstract());
or_panic!(stream.write_all(msg1));
let mut buf = vec![];
or_panic!(stream.read_to_end(&mut buf));
assert_eq!(&msg2[..], &buf[..]);
drop(stream);
thread.join().unwrap();
}
#[test]
#[cfg(target_os = "linux")]
fn abstract_address_max_len() {
use os::linux::SocketAddrExt;
use std::ffi::OsStr;
use std::io::Write;
use std::mem;
use std::os::unix::ffi::OsStrExt;
let len = unsafe {
let addr: libc::sockaddr_un = mem::zeroed();
addr.sun_path.len()
};
let mut socket_path = vec![0; len];
(&mut socket_path[1..9]).write_all(b"the path").unwrap();
let socket_path: &OsStr = OsStr::from_bytes(&socket_path).into();
let msg1 = b"hello";
let msg2 = b"world!";
let listener = or_panic!(UnixListener::bind(&socket_path));
let thread = thread::spawn(move || {
let mut stream = or_panic!(listener.accept()).0;
let mut buf = [0; 5];
or_panic!(stream.read(&mut buf));
assert_eq!(&msg1[..], &buf[..]);
or_panic!(stream.write_all(msg2));
});
let mut stream = or_panic!(UnixStream::connect(&socket_path));
assert_eq!(Some(&socket_path.as_bytes()[1..]),
stream.peer_addr().unwrap().as_abstract());
or_panic!(stream.write_all(msg1));
let mut buf = vec![];
or_panic!(stream.read_to_end(&mut buf));
assert_eq!(&msg2[..], &buf[..]);
drop(stream);
thread.join().unwrap();
}
#[test]
fn try_clone() {
let dir = or_panic!(TempDir::new("unix_socket"));
let socket_path = dir.path().join("sock");
let msg1 = b"hello";
let msg2 = b"world";
let listener = or_panic!(UnixListener::bind(&socket_path));
let thread = thread::spawn(move || {
let mut stream = or_panic!(listener.accept()).0;
or_panic!(stream.write_all(msg1));
or_panic!(stream.write_all(msg2));
});
let mut stream = or_panic!(UnixStream::connect(&socket_path));
let mut stream2 = or_panic!(stream.try_clone());
let mut buf = [0; 5];
or_panic!(stream.read(&mut buf));
assert_eq!(&msg1[..], &buf[..]);
or_panic!(stream2.read(&mut buf));
assert_eq!(&msg2[..], &buf[..]);
thread.join().unwrap();
}
#[test]
fn iter() {
let dir = or_panic!(TempDir::new("unix_socket"));
let socket_path = dir.path().join("sock");
let listener = or_panic!(UnixListener::bind(&socket_path));
let thread = thread::spawn(move || {
for stream in listener.incoming().take(2) {
let mut stream = or_panic!(stream);
let mut buf = [0];
or_panic!(stream.read(&mut buf));
}
});
for _ in 0..2 {
let mut stream = or_panic!(UnixStream::connect(&socket_path));
or_panic!(stream.write_all(&[0]));
}
thread.join().unwrap();
}
#[test]
fn long_path() {
let dir = or_panic!(TempDir::new("unix_socket"));
let socket_path = dir.path()
.join("asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfa\
sasdfasdfasdasdfasdfasdfadfasdfasdfasdfasdfasdf");
match UnixStream::connect(&socket_path) {
Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
Err(e) => panic!("unexpected error {}", e),
Ok(_) => panic!("unexpected success"),
}
match UnixListener::bind(&socket_path) {
Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
Err(e) => panic!("unexpected error {}", e),
Ok(_) => panic!("unexpected success"),
}
match UnixDatagram::bind(&socket_path) {
Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
Err(e) => panic!("unexpected error {}", e),
Ok(_) => panic!("unexpected success"),
}
}
#[test]
fn timeouts() {
let dir = or_panic!(TempDir::new("unix_socket"));
let socket_path = dir.path().join("sock");
let _listener = or_panic!(UnixListener::bind(&socket_path));
let stream = or_panic!(UnixStream::connect(&socket_path));
let dur = Duration::new(15410, 0);
assert_eq!(None, or_panic!(stream.read_timeout()));
or_panic!(stream.set_read_timeout(Some(dur)));
assert_eq!(Some(dur), or_panic!(stream.read_timeout()));
assert_eq!(None, or_panic!(stream.write_timeout()));
or_panic!(stream.set_write_timeout(Some(dur)));
assert_eq!(Some(dur), or_panic!(stream.write_timeout()));
or_panic!(stream.set_read_timeout(None));
assert_eq!(None, or_panic!(stream.read_timeout()));
or_panic!(stream.set_write_timeout(None));
assert_eq!(None, or_panic!(stream.write_timeout()));
}
#[test]
fn test_read_timeout() {
let dir = or_panic!(TempDir::new("unix_socket"));
let socket_path = dir.path().join("sock");
let _listener = or_panic!(UnixListener::bind(&socket_path));
let mut stream = or_panic!(UnixStream::connect(&socket_path));
or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
let mut buf = [0; 10];
let kind = stream.read(&mut buf).err().expect("expected error").kind();
assert!(kind == io::ErrorKind::WouldBlock || kind == io::ErrorKind::TimedOut);
}
#[test]
fn test_read_with_timeout() {
let dir = or_panic!(TempDir::new("unix_socket"));
let socket_path = dir.path().join("sock");
let listener = or_panic!(UnixListener::bind(&socket_path));
let mut stream = or_panic!(UnixStream::connect(&socket_path));
or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
let mut other_end = or_panic!(listener.accept()).0;
or_panic!(other_end.write_all(b"hello world"));
let mut buf = [0; 11];
or_panic!(stream.read(&mut buf));
assert_eq!(b"hello world", &buf[..]);
let kind = stream.read(&mut buf).err().expect("expected error").kind();
assert!(kind == io::ErrorKind::WouldBlock || kind == io::ErrorKind::TimedOut);
}
#[test]
fn test_unix_datagram() {
let dir = or_panic!(TempDir::new("unix_socket"));
let path1 = dir.path().join("sock1");
let path2 = dir.path().join("sock2");
let sock1 = or_panic!(UnixDatagram::bind(&path1));
let sock2 = or_panic!(UnixDatagram::bind(&path2));
let msg = b"hello world";
or_panic!(sock1.send_to(msg, &path2));
let mut buf = [0; 11];
or_panic!(sock2.recv_from(&mut buf));
assert_eq!(msg, &buf[..]);
}
#[test]
fn test_unnamed_unix_datagram() {
let dir = or_panic!(TempDir::new("unix_socket"));
let path1 = dir.path().join("sock1");
let sock1 = or_panic!(UnixDatagram::bind(&path1));
let sock2 = or_panic!(UnixDatagram::unbound());
let msg = b"hello world";
or_panic!(sock2.send_to(msg, &path1));
let mut buf = [0; 11];
let (usize, addr) = or_panic!(sock1.recv_from(&mut buf));
assert_eq!(usize, 11);
assert!(addr.is_unnamed());
assert_eq!(msg, &buf[..]);
}
#[test]
fn test_connect_unix_datagram() {
let dir = or_panic!(TempDir::new("unix_socket"));
let path1 = dir.path().join("sock1");
let path2 = dir.path().join("sock2");
let bsock1 = or_panic!(UnixDatagram::bind(&path1));
let bsock2 = or_panic!(UnixDatagram::bind(&path2));
let sock = or_panic!(UnixDatagram::unbound());
or_panic!(sock.connect(&path1));
// Check send()
let msg = b"hello there";
or_panic!(sock.send(msg));
let mut buf = [0; 11];
let (usize, addr) = or_panic!(bsock1.recv_from(&mut buf));
assert_eq!(usize, 11);
assert!(addr.is_unnamed());
assert_eq!(msg, &buf[..]);
// Changing default socket works too
or_panic!(sock.connect(&path2));
or_panic!(sock.send(msg));
or_panic!(bsock2.recv_from(&mut buf));
}
#[test]
fn test_unix_datagram_recv() {
let dir = or_panic!(TempDir::new("unix_socket"));
let path1 = dir.path().join("sock1");
let sock1 = or_panic!(UnixDatagram::bind(&path1));
let sock2 = or_panic!(UnixDatagram::unbound());
or_panic!(sock2.connect(&path1));
let msg = b"hello world";
or_panic!(sock2.send(msg));
let mut buf = [0; 11];
let size = or_panic!(sock1.recv(&mut buf));
assert_eq!(size, 11);
assert_eq!(msg, &buf[..]);
}
#[test]
fn datagram_pair() {
let msg1 = b"hello";
let msg2 = b"world!";
let (s1, s2) = or_panic!(UnixDatagram::pair());
let thread = thread::spawn(move || {
// s1 must be moved in or the test will hang!
let mut buf = [0; 5];
or_panic!(s1.recv(&mut buf));
assert_eq!(&msg1[..], &buf[..]);
or_panic!(s1.send(msg2));
});
or_panic!(s2.send(msg1));
let mut buf = [0; 6];
or_panic!(s2.recv(&mut buf));
assert_eq!(&msg2[..], &buf[..]);
drop(s2);
thread.join().unwrap();
}
#[test]
fn datagram_shutdown() {
let s1 = UnixDatagram::unbound().unwrap();
let s2 = s1.try_clone().unwrap();
let thread = thread::spawn(move || {
let mut buf = [0; 1];
assert_eq!(0, s1.recv_from(&mut buf).unwrap().0);
});
thread::sleep(Duration::from_millis(100));
s2.shutdown(Shutdown::Read).unwrap();;
thread.join().unwrap();
}
}