Vendor dependencies

This commit is contained in:
2026-08-01 16:11:49 +03:00
parent 7f139a0241
commit 6b5e7f0f8b
29706 changed files with 9575646 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"ea12f7eec27ffec3a11ddd3824163faf0976d24ee25d45fc422bd968cae30a98","Cargo.lock":"42cb360c4d4be269e2aa49d97424a93e53461e671a126197fa5c304ba2ad34b2","Cargo.toml":"9a0587d9daa54c4c1b91b8f2d9d617305d3371b8c74fd8d240452f84f7fb51b8","Cargo.toml.orig":"9c7d925cbd22b9bcb7af67857cb2f5a7b0ea9f8c75f1d96aff434d6836641518","LICENSE-APACHE2.0":"c93a7014a32c88c71551bd6fb4cae8cc9445c237d7e4a0774d4fc5e06089dbd9","LICENSE-MIT":"16c5a3cc951992b74de5f73206aa0005300fbe610708b76a25ca65006aab76d3","README.md":"08a0985b66272fde6d6966872072ce9059c310502c275c393ac0c006eb9d1a7e","examples/iterator.rs":"7c66eee565ea5f45182b1bcd80ee635b5b23221c3490a51099222897e2fae578","examples/lookup.rs":"36a142c52734d9530e7757a9763ed653c32cb09c04d6b858d0a99b19c8a7efea","examples/simple.rs":"44ccba226336865d0628343020d1c60bae9307d0432140e6ac961ab76c961452","src/iter/linux.rs":"75e5a059dc7261e67571aed9caca76ca4e5c9460eb14d0333041cd0fdf7d2dab","src/iter/mod.rs":"085d0849e31fa8f5fd219a767c80ab8094cd27574083ab701424910d16875236","src/iter/windows.rs":"e1fbe30dc728049e06f01a32a12f2e02cf233e33b4aa41aaef24f55cd4bb2f42","src/lib.rs":"56c4e39336c31eb38cb8a5971e8b698ecb4b82ee42c0023cba5f5dc4c3d39d93","src/linux.rs":"4e5b2f686e8b833ef7c7440ffda3e9e2ca3b3301717ea6cdeef71b4fd20c14d2","src/windows.rs":"40c48c12a6db504c06893635d5afdb0cc43226b8d3f438a3011de5fc96d131d0"},"package":"c0aeb26bf5e836cc1c341c8106051b573f1766dfa05aa87f0b98be5e51b02303"}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "9a1723346265a9fb04cc58c0995ca18b967c0a4a"
},
"path_in_vcs": ""
}
+175
View File
@@ -0,0 +1,175 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "bitflags"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cfg_aliases"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "itoa"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6"
[[package]]
name = "libc"
version = "0.2.169"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
[[package]]
name = "mac_address"
version = "1.1.8"
dependencies = [
"nix",
"serde",
"serde_json",
"serde_test",
"winapi",
]
[[package]]
name = "memoffset"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
dependencies = [
"autocfg",
]
[[package]]
name = "nix"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
dependencies = [
"bitflags",
"cfg-if",
"cfg_aliases",
"libc",
"memoffset",
]
[[package]]
name = "proc-macro2"
version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
dependencies = [
"proc-macro2",
]
[[package]]
name = "ryu"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
[[package]]
name = "serde"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.217"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.59"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcac07dbffa1c65e7f816ab9eba78eb142c6d44410f4eeba1e26e4f5dfa56b95"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "serde_test"
version = "1.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9a49e2f787c0fddfd5e758cbbd3cbf81c3a8d12ef091283c52d9e9b4d417d3c"
dependencies = [
"serde",
]
[[package]]
name = "syn"
version = "2.0.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+71
View File
@@ -0,0 +1,71 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
name = "mac_address"
version = "1.1.8"
authors = ["rep-nop <repnop@outlook.com>"]
build = false
exclude = ["/.github/"]
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Cross-platform retrieval of a network interface MAC address."
readme = "README.md"
keywords = [
"mac",
"address",
"network",
"interface",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/rep-nop/mac_address"
[lib]
name = "mac_address"
path = "src/lib.rs"
[[example]]
name = "iterator"
path = "examples/iterator.rs"
[[example]]
name = "lookup"
path = "examples/lookup.rs"
[[example]]
name = "simple"
path = "examples/simple.rs"
[dependencies.serde]
version = "1.0.198"
features = ["derive"]
optional = true
[dev-dependencies.serde_json]
version = "1.0.59"
[dev-dependencies.serde_test]
version = "1.0.117"
[target.'cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "android", target_os = "illumos"))'.dependencies.nix]
version = "0.29"
features = ["net"]
[target."cfg(windows)".dependencies.winapi]
version = "0.3"
features = [
"winerror",
"ws2def",
"iphlpapi",
]
+24
View File
@@ -0,0 +1,24 @@
[package]
name = "mac_address"
version = "1.1.8"
authors = ["rep-nop <repnop@outlook.com>"]
edition = "2018"
description = "Cross-platform retrieval of a network interface MAC address."
repository = "https://github.com/rep-nop/mac_address"
readme = "README.md"
license = "MIT OR Apache-2.0"
exclude = ["/.github/"]
keywords = ["mac", "address", "network", "interface"]
[dependencies]
serde = { version = "1.0.198", features = ["derive"], optional = true }
[target.'cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "android", target_os = "illumos"))'.dependencies]
nix = { version = "0.29", features = ["net"] }
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winerror", "ws2def", "iphlpapi"] }
[dev-dependencies]
serde_test = "1.0.117"
serde_json = "1.0.59"
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Wesley Norris
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+7
View File
@@ -0,0 +1,7 @@
Copyright © 2018 Wesley Norris
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+29
View File
@@ -0,0 +1,29 @@
# `mac_address`
[![crates.io](https://img.shields.io/crates/v/mac_address.svg)](https://crates.io/crates/mac_address)
[![Released API docs](https://docs.rs/mac_address/badge.svg)](https://docs.rs/mac_address)
`mac_address` provides a cross platform way to retrieve the [MAC address](https://en.wikipedia.org/wiki/MAC_address) of network hardware.
Supported platforms: Linux, Windows, MacOS, FreeBSD, OpenBSD, illumos
## Example
```rust
use mac_address::get_mac_address;
fn main() {
match get_mac_address() {
Ok(Some(ma)) => {
println!("MAC addr = {}", ma);
println!("bytes = {:?}", ma.bytes());
}
Ok(None) => println!("No MAC address found."),
Err(e) => println!("{:?}", e),
}
}
```
## License
`mac_address` is licensed under both MIT and Apache 2.0
+7
View File
@@ -0,0 +1,7 @@
use mac_address::MacAddressIterator;
fn main() {
for addr in MacAddressIterator::new().unwrap() {
println!("{}", addr);
}
}
+33
View File
@@ -0,0 +1,33 @@
use mac_address::mac_address_by_name;
fn main() {
#[cfg(any(target_os = "linux", target_os = "macos"))]
let name = "eth0";
#[cfg(target_os = "freebsd")]
let name = "em0";
#[cfg(target_os = "netbsd")]
let name = "igc0";
#[cfg(target_os = "openbsd")]
let name = "fxp0";
#[cfg(target_os = "windows")]
let name = "Ethernet";
#[cfg(target_os = "android")]
let name = "wlan0";
#[cfg(target_os = "illumos")]
let name = "igb0";
match mac_address_by_name(name) {
Ok(Some(ma)) => {
println!("MAC addr of {} = {}", name, ma);
println!("bytes = {:?}", ma.bytes());
}
Ok(None) => println!("Interface \"{}\" not found", name),
Err(e) => println!("{:?}", e),
}
}
+12
View File
@@ -0,0 +1,12 @@
use mac_address::get_mac_address;
fn main() {
match get_mac_address() {
Ok(Some(ma)) => {
println!("MAC addr = {}", ma);
println!("bytes = {:?}", ma.bytes());
}
Ok(None) => println!("No MAC address found."),
Err(e) => println!("{:?}", e),
}
}
+33
View File
@@ -0,0 +1,33 @@
use crate::{MacAddress, MacAddressError};
use nix::ifaddrs;
/// An iterator over all available MAC addresses on the system.
pub struct MacAddressIterator {
iter: std::iter::FilterMap<
ifaddrs::InterfaceAddressIterator,
fn(ifaddrs::InterfaceAddress) -> Option<MacAddress>,
>,
}
impl MacAddressIterator {
/// Creates a new `MacAddressIterator`.
pub fn new() -> Result<MacAddressIterator, MacAddressError> {
Ok(Self {
iter: ifaddrs::getifaddrs()?.filter_map(filter_macs),
})
}
}
fn filter_macs(intf: ifaddrs::InterfaceAddress) -> Option<MacAddress> {
intf.address?
.as_link_addr()
.and_then(|link| link.addr().map(MacAddress::new))
}
impl Iterator for MacAddressIterator {
type Item = MacAddress;
fn next(&mut self) -> Option<MacAddress> {
self.iter.next()
}
}
+17
View File
@@ -0,0 +1,17 @@
#[cfg(target_os = "windows")]
#[path = "windows.rs"]
mod internal;
#[cfg(any(
target_os = "linux",
target_os = "macos",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "android",
target_os = "illumos",
))]
#[path = "linux.rs"]
mod internal;
pub use internal::MacAddressIterator;
+47
View File
@@ -0,0 +1,47 @@
use crate::os;
use crate::{MacAddress, MacAddressError};
use winapi::um::iptypes::PIP_ADAPTER_ADDRESSES;
/// An iterator over all available MAC addresses on the system.
pub struct MacAddressIterator {
// So we don't UAF during iteration.
_buffer: os::AdaptersList,
ptr: PIP_ADAPTER_ADDRESSES,
}
impl MacAddressIterator {
/// Creates a new `MacAddressIterator`.
pub fn new() -> Result<MacAddressIterator, MacAddressError> {
let adapters = os::get_adapters()?;
let ptr = unsafe { adapters.ptr() };
Ok(Self {
_buffer: adapters,
ptr,
})
}
}
impl Iterator for MacAddressIterator {
type Item = MacAddress;
fn next(&mut self) -> Option<MacAddress> {
if self.ptr.is_null() {
None
} else {
let bytes = unsafe { os::convert_mac_bytes(self.ptr) };
#[cfg(target_pointer_width = "32")]
{
self.ptr = unsafe { self.ptr.read_unaligned().Next };
}
#[cfg(not(target_pointer_width = "32"))]
{
self.ptr = unsafe { (*self.ptr).Next };
}
Some(MacAddress::new(bytes))
}
}
}
+333
View File
@@ -0,0 +1,333 @@
//! `mac_address` provides a cross platform way to retrieve the MAC address of
//! network hardware. See [the Wikipedia
//! entry](https://en.wikipedia.org/wiki/MAC_address) for more information.
//!
//! Supported platforms: Linux, Windows, MacOS, FreeBSD, NetBSD
#![deny(missing_docs)]
#[cfg(target_os = "windows")]
#[path = "windows.rs"]
mod os;
#[cfg(any(
target_os = "linux",
target_os = "macos",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "android",
target_os = "illumos",
))]
#[path = "linux.rs"]
mod os;
mod iter;
pub use iter::MacAddressIterator;
/// Possible errors when attempting to retrieve a MAC address.
///
/// Eventually will expose more detailed error information.
#[derive(Debug)]
pub enum MacAddressError {
/// Signifies an internal API error has occurred.
InternalError,
}
#[cfg(any(
target_os = "linux",
target_os = "macos",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "android",
target_os = "illumos",
))]
impl From<nix::Error> for MacAddressError {
fn from(_: nix::Error) -> MacAddressError {
MacAddressError::InternalError
}
}
impl std::fmt::Display for MacAddressError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(match self {
MacAddressError::InternalError => "Internal API error",
})
}
}
impl std::error::Error for MacAddressError {}
/// An error that may occur when parsing a MAC address string.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum MacParseError {
/// Parsing of the MAC address contained an invalid digit.
InvalidDigit,
/// The MAC address did not have the correct length.
InvalidLength,
}
impl std::fmt::Display for MacParseError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(match *self {
MacParseError::InvalidDigit => "invalid digit",
MacParseError::InvalidLength => "invalid length",
})
}
}
impl std::error::Error for MacParseError {}
impl From<core::num::ParseIntError> for MacParseError {
fn from(_: core::num::ParseIntError) -> Self {
MacParseError::InvalidDigit
}
}
/// Contains the individual bytes of the MAC address.
#[derive(Debug, Clone, Copy, PartialEq, Default, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "std::borrow::Cow<'_, str>"))]
pub struct MacAddress {
bytes: [u8; 6],
}
impl MacAddress {
/// Creates a new `MacAddress` struct from the given bytes.
pub fn new(bytes: [u8; 6]) -> MacAddress {
MacAddress { bytes }
}
}
impl From<[u8; 6]> for MacAddress {
fn from(v: [u8; 6]) -> Self {
MacAddress::new(v)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for MacAddress {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(self)
}
}
/// Calls the OS-specific function for retrieving the MAC address of the first
/// network device containing one, ignoring local-loopback.
pub fn get_mac_address() -> Result<Option<MacAddress>, MacAddressError> {
let bytes = os::get_mac(None)?;
Ok(bytes.map(|b| MacAddress { bytes: b }))
}
/// Attempts to look up the MAC address of an interface via the specified name.
/// **NOTE**: On Windows, this uses the `FriendlyName` field of the adapter, which
/// is the same name shown in the "Network Connections" Control Panel screen.
pub fn mac_address_by_name(name: &str) -> Result<Option<MacAddress>, MacAddressError> {
let bytes = os::get_mac(Some(name))?;
Ok(bytes.map(|b| MacAddress { bytes: b }))
}
/// Attempts to look up the interface name via MAC address.
pub fn name_by_mac_address(mac: &MacAddress) -> Result<Option<String>, MacAddressError> {
os::get_ifname(&mac.bytes)
}
impl MacAddress {
/// Returns the array of MAC address bytes.
pub fn bytes(self) -> [u8; 6] {
self.bytes
}
}
impl std::str::FromStr for MacAddress {
type Err = MacParseError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let mut array = [0u8; 6];
// expect the `str` to be ASCII since it'll probably fail to parse
// anyway, this also asserts that each character in the string is only
// one byte in length which is necessary for the `match` below
if !input.is_ascii() {
// kind of hacky, but without `#[non_exhaustive]` on `MacParseError`
// adding a new variant is technically a breaking change, ugh...
return Err(MacParseError::InvalidLength);
}
match input.len() {
// MAC address with separators, e.g. 00:11:22:33:44:55
17 => {
array
.iter_mut()
.zip(input.split(|c| c == ':' || c == '-'))
.try_for_each::<_, Result<(), MacParseError>>(|(b, s)| {
*b = u8::from_str_radix(s, 16)?;
Ok(())
})?;
}
// MAC address without separators, e.g. 001122334455
12 => {
array
.iter_mut()
.zip((0..6).map(|i| &input[i * 2..=i * 2 + 1]))
.try_for_each::<_, Result<(), MacParseError>>(|(b, s)| {
*b = u8::from_str_radix(s, 16)?;
Ok(())
})?;
}
_ => return Err(MacParseError::InvalidLength),
}
Ok(MacAddress::new(array))
}
}
impl std::convert::TryFrom<&'_ str> for MacAddress {
type Error = MacParseError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
value.parse()
}
}
impl std::convert::TryFrom<std::borrow::Cow<'_, str>> for MacAddress {
type Error = MacParseError;
fn try_from(value: std::borrow::Cow<'_, str>) -> Result<Self, Self::Error> {
value.parse()
}
}
impl std::fmt::Display for MacAddress {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let _ = write!(
f,
"{:<02X}:{:<02X}:{:<02X}:{:<02X}:{:<02X}:{:<02X}",
self.bytes[0],
self.bytes[1],
self.bytes[2],
self.bytes[3],
self.bytes[4],
self.bytes[5]
);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_str_colon() {
let string = "80:FA:5B:41:10:6B";
let address = string.parse::<MacAddress>().unwrap();
assert_eq!(address.bytes(), [128, 250, 91, 65, 16, 107]);
assert_eq!(&format!("{}", address), string);
}
#[test]
fn parse_str_hyphen() {
let string = "01-23-45-67-89-AB";
let address = string.parse::<MacAddress>().unwrap();
assert_eq!(address.bytes(), [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB]);
assert_eq!(format!("{}", address), string.replace('-', ":"));
}
#[test]
fn parse_str_no_sep() {
let string = "4827e24425d8";
let address = string.parse::<MacAddress>().unwrap();
assert_eq!(address.bytes(), [0x48, 0x27, 0xE2, 0x44, 0x25, 0xD8]);
}
#[test]
fn parse_invalid_length() {
let string = "80:FA:5B:41:10:6B:AC";
let address = string.parse::<MacAddress>().unwrap_err();
assert_eq!(MacParseError::InvalidLength, address);
let string = "80:FA:5B:41";
let address = string.parse::<MacAddress>().unwrap_err();
assert_eq!(MacParseError::InvalidLength, address);
let string = "80FA5B41";
let address = string.parse::<MacAddress>().unwrap_err();
assert_eq!(MacParseError::InvalidLength, address);
let string = "80:FÁ:5B:41:10:6B";
let address = string.parse::<MacAddress>().unwrap_err();
assert_eq!(MacParseError::InvalidLength, address);
}
#[test]
fn parse_invalid_digit() {
let string = "80:FA:ZZ:41:10:6B";
let address = string.parse::<MacAddress>().unwrap_err();
assert_eq!(MacParseError::InvalidDigit, address);
}
#[test]
fn parse_invalid_separator() {
let string = "80|FA|AA|41|10|6B";
let address = string.parse::<MacAddress>().unwrap_err();
assert_eq!(MacParseError::InvalidDigit, address);
}
#[cfg(feature = "serde")]
#[test]
fn serde_works() {
use serde::{Deserialize, Serialize};
use serde_test::{assert_tokens, Token};
let mac: MacAddress = "80:FA:5B:41:10:6B".parse().unwrap();
assert_tokens(&mac, &[Token::BorrowedStr("80:FA:5B:41:10:6B")]);
#[derive(Serialize, Deserialize)]
struct Test {
mac: MacAddress,
}
assert_eq!(
serde_json::to_string(&Test { mac }).unwrap(),
serde_json::to_string::<Test>(
&serde_json::from_str("{ \"mac\": \"80:FA:5B:41:10:6B\" }").unwrap()
)
.unwrap(),
);
}
#[cfg(feature = "serde")]
#[test]
fn serde_from_reader_works() {
use serde::{Deserialize, Serialize};
let mac: MacAddress = "80:FA:5B:41:10:6B".parse().unwrap();
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Test {
mac: MacAddress,
}
assert_eq!(
Test { mac },
serde_json::from_reader(std::io::Cursor::new(r#"{ "mac": "80:FA:5B:41:10:6B" }"#))
.unwrap(),
);
}
#[test]
fn convert() {
for mac in MacAddressIterator::new().unwrap() {
let name = name_by_mac_address(&mac).unwrap().unwrap();
let mac2 = mac_address_by_name(&name).unwrap().unwrap();
assert_eq!(mac, mac2);
}
}
}
+49
View File
@@ -0,0 +1,49 @@
#![allow(dead_code)]
use crate::MacAddressError;
use nix::ifaddrs::*;
/// Uses the `getifaddrs` call to retrieve a list of network interfaces on the
/// host device and returns the first MAC address listed that isn't
/// local-loopback or if a name was specified, that name.
pub fn get_mac(name: Option<&str>) -> Result<Option<[u8; 6]>, MacAddressError> {
let ifiter = getifaddrs()?;
for interface in ifiter {
if let Some(iface_address) = interface.address {
if let Some(link) = iface_address.as_link_addr() {
let bytes = link.addr();
if let Some(name) = name {
if interface.interface_name == name {
return Ok(bytes);
}
} else if let Some(bytes) = bytes {
if bytes.iter().any(|&x| x != 0) {
return Ok(Some(bytes));
}
}
}
}
}
Ok(None)
}
pub fn get_ifname(mac: &[u8; 6]) -> Result<Option<String>, MacAddressError> {
let ifiter = getifaddrs()?;
for interface in ifiter {
if let Some(iface_address) = interface.address {
if let Some(link) = iface_address.as_link_addr() {
let bytes = link.addr();
if bytes == Some(*mac) {
return Ok(Some(interface.interface_name));
}
}
}
}
Ok(None)
}
+239
View File
@@ -0,0 +1,239 @@
use std::{
convert::{TryFrom, TryInto},
ffi::CStr,
ffi::OsString,
os::windows::ffi::OsStringExt,
ptr, slice,
};
use winapi::shared::{ntdef::ULONG, winerror::ERROR_SUCCESS, ws2def::AF_UNSPEC};
use winapi::um::{iphlpapi::GetAdaptersAddresses, iptypes::IP_ADAPTER_ADDRESSES_LH};
use crate::MacAddressError;
const GAA_FLAG_NONE: ULONG = 0x0000;
/// Uses bindings to the `Iphlpapi.h` Windows header to fetch the interface
/// devices list with
/// [GetAdaptersAddresses][https://msdn.microsoft.com/en-us/library/windows/desktop/aa365915(v=vs.85).aspx]
/// then loops over the returned list until it finds a network device with a MAC
/// address, and returns it.
///
/// If it fails to find a device, it returns a `NoDevicesFound` error.
pub fn get_mac(name: Option<&str>) -> Result<Option<[u8; 6]>, MacAddressError> {
let adapters = get_adapters()?;
// Safety: We don't use the pointer after `adapters` is dropped
let mut ptr = unsafe { adapters.ptr() };
loop {
// Break if we've gone through all devices
if ptr.is_null() {
break;
}
let bytes = unsafe { convert_mac_bytes(ptr) };
if let Some(name) = name {
#[cfg(not(target_pointer_width = "32"))]
let adapter_name = unsafe { construct_string((*ptr).FriendlyName) };
#[cfg(target_pointer_width = "32")]
let adapter_name = unsafe { construct_string(ptr.read_unaligned().FriendlyName) };
if adapter_name == name {
return Ok(Some(bytes));
} else {
#[cfg(not(target_pointer_width = "32"))]
let adapter_name = unsafe { CStr::from_ptr((*ptr).AdapterName) };
#[cfg(target_pointer_width = "32")]
let adapter_name = unsafe { CStr::from_ptr(ptr.read_unaligned().AdapterName) };
match adapter_name.to_str() {
Ok(s) if s == name => return Ok(Some(bytes)),
Ok(_) => {}
Err(_) => {
return Err(MacAddressError::InternalError);
}
}
}
} else if bytes.iter().any(|&x| x != 0) {
return Ok(Some(bytes));
}
// Otherwise go to the next device
#[cfg(target_pointer_width = "32")]
{
ptr = unsafe { ptr.read_unaligned().Next };
}
#[cfg(not(target_pointer_width = "32"))]
{
ptr = unsafe { (*ptr).Next };
}
}
Ok(None)
}
pub fn get_ifname(mac: &[u8; 6]) -> Result<Option<String>, MacAddressError> {
let adapters = get_adapters()?;
// Safety: We don't use the pointer after `adapters` is dropped
let mut ptr = unsafe { adapters.ptr() };
loop {
// Break if we've gone through all devices
if ptr.is_null() {
break;
}
let bytes = unsafe { convert_mac_bytes(ptr) };
if &bytes == mac {
#[cfg(not(target_pointer_width = "32"))]
let adapter_name = unsafe { construct_string((*ptr).FriendlyName) };
#[cfg(target_pointer_width = "32")]
let adapter_name = unsafe { construct_string(ptr.read_unaligned().FriendlyName) };
let adapter_name = adapter_name
.into_string()
.map_err(|_| MacAddressError::InternalError)?;
return Ok(Some(adapter_name));
}
// Otherwise go to the next device
#[cfg(target_pointer_width = "32")]
{
ptr = unsafe { ptr.read_unaligned().Next };
}
#[cfg(not(target_pointer_width = "32"))]
{
ptr = unsafe { (*ptr).Next };
}
}
Ok(None)
}
/// Copy over the 6 MAC address bytes to the buffer.
pub(crate) unsafe fn convert_mac_bytes(ptr: *mut IP_ADAPTER_ADDRESSES_LH) -> [u8; 6] {
#[cfg(target_pointer_width = "32")]
return ptr.read_unaligned().PhysicalAddress[..6]
.try_into()
.unwrap();
#[cfg(not(target_pointer_width = "32"))]
return ((*ptr).PhysicalAddress)[..6].try_into().unwrap();
}
pub(crate) struct AdaptersList {
ptr: *mut IP_ADAPTER_ADDRESSES_LH,
size: usize,
}
impl AdaptersList {
/// Safety: The pointer returned by this method MUST NOT be used after
/// `self` has gone out of scope. This pointer may also be null.
pub(crate) unsafe fn ptr(&self) -> *mut IP_ADAPTER_ADDRESSES_LH {
self.ptr
}
}
impl Drop for AdaptersList {
fn drop(&mut self) {
if !self.ptr.is_null() && self.size != 0 {
unsafe {
std::alloc::dealloc(
self.ptr as *mut u8,
std::alloc::Layout::from_size_align(
self.size,
core::mem::align_of::<IP_ADAPTER_ADDRESSES_LH>(),
)
.unwrap(),
)
};
}
}
}
pub(crate) fn get_adapters() -> Result<AdaptersList, MacAddressError> {
let mut buf_len = 0;
// This will get the number of bytes we need to allocate for all devices
unsafe {
GetAdaptersAddresses(
AF_UNSPEC as u32,
GAA_FLAG_NONE,
ptr::null_mut(),
ptr::null_mut(),
&mut buf_len,
);
}
if buf_len == 0 {
return Ok(AdaptersList {
ptr: ptr::null_mut(),
size: 0,
});
}
// Allocate `buf_len` bytes, and create a raw pointer to it with the correct alignment
// Safety:
let adapters_list: *mut IP_ADAPTER_ADDRESSES_LH = unsafe {
std::alloc::alloc(
std::alloc::Layout::from_size_align(
usize::try_from(buf_len).map_err(|_| MacAddressError::InternalError)?,
core::mem::align_of::<IP_ADAPTER_ADDRESSES_LH>(),
)
.unwrap(),
)
} as *mut IP_ADAPTER_ADDRESSES_LH;
// Get our list of adapters
let result = unsafe {
GetAdaptersAddresses(
// [IN] Family
AF_UNSPEC as u32,
// [IN] Flags
GAA_FLAG_NONE,
// [IN] Reserved
ptr::null_mut(),
// [INOUT] AdapterAddresses
adapters_list,
// [INOUT] SizePointer
&mut buf_len,
)
};
let adapters_list = AdaptersList {
ptr: adapters_list,
// Cast OK, we checked it above
size: buf_len as usize,
};
// Make sure we were successful
if result != ERROR_SUCCESS {
return Err(MacAddressError::InternalError);
}
Ok(adapters_list)
}
unsafe fn construct_string(ptr: *mut u16) -> OsString {
let slice = slice::from_raw_parts(ptr, get_null_position(ptr));
OsStringExt::from_wide(slice)
}
unsafe fn get_null_position(ptr: *mut u16) -> usize {
assert!(!ptr.is_null());
for i in 0.. {
if *ptr.offset(i) == 0 {
return i as usize;
}
}
unreachable!()
}