initial commit

This commit is contained in:
Adam Ierymenko
2023-09-05 16:47:56 -04:00
commit a4bd420d7c
8 changed files with 1390 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
.DS_Store
target
*.o
*.tmp
Generated
+321
View File
@@ -0,0 +1,321 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "base64"
version = "0.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "414dcefbc63d77c526a76b3afcf6fbb9b5e2791c19c3aa2297733208750c6e53"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "concurrent-queue"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62ec6771ecfa0762d24683ee5a32ad78487a3d3afdc0fb8cae19d2c5deb50b7c"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "core_affinity"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "622892f5635ce1fc38c8f16dfc938553ed64af482edb5e150bf4caedbfcb2304"
dependencies = [
"libc",
"num_cpus",
"winapi",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294"
dependencies = [
"cfg-if",
]
[[package]]
name = "hermit-abi"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b"
[[package]]
name = "libc"
version = "0.2.147"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
[[package]]
name = "log"
version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
[[package]]
name = "num-traits"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2"
dependencies = [
"autocfg",
]
[[package]]
name = "num_cpus"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43"
dependencies = [
"hermit-abi",
"libc",
]
[[package]]
name = "pin-project-lite"
version = "0.2.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
[[package]]
name = "polling"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b2d323e8ca7996b3e23126511a523f7e62924d93ecd5ae73b333815b0eb3dce"
dependencies = [
"autocfg",
"bitflags",
"cfg-if",
"concurrent-queue",
"libc",
"log",
"pin-project-lite",
"windows-sys",
]
[[package]]
name = "proc-macro2"
version = "1.0.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.188"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.188"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "signal-hook"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801"
dependencies = [
"libc",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1"
dependencies = [
"libc",
]
[[package]]
name = "syn"
version = "2.0.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c324c494eba9d92503e6f1ef2e6df781e78f6a7705a0202d9801b198807d518a"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "udwee"
version = "0.0.1"
dependencies = [
"core_affinity",
"libc",
"num-traits",
"polling",
"zerotier-common-utils",
]
[[package]]
name = "unicode-ident"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c"
[[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"
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "zeroize"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zerotier-common-utils"
version = "0.1.0"
source = "git+https://github.com/zerotier/common-utils.git?branch=main#c24a5b1dbf50f3c25cbba5a43c0f927026144f08"
dependencies = [
"base64",
"libc",
"serde",
"signal-hook",
"winapi",
"zeroize",
]
+15
View File
@@ -0,0 +1,15 @@
[package]
authors = ["ZeroTier, Inc. <contact@zerotier.com>"]
edition = "2021"
license = "MPL-2.0"
name = "udwee"
version = "0.0.1"
[dependencies]
num-traits = "^0"
zerotier-common-utils = { git = "https://github.com/zerotier/common-utils.git", branch = "main" }
core_affinity = "^0"
polling = "^2"
[target."cfg(not(windows))".dependencies]
libc = "^0"
+373
View File
@@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+10
View File
@@ -0,0 +1,10 @@
UDWee
======
UDWee makes UDP go *weeeeeeeeee* as in really fast. It uses the following approaches on each platform:
* macOS / BSD: SO_REUSEPORT and thread-per-core I/O.
* Linux: SO_REUSEPORT and thread-per-core with `recvmmsg` and `sendmmsg` (and io_uring possibly in the future)
* Windows: TBD
It's designed for use with ZeroTier but can be used by other projects as well. The `InetAddress` class from the ZeroTier common utilities crate is used instead of the usual `SocketAddr` as it can easily be cast to/from the low-level OS `sockaddr` structures, but it implements into/from traits for `SocketAddr` and friends.
+16
View File
@@ -0,0 +1,16 @@
#unstable_features = true
max_width = 120
#use_small_heuristics = "Max"
edition = "2021"
#empty_item_single_line = true
newline_style = "Unix"
struct_lit_width = 60
tab_spaces = 4
use_small_heuristics = "Default"
#fn_single_line = true
#hex_literal_case = "Lower"
#merge_imports = false
group_imports = "StdExternalCrate"
single_line_if_else_max_width = 0
use_try_shorthand = true
imports_granularity = "Module"
+463
View File
@@ -0,0 +1,463 @@
mod os_socket;
use std::collections::HashSet;
use std::error::Error;
use std::mem::size_of;
use std::os::fd::RawFd;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::thread::JoinHandle;
use std::time::Duration;
#[allow(unused_imports)]
use num_traits::AsPrimitive;
use polling::{Event, Poller};
use zerotier_common_utils::inetaddress::InetAddress;
/// Trait to be implemented to handle packets read from UDP sockets.
pub trait PacketHandler: Send + Sync + Sized + 'static {
/// Data type for buffers passed in and out of the UDP I/O engine.
///
/// This is commonly Box<[u8]> or similar. It should be a thin pointer and not a whole literal
/// buffer to avoid a lot of memory copying.
type Buffer: AsMut<[u8]> + Send;
/// A cloneable reference to the handler, typically Arc<...>.
type Ref: AsRef<Self> + Send + Clone;
/// Data type for arbitrary data to attach to a socket.
///
/// It must be safe an efficient to clone this since a copy will be distributed to each
/// worker thread. This would typically be a small bit of static data or an Arc<> or Weak<>.
///
/// Use () if this is not needed.
type SocketApplicationData: Send + Clone;
/// Obtain a buffer to receive a new packet.
///
/// The buffer's contents do not need to be zeroed prior to being used. Its as_mut() function
/// must return a slice large enough to receive a UDP packet or packets will be lost.
fn get_buffer(&self) -> Self::Buffer;
/// Called by the engine to return a buffer after a send completes (or fails).
///
/// This isn't called after on_udp_packet() since that handler takes ownership of the buffer.
/// If you are doing pooling you could instead call this internally inside on_udp_packet when
/// processing is complete.
///
/// The default implementation is a no-op. Override if needed to e.g. return buffers to a pool.
#[allow(unused_variables)]
fn return_buffer(&self, buffer: Self::Buffer) {}
/// Called whan a UDP packet is received.
///
/// This is called directly (and concurrently) from the actual I/O thread(s) internal
/// to the engine. It therefore should never do anything time consuming unless you are
/// okay with blocking engine threads. Queues or channels can be used to send packets
/// elsewhere for processing. This also works for interoperability with async code.
fn on_udp_packet(&self, socket: &UdpSocket<Self>, remote_address: &InetAddress, data: Self::Buffer, len: usize);
}
/// Fast UDP I/O engine.
pub struct Engine<H: PacketHandler> {
threads: Vec<Arc<EngineThread<H>>>,
bound: Mutex<HashSet<InetAddress>>,
}
/// Bound UDP socket handle.
///
/// UdpSocket doesn't implement Clone because the socket returned from bind() is meant to
/// uniquely represent the socket in the application. Shadow socket instances are also created
/// internally to supply each thread with one to give to on_udp_packet() to send packets within
/// a receive handler, but these are not "canonical" and cloning them would create confusion.
///
/// Wrapping the returned socket in Rc<> or Arc<> is fine if you want auto-GC inside your
/// application.
pub struct UdpSocket<H: PacketHandler> {
fd: RawFd,
/// Unique internal ID (not a file descriptor) for this socket.
pub id: usize,
/// Local address to which this socket is bound.
pub local_address: InetAddress,
/// Handler supplied when opening this socket.
pub handler: H::Ref,
/// Arbitrary application data attached to socket.
pub data: H::SocketApplicationData,
}
/// Commands that can be sent to worker threads.
enum ThreadCommand<H: PacketHandler> {
Open(UdpSocket<H>),
Close(usize),
Shutdown,
}
/// State information for each worker thread.
struct EngineThread<H: PacketHandler> {
poller: Poller,
commands: Mutex<Vec<ThreadCommand<H>>>,
thread: JoinHandle<()>,
}
impl<H: PacketHandler> Engine<H> {
/// Create a new engine.
pub fn new() -> Self {
let wait_for_arc_init = |self_ref: Weak<EngineThread<H>>| loop {
if let Some(self_ref) = self_ref.upgrade() {
self_ref.thread_main();
break;
} else {
// wait for self_ref to be fully constructed by Arc::new_cyclic()
std::thread::sleep(Duration::from_millis(1));
}
};
Self {
threads: if let Some(core_ids) = core_affinity::get_core_ids() {
assert!(core_ids.len() > 0);
core_ids
.into_iter()
.map(|core_id| {
Arc::new_cyclic(|self_ref: &Weak<EngineThread<H>>| {
let self_ref = self_ref.clone();
EngineThread {
poller: Poller::new().unwrap(),
commands: Mutex::new(Vec::with_capacity(8)),
thread: std::thread::spawn(move || {
core_affinity::set_for_current(core_id);
wait_for_arc_init(self_ref);
}),
}
})
})
.collect()
} else {
let hw_par = std::thread::available_parallelism().unwrap().get();
let mut threads = Vec::with_capacity(hw_par);
for _ in 0..hw_par {
threads.push(Arc::new_cyclic(|self_ref: &Weak<EngineThread<H>>| {
let self_ref = self_ref.clone();
EngineThread {
poller: Poller::new().unwrap(),
commands: Mutex::new(Vec::with_capacity(8)),
thread: std::thread::spawn(move || wait_for_arc_init(self_ref)),
}
}))
}
threads
},
bound: Mutex::new(HashSet::new()),
}
}
/// Bind a UDP socket to a local address.
///
/// The returned UdpSocket must be closed explicitly with close() when the application is
/// finished with it.
///
/// Packets are sent via the returned socket object. When packets are received the handler
/// will be called directly.
///
/// * `bind_address`: Local IP address and port
/// * `bind_to_device`: If specified, bind to a network interface (platform-specific, mainly Linux)
/// * `v6only`: If true IPv6 sockets bound to ::0 should only receive IPv6 datagrams.
/// * `handler`: Reference to handler instance for packets read from this socket.
/// * `data`: Arbitrary data to attach to socket.
pub fn bind(
&self,
bind_address: &InetAddress,
bind_to_device: Option<&str>,
v6only: bool,
handler: H::Ref,
data: H::SocketApplicationData,
) -> Result<UdpSocket<H>, Box<dyn Error>> {
// Counter used to assign each UdpSocket an internally unique ID.
static ID_COUNTER: AtomicUsize = AtomicUsize::new(1);
let mut bound = self.bound.lock().unwrap(); // also serializes calls to bind()
if bound.contains(bind_address) {
return Err(Box::new(std::io::Error::new(
std::io::ErrorKind::AddrNotAvailable,
"already bound to this address",
)));
}
let mut fds = Vec::with_capacity(self.threads.len());
for _ in 0..self.threads.len() {
match unsafe { crate::os_socket::bind_udp(bind_address, bind_to_device, true, v6only, true) } {
Ok(fd) => fds.push(fd),
Err(desc) => {
for fd in fds.iter() {
unsafe { libc::close(*fd) };
}
return Err(Box::new(std::io::Error::new(
std::io::ErrorKind::AddrNotAvailable,
desc,
)));
}
}
}
let id = ID_COUNTER.fetch_add(1, Ordering::SeqCst);
bound.insert(bind_address.clone());
for (t, fd) in self.threads.iter().zip(fds.iter()) {
t.commands.lock().unwrap().push(ThreadCommand::Open(UdpSocket {
fd: *fd,
id,
local_address: bind_address.clone(),
handler: handler.clone(),
data: data.clone(),
}));
let _ = t.poller.notify();
}
Ok(UdpSocket {
fd: *fds.first().unwrap(),
id,
local_address: bind_address.clone(),
handler,
data,
})
}
/// Close a socket.
///
/// Note that it's possible for a few packets to continue to be received on this socket
/// until all threads have had a chance to receive a close command for it.
pub fn close(&self, socket: UdpSocket<H>) {
if self.bound.lock().unwrap().remove(&socket.local_address) {
for t in self.threads.iter() {
t.commands.lock().unwrap().push(ThreadCommand::Close(socket.id));
let _ = t.poller.notify();
}
}
}
}
impl<H: PacketHandler> Drop for Engine<H> {
fn drop(&mut self) {
for t in self.threads.drain(..) {
t.commands.lock().unwrap().insert(0, ThreadCommand::Shutdown); // tell thread to exit
loop {
let _ = t.poller.notify();
if t.thread.is_finished() {
break;
} else {
std::thread::sleep(Duration::from_millis(1));
}
}
}
}
}
impl<H: PacketHandler> EngineThread<H> {
fn thread_main(&self) {
let mut events = Vec::with_capacity(16);
let mut commands = Vec::with_capacity(16);
let mut sockets: Vec<Pin<Box<UdpSocket<H>>>> = Vec::with_capacity(16);
let mut from_address = InetAddress::new();
loop {
if self.poller.wait(&mut events, None).is_err() {
panic!("polling failed");
}
for ev in events.iter() {
match ev {
Event { key, readable, writable: _writable } => {
if *readable {
let d: &UdpSocket<H> = unsafe { &*(*key as *const UdpSocket<H>) };
let handler = d.handler.as_ref();
loop {
let mut buf = handler.get_buffer();
let buf_inner = buf.as_mut();
let mut addrlen = size_of::<InetAddress>() as libc::socklen_t;
let packet_size = unsafe {
libc::recvfrom(
d.fd,
buf_inner.as_mut_ptr().cast(),
buf_inner.len().as_(),
0,
(&mut from_address as *mut InetAddress).cast(),
(&mut addrlen as *mut libc::socklen_t).cast(),
) as isize
};
if packet_size >= 0 {
handler.on_udp_packet(d, &from_address, buf, packet_size as usize);
} else {
break;
}
}
let _ = self
.poller
.modify(d.fd, Event { key: *key, readable: true, writable: false });
}
}
}
}
events.clear();
std::mem::swap(self.commands.lock().unwrap().as_mut(), &mut commands);
for command in commands.drain(..) {
match command {
ThreadCommand::Open(socket) => {
let fd = socket.fd;
sockets.push(Box::pin(socket));
self.poller
.add(
fd,
Event {
key: (&*sockets.last().unwrap().as_ref() as *const UdpSocket<H>) as usize,
readable: true,
writable: false,
},
)
.unwrap();
}
ThreadCommand::Close(id) => sockets.retain(|d| {
if d.id == id {
self.poller.delete(d.fd).unwrap();
unsafe { libc::close(d.fd) };
false
} else {
true
}
}),
ThreadCommand::Shutdown => {
for d in sockets.iter() {
unsafe { libc::close(d.fd) };
}
return;
}
}
}
}
}
}
impl<H: PacketHandler> UdpSocket<H> {
/// Send a packet over this socket.
///
/// This doesn't provide a return value because (1) UDP does not guarantee delivery anyway
/// and (2) on some platforms a queue might be used to batch sends and so no feedback will
/// be immediately available.
///
/// Attempting to send on a socket after the engine that created it has been dropped will
/// either silently fail or panic depending on the implementation.
#[inline]
pub fn send(&self, dest: &InetAddress, mut data: H::Buffer, len: usize) {
// Basic implementation for most platforms.
unsafe {
libc::sendto(
self.fd,
data.as_mut().as_ptr().cast(),
len.as_(),
0,
(dest as *const InetAddress).cast(),
size_of::<InetAddress>().as_(),
);
self.handler.as_ref().return_buffer(data);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::AtomicU64;
#[derive(Default)]
struct TestHandler {
pool: Mutex<Vec<Box<[u8]>>>,
received: AtomicU64,
echo: bool,
}
impl PacketHandler for TestHandler {
type Buffer = Box<[u8]>;
type Ref = Arc<Self>;
type SocketApplicationData = ();
fn get_buffer(&self) -> Self::Buffer {
let mut pool = self.pool.lock().unwrap();
if pool.is_empty() {
drop(pool);
let mut v = Vec::new();
v.resize(2048, 0);
v.into_boxed_slice()
} else {
pool.pop().unwrap()
}
}
fn return_buffer(&self, buffer: Self::Buffer) {
self.pool.lock().unwrap().push(buffer);
}
fn on_udp_packet(
&self,
socket: &UdpSocket<Self>,
remote_address: &InetAddress,
data: Self::Buffer,
len: usize,
) {
self.received.fetch_add(len as u64, Ordering::SeqCst);
if self.echo {
socket.send(remote_address, data, len);
//println!("echo! {} {}", len, self.received.load(Ordering::Relaxed));
} else {
self.return_buffer(data);
}
}
}
#[test]
fn loopback() {
let eng = Engine::<TestHandler>::new();
let sender_handler = Arc::new(TestHandler {
pool: Mutex::new(Vec::new()),
received: AtomicU64::new(0),
echo: false,
});
let sender = eng
.bind(
&InetAddress::from_ip_port(&[127, 0, 0, 1], 11111),
None,
true,
sender_handler.clone(),
(),
)
.unwrap();
let receiver_handler = Arc::new(TestHandler {
pool: Mutex::new(Vec::new()),
received: AtomicU64::new(0),
echo: true,
});
let sendto_addr = InetAddress::from_ip_port(&[127, 0, 0, 1], 11112);
let _receiver = eng
.bind(&sendto_addr, None, true, receiver_handler.clone(), ())
.unwrap();
const PACKET_COUNT: usize = 1024;
for _ in 0..PACKET_COUNT {
let mut b = sender_handler.get_buffer();
b.as_mut().fill(1);
sender.send(&sendto_addr, b, 1024);
}
for _ in 0..5000 {
if sender_handler.received.load(Ordering::Relaxed) == (PACKET_COUNT * 1024) as u64
&& receiver_handler.received.load(Ordering::Relaxed) == (PACKET_COUNT * 1024) as u64
{
return;
} else {
std::thread::sleep(Duration::from_millis(1));
}
}
panic!("receive timed out");
}
}
+188
View File
@@ -0,0 +1,188 @@
#[allow(unused_imports)]
use num_traits::AsPrimitive;
use zerotier_common_utils::inetaddress::InetAddress;
#[allow(unused)]
#[cfg(unix)]
pub(crate) unsafe fn bind_udp(
address: &InetAddress,
bind_to_device: Option<&str>,
reuseport: bool,
v6only: bool,
nonblock: bool,
) -> Result<i32, &'static str> {
use libc::*;
use zerotier_common_utils::inetaddress::InetAddress;
let mut setsockopt_results: c_int = 0;
let mut fl;
let (af, sa_len) = if address.is_ipv4() {
(AF_INET, std::mem::size_of::<sockaddr_in>().as_())
} else if address.is_ipv6() {
(AF_INET6, std::mem::size_of::<sockaddr_in6>().as_())
} else {
return Err("unrecognized address family");
};
let s = socket(af.as_(), SOCK_DGRAM, 0);
if s <= 0 {
return Err("unable to create new UDP socket");
}
if nonblock {
fcntl(s, F_SETFL, O_NONBLOCK);
}
/*
let mut timeo: timeval = std::mem::zeroed();
timeo.tv_sec = SOCKET_RECV_TIMEOUT_SECONDS.as_();
timeo.tv_usec = 0;
setsockopt_results |= setsockopt(
s,
SOL_SOCKET.as_(),
SO_RCVTIMEO.as_(),
(&mut timeo as *mut timeval).cast(),
std::mem::size_of::<timeval>().as_(),
);
*/
if reuseport {
fl = 1;
if setsockopt(
s,
SOL_SOCKET.as_(),
SO_REUSEPORT.as_(),
(&mut fl as *mut c_int).cast(),
std::mem::size_of::<c_int>().as_(),
) != 0
{
close(s);
return Err("unable to set SO_REUSEPORT");
}
}
fl = 1;
setsockopt(
s,
SOL_SOCKET.as_(),
SO_BROADCAST.as_(),
(&mut fl as *mut c_int).cast(),
std::mem::size_of::<c_int>().as_(),
);
if af == AF_INET6 {
fl = if v6only {
1
} else {
0
};
if setsockopt(
s,
IPPROTO_IPV6.as_(),
IPV6_V6ONLY.as_(),
(&mut fl as *mut c_int).cast(),
std::mem::size_of::<c_int>().as_(),
) != 0
{
close(s);
return Err("unable to set V6ONLY");
}
}
#[cfg(target_os = "linux")]
{
if let Some(bind_to_device) = bind_to_device {
if !bind_to_device.is_empty() {
let _ = std::ffi::CString::new(bind_to_device).map(|dn| {
let dnb = dn.as_bytes_with_nul();
let _ = setsockopt(
s.as_(),
SOL_SOCKET.as_(),
SO_BINDTODEVICE.as_(),
dnb.as_ptr().cast(),
(dnb.len() - 1).as_(),
);
});
}
}
}
if setsockopt_results != 0 {
close(s);
return Err("setsockopt() failed");
}
if af == AF_INET {
#[cfg(not(target_os = "linux"))]
{
fl = 0;
setsockopt(
s,
IPPROTO_IP.as_(),
IP_DONTFRAG.as_(),
(&mut fl as *mut c_int).cast(),
std::mem::size_of::<c_int>().as_(),
);
}
#[cfg(target_os = "linux")]
{
fl = IP_PMTUDISC_DONT as c_int;
setsockopt(
s,
IPPROTO_IP.as_(),
IP_MTU_DISCOVER.as_(),
(&mut fl as *mut c_int).cast(),
std::mem::size_of::<c_int>().as_(),
);
}
}
if af == AF_INET6 {
fl = 0;
setsockopt(
s,
IPPROTO_IPV6.as_(),
IPV6_DONTFRAG.as_(),
(&mut fl as *mut c_int).cast(),
std::mem::size_of::<c_int>().as_(),
);
}
fl = 1048576;
while fl >= 65536 {
if setsockopt(
s,
SOL_SOCKET.as_(),
SO_RCVBUF.as_(),
(&mut fl as *mut c_int).cast(),
std::mem::size_of::<c_int>().as_(),
) == 0
{
break;
}
fl -= 65536;
}
fl = 1048576;
while fl >= 65536 {
if setsockopt(
s,
SOL_SOCKET.as_(),
SO_SNDBUF.as_(),
(&mut fl as *mut c_int).cast(),
std::mem::size_of::<c_int>().as_(),
) == 0
{
break;
}
fl -= 65536;
}
if bind(s, (address as *const InetAddress).cast(), sa_len) != 0 {
close(s);
return Err("bind to address failed");
}
Ok(s as i32)
}