Browse Source

Merge commit '28df0c2e383ddb88d1afef2d0ac52046edd6cdbf' of github.com:zerotier/ZeroTierOne into master

pull/1/head
Xadhoom 5 years ago
parent
commit
2fed8b23b3
  1. 2
      .github/ISSUE_TEMPLATE/bug_report.md
  2. 3
      .gitignore
  3. 10
      AUTHORS.md
  4. 11
      COPYING
  5. 31
      Jenkinsfile
  6. 339
      LICENSE.GPL-2
  7. 674
      LICENSE.GPL-3
  8. 168
      LICENSE.txt
  9. 16
      OFFICIAL-RELEASE-STEPS.md
  10. 60
      README.md
  11. 39
      RELEASE-NOTES.md
  12. 1042
      attic/Cluster.cpp
  13. 463
      attic/Cluster.hpp
  14. 168
      attic/ClusterDefinition.hpp
  15. 243
      attic/ClusterGeoIpService.cpp
  16. 151
      attic/ClusterGeoIpService.hpp
  17. 101
      attic/FCV.hpp
  18. 650
      attic/OSXEthernetTap.cpp.pcap-with-bridge-test
  19. 831
      attic/OSXEthernetTap.cpp.utun-work-in-progress
  20. 95
      attic/OSXEthernetTap.hpp
  21. 96
      attic/OSXEthernetTap.hpp.pcap-with-bridge-test
  22. 101
      attic/OSXEthernetTap.hpp.utun-work-in-progress
  23. 4
      attic/README.md
  24. 497
      attic/RethinkDB.cpp
  25. 84
      attic/RethinkDB.hpp
  26. 18
      attic/kubernetes_docs/.zerotierCliSettings
  27. 19
      attic/kubernetes_docs/Dockerfile
  28. 150
      attic/kubernetes_docs/README.md
  29. 23
      attic/kubernetes_docs/entrypoint.sh
  30. 8
      attic/kubernetes_docs/server.js
  31. 25
      attic/lat_lon_to_xyz.js
  32. 4
      attic/world/build.sh
  33. 96
      attic/world/mkworld.cpp
  34. BIN
      attic/world/old/earth-2015-11-16.bin
  35. BIN
      attic/world/old/earth-2015-11-20.bin
  36. BIN
      attic/world/old/earth-2015-12-17.bin
  37. BIN
      attic/world/old/earth-2016-01-13.bin
  38. BIN
      attic/world/world.bin
  39. 4
      attic/world/world.c
  40. 107
      controller/DB.cpp
  41. 118
      controller/DB.hpp
  42. 231
      controller/DBMirrorSet.cpp
  43. 71
      controller/DBMirrorSet.hpp
  44. 153
      controller/EmbeddedNetworkController.cpp
  45. 46
      controller/EmbeddedNetworkController.hpp
  46. 116
      controller/FileDB.cpp
  47. 36
      controller/FileDB.hpp
  48. 406
      controller/LFDB.cpp
  49. 89
      controller/LFDB.hpp
  50. 379
      controller/PostgreSQL.cpp
  51. 127
      controller/PostgreSQL.hpp
  52. 1
      controller/README.md
  53. 161
      controller/RabbitMQ.cpp
  54. 64
      controller/RabbitMQ.hpp
  55. 36
      debian/changelog
  56. 28
      debian/copyright
  57. 19
      docker/Dockerfile
  58. 36
      ext/bin/tap-mac/tap.kext/Contents/Info.plist
  59. BIN
      ext/bin/tap-mac/tap.kext/Contents/MacOS/tap
  60. 105
      ext/bin/tap-mac/tap.kext/Contents/_CodeSignature/CodeResources
  61. 26
      ext/central-controller-docker/Dockerfile
  62. 3
      ext/central-controller-docker/README.md
  63. 2
      ext/central-controller-docker/main.sh
  64. 22
      ext/cpp-httplib/LICENSE
  65. 259
      ext/cpp-httplib/README.md
  66. 2779
      ext/cpp-httplib/httplib.h
  67. 30
      ext/installfiles/linux/zerotier-containerized/Dockerfile
  68. 1505
      ext/installfiles/mac/ZeroTier One.pkgproj
  69. 9
      ext/installfiles/mac/postinst.sh
  70. 10
      ext/installfiles/windows/ZeroTier One.aip
  71. 11
      ext/installfiles/windows/chocolatey/zerotier-one/tools/LICENSE.txt
  72. 5
      ext/installfiles/windows/chocolatey/zerotier-one/tools/VERIFICATION.txt
  73. 8
      ext/installfiles/windows/chocolatey/zerotier-one/tools/chocolateyinstall.ps1
  74. 30
      ext/installfiles/windows/chocolatey/zerotier-one/tools/chocolateyuninstall.ps1
  75. 76
      ext/installfiles/windows/chocolatey/zerotier-one/zerotier-one.nuspec
  76. 2538
      ext/librabbitmq/macos/include/amqp.h
  77. 1144
      ext/librabbitmq/macos/include/amqp_framing.h
  78. 68
      ext/librabbitmq/macos/include/amqp_tcp_socket.h
  79. BIN
      ext/librabbitmq/macos/lib/librabbitmq.a
  80. 29
      include/ZeroTierDebug.h
  81. 50
      include/ZeroTierOne.h
  82. 8
      macui/ZeroTier One.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
  83. 4
      make-bsd.mk
  84. 67
      make-linux.mk
  85. 19
      make-mac.mk
  86. 27
      node/Address.hpp
  87. 27
      node/AtomicCounter.hpp
  88. 27
      node/Buffer.hpp
  89. 1069
      node/C25519.cpp
  90. 27
      node/C25519.hpp
  91. 27
      node/Capability.cpp
  92. 27
      node/Capability.hpp
  93. 27
      node/CertificateOfMembership.cpp
  94. 31
      node/CertificateOfMembership.hpp
  95. 27
      node/CertificateOfOwnership.cpp
  96. 54
      node/CertificateOfOwnership.hpp
  97. 97
      node/Constants.hpp
  98. 27
      node/Credential.hpp
  99. 33
      node/Dictionary.hpp
  100. 27
      node/Hashtable.hpp
  101. Some files were not shown because too many files have changed in this diff Show More

2
.github/ISSUE_TEMPLATE/bug_report.md

@ -6,7 +6,7 @@ about: Create a report to help us improve
**Alternative, faster ways to get help** **Alternative, faster ways to get help**
If you have just started using ZeroTier, here are some places to get help: If you have just started using ZeroTier, here are some places to get help:
- my.zerotier.com has a _Community_ tab. It's a live chat with other users and the developers. - my.zerotier.com has a _Community_ tab. It's a live chat with other users and the developers.
- [ZeroTier Knowledge Base](https://support.zerotier.com/knowledgebase.php?s=MQ__) - [ZeroTier Knowledge Base](https://zerotier.atlassian.net/wiki/spaces/SD/overview)
- www.zerotier.com has a Contact Us button - www.zerotier.com has a Contact Us button
- email contact@zerotier.com - email contact@zerotier.com

3
.gitignore vendored

@ -118,3 +118,6 @@ ext/librethinkdbxx/build
.vscode .vscode
__pycache__ __pycache__
*~ *~
attic/world/*.c25519
attic/world/mkworld
workspace/

10
AUTHORS.md

@ -1,3 +1,5 @@
# Authors and Third Party Code Licensing Information
## Primary Authors ## Primary Authors
* ZeroTier Core and ZeroTier One virtual networking service<br> * ZeroTier Core and ZeroTier One virtual networking service<br>
@ -26,7 +28,7 @@
## Third-Party Code ## Third-Party Code
ZeroTier includes the following third party code, either in ext/ or incorporated into the ZeroTier core. ZeroTier includes the following third party code, either in ext/ or incorporated into the ZeroTier core. This third party code remains licensed under its original license and is not subject to ZeroTier's BSL license.
* LZ4 compression algorithm by Yann Collet * LZ4 compression algorithm by Yann Collet
@ -65,3 +67,9 @@ ZeroTier includes the following third party code, either in ext/ or incorporated
* Files: ext/libnatpmp/* ext/miniupnpc/* * Files: ext/libnatpmp/* ext/miniupnpc/*
* Home page: http://miniupnp.free.fr/ * Home page: http://miniupnp.free.fr/
* License grant: BSD attribution no-endorsement * License grant: BSD attribution no-endorsement
* cpp-httplib by yhirose
* Files: ext/cpp-httplib/*
* Home page: https://github.com/yhirose/cpp-httplib
* License grant: MIT

11
COPYING

@ -1,13 +1,8 @@
ZeroTier One, an endpoint server for the ZeroTier virtual network layer. ZeroTier One, an endpoint server for the ZeroTier virtual network layer.
Copyright © 2011–2018 ZeroTier, Inc. Copyright © 2011–2019 ZeroTier, Inc.
ZeroTier One is free software: you can redistribute it and/or modify ZeroTier is released under the terms of the BSL version 1.1. See the
it under the terms of the GNU General Public License as published by file LICENSE.txt for details.
the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
See the file ‘LICENSE.GPL-3’ for the text of the GNU GPL version 3.
If that file is not present, see <http://www.gnu.org/licenses/>.
.. ..
Local variables: Local variables:

31
Jenkinsfile vendored

@ -24,22 +24,22 @@ parallel 'centos7': {
throw err throw err
} }
} }
}, 'android-ndk': { // }, 'android-ndk': {
node('android-ndk') { // node('android-ndk') {
try { // try {
checkout scm // checkout scm
stage('Build Android NDK') { // stage('Build Android NDK') {
sh "/android/android-ndk-r15b/ndk-build -C $WORKSPACE/java ZT1=${WORKSPACE}" // sh "/android/android-ndk-r15b/ndk-build -C $WORKSPACE/java ZT1=${WORKSPACE}"
} // }
} // }
catch (err) { // catch (err) {
currentBuild.result = "FAILURE" // currentBuild.result = "FAILURE"
mattermostSend color: '#ff0000', message: "${env.JOB_NAME} broken on Android NDK (<${env.BUILD_URL}|Open>)" // mattermostSend color: '#ff0000', message: "${env.JOB_NAME} broken on Android NDK (<${env.BUILD_URL}|Open>)"
throw err // throw err
} // }
} // }
}, 'macOS': { }, 'macOS': {
node('macOS') { node('macOS') {
try { try {
@ -66,8 +66,7 @@ parallel 'centos7': {
checkout scm checkout scm
stage('Build Windows') { stage('Build Windows') {
bat '''CALL "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\vcvarsall.bat" amd64 bat '''CALL "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Auxiliary\\Build\\vcvars32.bat" x64
git clean -dfx
msbuild windows\\ZeroTierOne.sln msbuild windows\\ZeroTierOne.sln
''' '''
} }

339
LICENSE.GPL-2

@ -1,339 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

674
LICENSE.GPL-3

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

168
LICENSE.txt

@ -1,37 +1,149 @@
ZeroTier One - Network Virtualization Everywhere -----------------------------------------------------------------------------
Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
This program is free software: you can redistribute it and/or modify Business Source License 1.1
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved.
but WITHOUT ANY WARRANTY; without even the implied warranty of "Business Source License" is a trademark of MariaDB Corporation Ab.
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License -----------------------------------------------------------------------------
along with this program. If not, see <http://www.gnu.org/licenses/>.
See LICENSE.GPL-3 for the full GNU GPL v3 license. Parameters
-- Licensor: ZeroTier, Inc.
Licensed Work: ZeroTier Network Virtualization Engine 1.4.4
The Licensed Work is (c)2019 ZeroTier, Inc.
Additional Use Grant: You may make use of the Licensed Work, provided you
do not use it in any of the following ways:
You can be released from the requirements of the license by purchasing * Sell hosted ZeroTier services as a "SaaS" Product
a commercial license. Buying such a license is mandatory as soon as you
develop commercial closed-source software that incorporates or links
directly against ZeroTier software without disclosing the source code
of your own application.
-- (1) Operate or sell access to ZeroTier root servers,
network controllers, or authorization key or certificate
generation components of the Licensed Work as a
for-profit service, regardless of whether the use of
these components is sold alone or is bundled with other
services. Note that this does not apply to the use of
ZeroTier behind the scenes to operate a service not
related to ZeroTier network administration.
The above license does not apply to third party code included with or * Create Non-Open-Source Commercial Derviative Works
linked against by ZeroTier software. See the third party code section
of the AUTHORS.md for an index of third party software included in
this software repository.
Licenses for third party code are all relatively permissive: MIT, (2) Link or directly include the Licensed Work in a
BSD, and public domain. The only exception is the tap-windows driver commercial or for-profit application or other product
which is under the GPLv2, but this is only needed to produce the not distributed under an Open Source Initiative (OSI)
binary tap device driver used by the ZeroTier service on Windows. compliant license. See: https://opensource.org/licenses
(3) Remove the name, logo, copyright, or other branding
material from the Licensed Work to create a "rebranded"
or "white labeled" version to distribute as part of
any commercial or for-profit product or service.
* Certain Government Uses
(4) Use or deploy the Licensed Work in a government
setting in support of any active government function
or operation with the exception of the following:
physical or mental health care, family and social
services, social welfare, senior care, child care, and
the care of persons with disabilities.
Change Date: 2023-01-01
Change License: Apache License version 2.0 as published by the Apache
Software Foundation
https://www.apache.org/licenses/
Alternative Licensing
If you would like to use the Licensed Work in any way that conflicts with
the stipulations of the Additional Use Grant, contact ZeroTier, Inc. to
obtain an alternative commercial license.
Visit us on the web at: https://www.zerotier.com/
Notice
The Business Source License (this document, or the "License") is not an Open
Source license. However, the Licensed Work will eventually be made available
under an Open Source License, as stated in this License.
For more information on the use of the Business Source License for ZeroTier
products, please visit our pricing page which contains license details and
and license FAQ: https://zerotier.com/pricing
For more information on the use of the Business Source License generally,
please visit the Adopting and Developing Business Source License FAQ at
https://mariadb.com/bsl-faq-adopting.
-----------------------------------------------------------------------------
Business Source License 1.1
Terms
The Licensor hereby grants you the right to copy, modify, create derivative
works, redistribute, and make non-production use of the Licensed Work. The
Licensor may make an Additional Use Grant, above, permitting limited
production use.
Effective on the Change Date, or the fourth anniversary of the first publicly
available distribution of a specific version of the Licensed Work under this
License, whichever comes first, the Licensor hereby grants you rights under
the terms of the Change License, and the rights granted in the paragraph
above terminate.
If your use of the Licensed Work does not comply with the requirements
currently in effect as described in this License, you must purchase a
commercial license from the Licensor, its affiliated entities, or authorized
resellers, or you must refrain from using the Licensed Work.
All copies of the original and modified Licensed Work, and derivative works
of the Licensed Work, are subject to this License. This License applies
separately for each version of the Licensed Work and the Change Date may vary
for each version of the Licensed Work released by Licensor.
You must conspicuously display this License on each original or modified copy
of the Licensed Work. If you receive the Licensed Work in original or
modified form from a third party, the terms and conditions set forth in this
License apply to your use of that work.
Any use of the Licensed Work in violation of this License will automatically
terminate your rights under this License for the current and all other
versions of the Licensed Work.
This License does not grant you any right in any trademark or logo of
Licensor or its affiliates (provided that you may use a trademark or logo of
Licensor as expressly required by this License).
TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
TITLE.
-----------------------------------------------------------------------------
MariaDB hereby grants you permission to use this License’s text to license
your works, and to refer to it using the trademark "Business Source License",
as long as you comply with the Covenants of Licensor below.
Covenants of Licensor
In consideration of the right to use this License’s text and the "Business
Source License" name and trademark, Licensor covenants to MariaDB, and to all
other recipients of the licensed work to be provided by Licensor:
1. To specify as the Change License the GPL Version 2.0 or any later version,
or a license that is compatible with GPL Version 2.0 or a later version,
where "compatible" means that software provided under the Change License can
be included in a program with software provided under GPL Version 2.0 or a
later version. Licensor may specify additional Change Licenses without
limitation.
2. To either: (a) specify an additional grant of rights to use that does not
impose any additional restriction on the right granted in this License, as
the Additional Use Grant; or (b) insert the text "None".
3. To specify a Change Date.
4. Not to modify this License in any other way.

16
OFFICIAL-RELEASE-STEPS.md

@ -13,7 +13,6 @@ The version must be incremented in all of the following files:
/zerotier-one.spec /zerotier-one.spec
/debian/changelog /debian/changelog
/ext/installfiles/mac/ZeroTier One.pkgproj /ext/installfiles/mac/ZeroTier One.pkgproj
/ext/installfiles/windows/chocolatey/zerotier-one.nuspec
/ext/installfiles/windows/ZeroTier One.aip /ext/installfiles/windows/ZeroTier One.aip
/windows/WinUI/AboutView.xaml /windows/WinUI/AboutView.xaml
@ -29,21 +28,6 @@ Mac's easy. Just type:
You will need [Packages](http://s.sudre.free.fr/Software/Packages/about.html) and our release signing key in the keychain. You will need [Packages](http://s.sudre.free.fr/Software/Packages/about.html) and our release signing key in the keychain.
## Linux
See `LinuxBuild` environment on `linux-build` VM and use: `chroots/mount-build.sh`, `chroots/build.sh`, and the scripts in `build/` to make APT and RPM repositories.
## Windows ## Windows
First load the Visual Studio solution and rebuild the UI and ZeroTier One in both x64 and i386 `Release` mode. Then load [Advanced Installer Enterprise](http://www.advancedinstaller.com/), check that the version is correct, and build. The build will fail if any build artifacts are missing, and Windows must have our product singing key (from DigiCert) available to sign the resulting MSI file. The MSI must then be tested on at least a few different CLEAN Windows VMs to ensure that the installer is valid and properly signed. First load the Visual Studio solution and rebuild the UI and ZeroTier One in both x64 and i386 `Release` mode. Then load [Advanced Installer Enterprise](http://www.advancedinstaller.com/), check that the version is correct, and build. The build will fail if any build artifacts are missing, and Windows must have our product singing key (from DigiCert) available to sign the resulting MSI file. The MSI must then be tested on at least a few different CLEAN Windows VMs to ensure that the installer is valid and properly signed.
*After the MSI is published to download.zerotier.com in the proper RELEASE/#.#.#/dist subfolder for its version* the Chocolatey package must be rebuilt and published. Open a command prompt, change to `ext/installfiles/windows/chocolatey`, and type `choco pack`. Then use `choco push` to push it to Chocolatey (API key required).
choco pack
choco push zerotier-one.#.#.#.nupkg -s https://chocolatey.org/
Note that this does not cover rebuilding the drivers or their containing MSI projects, as this is typically not necessary and they are shipped in binary form in the repository for convenience.
## iOS, Android
... no docs here yet since this is done entirely out of band with regular installs.

60
README.md

@ -1,22 +1,32 @@
ZeroTier - A Planetary Ethernet Switch ZeroTier - Global Area Networking
====== ======
ZeroTier is a smart programmable Ethernet switch for planet Earth. ZeroTier is a smart programmable Ethernet switch for planet Earth. It allows all networked devices, VMs, containers, and applications to communicate as if they all reside in the same physical data center or cloud region.
It replaces the physical LAN/WAN boundary with a virtual one, allowing devices of any type at any location to be managed as if they all reside in the same cloud region or data center. All traffic is encrypted end-to-end and takes the most direct path available for minimum latency and maximum performance. The goals and design of ZeroTier are inspired by among other things the original [Google BeyondCorp](https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43231.pdf) paper and the [Jericho Forum](https://en.wikipedia.org/wiki/Jericho_Forum). This is accomplished by combining a cryptographically addressed and secure peer to peer network (termed VL1) with an Ethernet emulation layer somewhat similar to VXLAN (termed VL2). Our VL2 Ethernet virtualization layer includes advanced enterprise SDN features like fine grained access control rules for network micro-segmentation and security monitoring.
Visit [ZeroTier's site](https://www.zerotier.com/?pk_campaign=github_ZeroTierOne) for more information and [pre-built binary packages](https://www.zerotier.com/download.shtml?pk_campaign=github_ZeroTierOne). Apps for Android and iOS are available for free in the Google Play and Apple app stores. All ZeroTier traffic is encrypted end-to-end using secret keys that only you control. Most traffic flows peer to peer, though we offer free (but slow) relaying for users who cannot establish peer to peer connetions.
The goals and design principles of ZeroTier are inspired by among other things the original [Google BeyondCorp](https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43231.pdf) paper and the [Jericho Forum](https://en.wikipedia.org/wiki/Jericho_Forum) with its notion of "deperimeterization."
Visit [ZeroTier's site](https://www.zerotier.com/) for more information and [pre-built binary packages](https://www.zerotier.com/download/). Apps for Android and iOS are available for free in the Google Play and Apple app stores.
ZeroTier is licensed under the [BSL version 1.1](https://mariadb.com/bsl11/). See [LICENSE.txt](LICENSE.txt) and the [ZeroTier pricing page](https://www.zerotier.com/pricing) for details. ZeroTier is free to use internally in businesses and academic institutions and for non-commercial purposes. Certain types of commercial use such as building closed-source apps and devices based on ZeroTier or offering ZeroTier network controllers and network management as a SaaS service require a commercial license.
A small amount of third party code is also included in ZeroTier and is not subject to our BSL license. See [AUTHORS.md] for a list of third party code, where it is included, and the licenses that apply to it. All of the third party code in ZeroTier is liberally licensed (MIT, BSD, Apache, public domain, etc.).
### Getting Started ### Getting Started
Everything in the ZeroTier world is controlled by two types of identifier: 40-bit/10-digit *ZeroTier addresses* and 64-bit/16-digit *network IDs*. A ZeroTier address identifies a node or "device" (laptop, phone, server, VM, app, etc.) while a network ID identifies a virtual Ethernet network that can be joined by devices. Everything in the ZeroTier world is controlled by two types of identifier: 40-bit/10-digit *ZeroTier addresses* and 64-bit/16-digit *network IDs*. These identifiers are easily distinguished by their length. A ZeroTier address identifies a node or "device" (laptop, phone, server, VM, app, etc.) while a network ID identifies a virtual Ethernet network that can be joined by devices.
Another way of thinking about it is that ZeroTier addresses are port numbers on a giant planetary-sized smart switch while network IDs are VLANs to which these ports can be assigned. For more details read about VL1 and VL2 in [the ZeroTier manual](https://www.zerotier.com/manual.shtml). ZeroTier addresses can be thought of as port numbers on an enormous planet-wide enterprise Ethernet smart switch supporting VLANs. Network IDs are VLAN IDs to which these ports may be assigned. A single port can be assigned to more than one VLAN.
*Network controllers* are ZeroTier nodes that act as access control certificate authorities and configuration managers for virtual networks. The first 40 bits (or 10 digits) of a network ID is the ZeroTier address of its controller. You can create networks with our [hosted controllers](https://my.zerotier.com/) and web UI/API or [host your own](controller/) if you don't mind posting some JSON configuration info or writing a script to do so. A ZeroTier address looks like `8056c2e21c` and a network ID looks like `8056c2e21c000001`. Network IDs are composed of the ZeroTier address of that network's primary controller and an arbitrary 24-bit ID that identifies the network on this controller. Network controllers are roughly analogous to SDN controllers in SDN protocols like [OpenFlow](https://en.wikipedia.org/wiki/OpenFlow), though as with the analogy between VXLAN and VL2 this should not be read to imply that the protocols or design are the same. You can use our convenient and inexpensive SaaS hosted controllers at [my.zerotier.com](https://my.zerotier.com/) or [run your own controller](controller/) if you don't mind messing around with JSON configuration files or writing scripts to do so.
### Project Layout ### Project Layout
The base path contains the ZeroTier One service main entry point (`one.cpp`), self test code, makefiles, etc.
- `artwork/`: icons, logos, etc. - `artwork/`: icons, logos, etc.
- `attic/`: old stuff and experimental code that we want to keep around for reference. - `attic/`: old stuff and experimental code that we want to keep around for reference.
- `controller/`: the reference network controller implementation, which is built and included by default on desktop and server build targets. - `controller/`: the reference network controller implementation, which is built and included by default on desktop and server build targets.
@ -28,35 +38,27 @@ Another way of thinking about it is that ZeroTier addresses are port numbers on
- `macui/`: a Macintosh menu-bar app for controlling ZeroTier One, written in Objective C. - `macui/`: a Macintosh menu-bar app for controlling ZeroTier One, written in Objective C.
- `node/`: the ZeroTier virtual Ethernet switch core, which is designed to be entirely separate from the rest of the code and able to be built as a stand-alone OS-independent library. Note to developers: do not use C++11 features in here, since we want this to build on old embedded platforms that lack C++11 support. C++11 can be used elsewhere. - `node/`: the ZeroTier virtual Ethernet switch core, which is designed to be entirely separate from the rest of the code and able to be built as a stand-alone OS-independent library. Note to developers: do not use C++11 features in here, since we want this to build on old embedded platforms that lack C++11 support. C++11 can be used elsewhere.
- `osdep/`: code to support and integrate with OSes, including platform-specific stuff only built for certain targets. - `osdep/`: code to support and integrate with OSes, including platform-specific stuff only built for certain targets.
- `rule-compiler/`: JavaScript rules language compiler for defining network-level rules.
- `service/`: the ZeroTier One service, which wraps the ZeroTier core and provides VPN-like connectivity to virtual networks for desktops, laptops, servers, VMs, and containers. - `service/`: the ZeroTier One service, which wraps the ZeroTier core and provides VPN-like connectivity to virtual networks for desktops, laptops, servers, VMs, and containers.
- `tcp-proxy/`: TCP proxy code run by ZeroTier, Inc. to provide TCP fallback (this will die soon!). - `windows/`: Visual Studio solution files, Windows service code, and the Windows task bar app UI.
- `windows/`: Visual Studio solution files, Windows service code for ZeroTier One, and the Windows task bar app UI.
The base path contains the ZeroTier One service main entry point (`one.cpp`), self test code, makefiles, etc.
### Build and Platform Notes ### Build and Platform Notes
To build on Mac and Linux just type `make`. On FreeBSD and OpenBSD `gmake` (GNU make) is required and can be installed from packages or ports. For Windows there is a Visual Studio solution in `windows/'. To build on Mac and Linux just type `make`. On FreeBSD and OpenBSD `gmake` (GNU make) is required and can be installed from packages or ports. For Windows there is a Visual Studio solution in `windows/'.
- **Mac** - **Mac**
- Xcode command line tools for OSX 10.7 or newer are required. - Xcode command line tools for OSX 10.8 or newer are required.
- Tap device driver kext source is in `ext/tap-mac` and a signed pre-built binary can be found in `ext/bin/tap-mac`. You should not need to build it yourself. It's a fork of [tuntaposx](http://tuntaposx.sourceforge.net) with device names changed to `zt#`, support for a larger MTU, and tun functionality removed.
- **Linux** - **Linux**
- The minimum compiler versions required are GCC/G++ 4.9.3 or CLANG/CLANG++ 3.4.2. - The minimum compiler versions required are GCC/G++ 4.9.3 or CLANG/CLANG++ 3.4.2. (Install `clang` on CentOS 7 as G++ is too old.)
- Linux makefiles automatically detect and prefer clang/clang++ if present as it produces smaller and slightly faster binaries in most cases. You can override by supplying CC and CXX variables on the make command line. - Linux makefiles automatically detect and prefer clang/clang++ if present as it produces smaller and slightly faster binaries in most cases. You can override by supplying CC and CXX variables on the make command line.
- CentOS 7 ships with a version of GCC/G++ that is too old, but a new enough version of CLANG can be found in the *epel* repositories. Type `yum install epel-release` and then `yum install clang` to build there.
- **Windows** - **Windows**
- Windows 7 or newer is supported. This *may* work on Vista but isn't officially supported there. It will not work on Windows XP. - Windows 7 or newer is supported. This *may* work on Vista but isn't officially supported there. It will not work on Windows XP.
- We build with Visual Studio 2015. Older versions may not work. Clang or MinGW will also probably work but may require some makefile hacking. - We build with Visual Studio 2017. Older versions may not work. Clang or MinGW will also probably work but may require some makefile hacking.
- Pre-built signed Windows drivers are included in `ext/bin/tap-windows-ndis6`. The MSI files found there will install them on 32-bit and 64-bit systems. We don't recommend trying to build Windows drivers from scratch unless you know what you're doing. One does not simply "build" a Windows driver.
- **FreeBSD** - **FreeBSD**
- Tested most recently on FreeBSD-11. Older versions may work but we're not sure. - GNU make is required. Type `gmake` to build.
- GCC/G++ 4.9 and gmake are required. These can be installed from packages or ports. Type `gmake` to build.
- **OpenBSD** - **OpenBSD**
- There is a limit of four network memberships on OpenBSD as there are only four tap devices (`/dev/tap0` through `/dev/tap3`). We're not sure if this can be increased. - There is a limit of four network memberships on OpenBSD as there are only four tap devices (`/dev/tap0` through `/dev/tap3`).
- OpenBSD lacks `getifmaddrs` (or any equivalent method) to get interface multicast memberships. As a result multicast will only work on OpenBSD for ARP and NDP (IP/MAC lookup) and not for other purposes. - GNU make is required. Type `gmake` to build.
- Only tested on OpenBSD 6.0. Older versions may not work.
- GCC/G++ 4.9 and gmake are required and can be installed using `pkg_add` or from ports. They get installed in `/usr/local/bin` as `egcc` and `eg++` and our makefile is pre-configured to use them on OpenBSD.
Typing `make selftest` will build a *zerotier-selftest* binary which unit tests various internals and reports on a few aspects of the build environment. It's a good idea to try this on novel platforms or architectures. Typing `make selftest` will build a *zerotier-selftest* binary which unit tests various internals and reports on a few aspects of the build environment. It's a good idea to try this on novel platforms or architectures.
@ -85,7 +87,7 @@ Running ZeroTier One on a Mac is the same, but OSX requires a kernel extension.
This will create the home folder for Mac, place *tap.kext* there, and set its modes correctly to enable ZeroTier One to manage it with *kextload* and *kextunload*. This will create the home folder for Mac, place *tap.kext* there, and set its modes correctly to enable ZeroTier One to manage it with *kextload* and *kextunload*.
### Troubleshooting ### Basic Troubleshooting
For most users, it just works. For most users, it just works.
@ -101,14 +103,6 @@ ZeroTier One peers will automatically locate each other and communicate directly
Users behind certain types of firewalls and "symmetric" NAT devices may not able able to connect to external peers directly at all. ZeroTier has limited support for port prediction and will *attempt* to traverse symmetric NATs, but this doesn't always work. If P2P connectivity fails you'll be bouncing UDP packets off our relay servers resulting in slower performance. Some NAT router(s) have a configurable NAT mode, and setting this to "full cone" will eliminate this problem. If you do this you may also see a magical improvement for things like VoIP phones, Skype, BitTorrent, WebRTC, certain games, etc., since all of these use NAT traversal techniques similar to ours. Users behind certain types of firewalls and "symmetric" NAT devices may not able able to connect to external peers directly at all. ZeroTier has limited support for port prediction and will *attempt* to traverse symmetric NATs, but this doesn't always work. If P2P connectivity fails you'll be bouncing UDP packets off our relay servers resulting in slower performance. Some NAT router(s) have a configurable NAT mode, and setting this to "full cone" will eliminate this problem. If you do this you may also see a magical improvement for things like VoIP phones, Skype, BitTorrent, WebRTC, certain games, etc., since all of these use NAT traversal techniques similar to ours.
If you're interested, there's a [technical deep dive about NAT traversal on our blog](https://www.zerotier.com/blog/?p=226?pk_campaign=github_ZeroTierOne). A troubleshooting tool to help you diagnose NAT issues is planned for the future as are uPnP/IGD/NAT-PMP and IPv6 transport.
If a firewall between you and the Internet blocks ZeroTier's UDP traffic, you will fall back to last-resort TCP tunneling to rootservers over port 443 (https impersonation). This will work almost anywhere but is *very slow* compared to UDP or direct peer to peer connectivity. If a firewall between you and the Internet blocks ZeroTier's UDP traffic, you will fall back to last-resort TCP tunneling to rootservers over port 443 (https impersonation). This will work almost anywhere but is *very slow* compared to UDP or direct peer to peer connectivity.
### Contributing Additional help [can be found in our knowledge base](https://zerotier.atlassian.net/wiki/spaces/SD/overview).
Please make pull requests against the `dev` branch. The `master` branch is release, and `edge` is for unstable and work in progress changes and is not likely to work.
### License
The ZeroTier source code is open source and is licensed under the GNU GPL v3 (not LGPL). If you'd like to embed it in a closed-source commercial product or appliance, please e-mail [contact@zerotier.com](mailto:contact@zerotier.com) to discuss commercial licensing. Otherwise it can be used for free.

39
RELEASE-NOTES.md

@ -1,6 +1,45 @@
ZeroTier Release Notes ZeroTier Release Notes
====== ======
# 2019-08-30 -- Version 1.4.6
* Update default root list to latest
* ARM32 platform build and flag fixes
* Add a clarification line to LICENSE.txt
* Fix license message in CLI
* Windows service now looks for service command line arguments
* Fixed a bug that could cause excessive queued multicasts
# 2019-08-23 -- Version 1.4.4
* Change license from GPL3 to BSL 1.1, see LICENSE.txt
* Fix an issue with the "ipauth" rule and auto-generated unforgeable IPv6 addresses
* Fix socket/bind errors setting IPs and routes on Linux
# 2019-08-12 -- Version 1.4.2
* Fix high CPU use bug on some platforms
* Fix issues with PostgreSQL controller DB (only affects Central)
* Restore backward compatibility with MacOS versions prior to 10.13
# 2019-07-29 -- Version 1.4.0
### Major Changes
* Mac version no longer requires a kernel extension, instead making use of the [feth interfaces](https://apple.stackexchange.com/questions/337715/fake-ethernet-interfaces-feth-if-fake-anyone-ever-seen-this).
* Added support for concurrent multipath (multiple paths at once) with traffic weighting by link quality and faster recovery from lost links.
* Added under-the-hood support for QoS (not yet exposed) that will eventually be configurable via our rules engine.
### Minor Changes and Bug Fixes
* Experimental controller DB driver for [LF](https://github.com/zerotier/lf) to store network controller data (LFDB.cpp / LFDB.hpp).
* Modified credential push and direct path push timings and algorithms to somewhat reduce "chattiness" of the protocol when idle. More radical background overhead reductions will have to wait for the 2.x line.
* Removed our beta/half-baked integration of Central with the Windows UI. We're going to do a whole new UI of some kind in the future at least for Windows and Mac.
* Fixed stack overflow issues on Linux versions using musl libc.
* Fixed some alignment problems reported on ARM and ARM64, but some reports we could not reproduce so please report any issues with exact chip, OS/distro, and ZeroTier version in use.
* Fixed numerous other small issues and bugs such as ARM alignment issues causing crashes on some devices.
* Windows now sets the adapter name such that it is consistent in both the Windows UI and command line utilities.
# 2018-07-27 -- Version 1.2.12 # 2018-07-27 -- Version 1.2.12
* Fixed a bug that caused exits to take a long time on Mac due to huge numbers of redundant attempts to delete managed routes. * Fixed a bug that caused exits to take a long time on Mac due to huge numbers of redundant attempts to delete managed routes.

1042
attic/Cluster.cpp

File diff suppressed because it is too large Load Diff

463
attic/Cluster.hpp

@ -1,463 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
#ifndef ZT_CLUSTER_HPP
#define ZT_CLUSTER_HPP
#ifdef ZT_ENABLE_CLUSTER
#include <map>
#include "Constants.hpp"
#include "../include/ZeroTierOne.h"
#include "Address.hpp"
#include "InetAddress.hpp"
#include "SHA512.hpp"
#include "Utils.hpp"
#include "Buffer.hpp"
#include "Mutex.hpp"
#include "SharedPtr.hpp"
#include "Hashtable.hpp"
#include "Packet.hpp"
#include "SharedPtr.hpp"
/**
* Timeout for cluster members being considered "alive"
*
* A cluster member is considered dead and will no longer have peers
* redirected to it if we have not heard a heartbeat in this long.
*/
#define ZT_CLUSTER_TIMEOUT 5000
/**
* Desired period between doPeriodicTasks() in milliseconds
*/
#define ZT_CLUSTER_PERIODIC_TASK_PERIOD 20
/**
* How often to flush outgoing message queues (maximum interval)
*/
#define ZT_CLUSTER_FLUSH_PERIOD ZT_CLUSTER_PERIODIC_TASK_PERIOD
/**
* Maximum number of queued outgoing packets per sender address
*/
#define ZT_CLUSTER_MAX_QUEUE_PER_SENDER 16
/**
* Expiration time for send queue entries
*/
#define ZT_CLUSTER_QUEUE_EXPIRATION 3000
/**
* Chunk size for allocating queue entries
*
* Queue entries are allocated in chunks of this many and are added to a pool.
* ZT_CLUSTER_MAX_QUEUE_GLOBAL must be evenly divisible by this.
*/
#define ZT_CLUSTER_QUEUE_CHUNK_SIZE 32
/**
* Maximum number of chunks to ever allocate
*
* This is a global sanity limit to prevent resource exhaustion attacks. It
* works out to about 600mb of RAM. You'll never see this on a normal edge
* node. We're unlikely to see this on a root server unless someone is DOSing
* us. In that case cluster relaying will be affected but other functions
* should continue to operate normally.
*/
#define ZT_CLUSTER_MAX_QUEUE_CHUNKS 8194
/**
* Max data per queue entry
*/
#define ZT_CLUSTER_SEND_QUEUE_DATA_MAX 1500
/**
* We won't send WANT_PEER to other members more than every (ms) per recipient
*/
#define ZT_CLUSTER_WANT_PEER_EVERY 1000
namespace ZeroTier {
class RuntimeEnvironment;
class MulticastGroup;
class Peer;
class Identity;
// Internal class implemented inside Cluster.cpp
class _ClusterSendQueue;
/**
* Multi-homing cluster state replication and packet relaying
*
* Multi-homing means more than one node sharing the same ZeroTier identity.
* There is nothing in the protocol to prevent this, but to make it work well
* requires the devices sharing an identity to cooperate and share some
* information.
*
* There are three use cases we want to fulfill:
*
* (1) Multi-homing of root servers with handoff for efficient routing,
* HA, and load balancing across many commodity nodes.
* (2) Multi-homing of network controllers for the same reason.
* (3) Multi-homing of nodes on virtual networks, such as domain servers
* and other important endpoints.
*
* These use cases are in order of escalating difficulty. The initial
* version of Cluster is aimed at satisfying the first, though you are
* free to try #2 and #3.
*/
class Cluster
{
public:
/**
* State message types
*/
enum StateMessageType
{
CLUSTER_MESSAGE_NOP = 0,
/**
* This cluster member is alive:
* <[2] version minor>
* <[2] version major>
* <[2] version revision>
* <[1] protocol version>
* <[4] X location (signed 32-bit)>
* <[4] Y location (signed 32-bit)>
* <[4] Z location (signed 32-bit)>
* <[8] local clock at this member>
* <[8] load average>
* <[8] number of peers>
* <[8] flags (currently unused, must be zero)>
* <[1] number of preferred ZeroTier endpoints>
* <[...] InetAddress(es) of preferred ZeroTier endpoint(s)>
*
* Cluster members constantly broadcast an alive heartbeat and will only
* receive peer redirects if they've done so within the timeout.
*/
CLUSTER_MESSAGE_ALIVE = 1,
/**
* Cluster member has this peer:
* <[...] serialized identity of peer>
*
* This is typically sent in response to WANT_PEER but can also be pushed
* to prepopulate if this makes sense.
*/
CLUSTER_MESSAGE_HAVE_PEER = 2,
/**
* Cluster member wants this peer:
* <[5] ZeroTier address of peer>
*
* Members that have a direct link to this peer will respond with
* HAVE_PEER.
*/
CLUSTER_MESSAGE_WANT_PEER = 3,
/**
* A remote packet that we should also possibly respond to:
* <[2] 16-bit length of remote packet>
* <[...] remote packet payload>
*
* Cluster members may relay requests by relaying the request packet.
* These may include requests such as WHOIS and MULTICAST_GATHER. The
* packet must be already decrypted, decompressed, and authenticated.
*
* This can only be used for small request packets as per the cluster
* message size limit, but since these are the only ones in question
* this is fine.
*
* If a response is generated it is sent via PROXY_SEND.
*/
CLUSTER_MESSAGE_REMOTE_PACKET = 4,
/**
* Request that VERB_RENDEZVOUS be sent to a peer that we have:
* <[5] ZeroTier address of peer on recipient's side>
* <[5] ZeroTier address of peer on sender's side>
* <[1] 8-bit number of sender's peer's active path addresses>
* <[...] series of serialized InetAddresses of sender's peer's paths>
*
* This requests that we perform NAT-t introduction between a peer that
* we have and one on the sender's side. The sender furnishes contact
* info for its peer, and we send VERB_RENDEZVOUS to both sides: to ours
* directly and with PROXY_SEND to theirs.
*/
CLUSTER_MESSAGE_PROXY_UNITE = 5,
/**
* Request that a cluster member send a packet to a locally-known peer:
* <[5] ZeroTier address of recipient>
* <[1] packet verb>
* <[2] length of packet payload>
* <[...] packet payload>
*
* This differs from RELAY in that it requests the receiving cluster
* member to actually compose a ZeroTier Packet from itself to the
* provided recipient. RELAY simply says "please forward this blob."
* RELAY is used to implement peer-to-peer relaying with RENDEZVOUS,
* while PROXY_SEND is used to implement proxy sending (which right
* now is only used to send RENDEZVOUS).
*/
CLUSTER_MESSAGE_PROXY_SEND = 6,
/**
* Replicate a network config for a network we belong to:
* <[...] network config chunk>
*
* This is used by clusters to avoid every member having to query
* for the same netconf for networks all members belong to.
*
* The first field of a network config chunk is the network ID,
* so this can be checked to look up the network on receipt.
*/
CLUSTER_MESSAGE_NETWORK_CONFIG = 7
};
/**
* Construct a new cluster
*/
Cluster(
const RuntimeEnvironment *renv,
uint16_t id,
const std::vector<InetAddress> &zeroTierPhysicalEndpoints,
int32_t x,
int32_t y,
int32_t z,
void (*sendFunction)(void *,unsigned int,const void *,unsigned int),
void *sendFunctionArg,
int (*addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *),
void *addressToLocationFunctionArg);
~Cluster();
/**
* @return This cluster member's ID
*/
inline uint16_t id() const throw() { return _id; }
/**
* Handle an incoming intra-cluster message
*
* @param data Message data
* @param len Message length (max: ZT_CLUSTER_MAX_MESSAGE_LENGTH)
*/
void handleIncomingStateMessage(const void *msg,unsigned int len);
/**
* Broadcast that we have a given peer
*
* This should be done when new peers are first contacted.
*
* @param id Identity of peer
*/
void broadcastHavePeer(const Identity &id);
/**
* Broadcast a network config chunk to other members of cluster
*
* @param chunk Chunk data
* @param len Length of chunk
*/
void broadcastNetworkConfigChunk(const void *chunk,unsigned int len);
/**
* If the cluster has this peer, prepare the packet to send via cluster
*
* Note that outp is only armored (or modified at all) if the return value is a member ID.
*
* @param toPeerAddress Value of outp.destination(), simply to save additional lookup
* @param ts Result: set to time of last HAVE_PEER from the cluster
* @param peerSecret Result: Buffer to fill with peer secret on valid return value, must be at least ZT_PEER_SECRET_KEY_LENGTH bytes
* @return -1 if cluster does not know this peer, or a member ID to pass to sendViaCluster()
*/
int checkSendViaCluster(const Address &toPeerAddress,uint64_t &mostRecentTs,void *peerSecret);
/**
* Send data via cluster front plane (packet head or fragment)
*
* @param haveMemberId Member ID that has this peer as returned by prepSendviaCluster()
* @param toPeerAddress Destination peer address
* @param data Packet or packet fragment data
* @param len Length of packet or fragment
* @return True if packet was sent (and outp was modified via armoring)
*/
bool sendViaCluster(int haveMemberId,const Address &toPeerAddress,const void *data,unsigned int len);
/**
* Relay a packet via the cluster
*
* This is used in the outgoing packet and relaying logic in Switch to
* relay packets to other cluster members. It isn't PROXY_SEND-- that is
* used internally in Cluster to send responses to peer queries.
*
* @param fromPeerAddress Source peer address (if known, should be NULL for fragments)
* @param toPeerAddress Destination peer address
* @param data Packet or packet fragment data
* @param len Length of packet or fragment
* @param unite If true, also request proxy unite across cluster
*/
void relayViaCluster(const Address &fromPeerAddress,const Address &toPeerAddress,const void *data,unsigned int len,bool unite);
/**
* Send a distributed query to other cluster members
*
* Some queries such as WHOIS or MULTICAST_GATHER need a response from other
* cluster members. Replies (if any) will be sent back to the peer via
* PROXY_SEND across the cluster.
*
* @param pkt Packet to distribute
*/
void sendDistributedQuery(const Packet &pkt);
/**
* Call every ~ZT_CLUSTER_PERIODIC_TASK_PERIOD milliseconds.
*/
void doPeriodicTasks();
/**
* Add a member ID to this cluster
*
* @param memberId Member ID
*/
void addMember(uint16_t memberId);
/**
* Remove a member ID from this cluster
*
* @param memberId Member ID to remove
*/
void removeMember(uint16_t memberId);
/**
* Find a better cluster endpoint for this peer (if any)
*
* @param redirectTo InetAddress to be set to a better endpoint (if there is one)
* @param peerAddress Address of peer to (possibly) redirect
* @param peerPhysicalAddress Physical address of peer's current best path (where packet was most recently received or getBestPath()->address())
* @param offload Always redirect if possible -- can be used to offload peers during shutdown
* @return True if redirectTo was set to a new address, false if redirectTo was not modified
*/
bool findBetterEndpoint(InetAddress &redirectTo,const Address &peerAddress,const InetAddress &peerPhysicalAddress,bool offload);
/**
* @param ip Address to check
* @return True if this is a cluster frontplane address (excluding our addresses)
*/
bool isClusterPeerFrontplane(const InetAddress &ip) const;
/**
* Fill out ZT_ClusterStatus structure (from core API)
*
* @param status Reference to structure to hold result (anything there is replaced)
*/
void status(ZT_ClusterStatus &status) const;
private:
void _send(uint16_t memberId,StateMessageType type,const void *msg,unsigned int len);
void _flush(uint16_t memberId);
void _doREMOTE_WHOIS(uint64_t fromMemberId,const Packet &remotep);
void _doREMOTE_MULTICAST_GATHER(uint64_t fromMemberId,const Packet &remotep);
// These are initialized in the constructor and remain immutable ------------
uint16_t _masterSecret[ZT_SHA512_DIGEST_LEN / sizeof(uint16_t)];
unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
const RuntimeEnvironment *RR;
_ClusterSendQueue *const _sendQueue;
void (*_sendFunction)(void *,unsigned int,const void *,unsigned int);
void *_sendFunctionArg;
int (*_addressToLocationFunction)(void *,const struct sockaddr_storage *,int *,int *,int *);
void *_addressToLocationFunctionArg;
const int32_t _x;
const int32_t _y;
const int32_t _z;
const uint16_t _id;
const std::vector<InetAddress> _zeroTierPhysicalEndpoints;
// end immutable fields -----------------------------------------------------
struct _Member
{
unsigned char key[ZT_PEER_SECRET_KEY_LENGTH];
uint64_t lastReceivedAliveAnnouncement;
uint64_t lastAnnouncedAliveTo;
uint64_t load;
uint64_t peers;
int32_t x,y,z;
std::vector<InetAddress> zeroTierPhysicalEndpoints;
Buffer<ZT_CLUSTER_MAX_MESSAGE_LENGTH> q;
Mutex lock;
inline void clear()
{
lastReceivedAliveAnnouncement = 0;
lastAnnouncedAliveTo = 0;
load = 0;
peers = 0;
x = 0;
y = 0;
z = 0;
zeroTierPhysicalEndpoints.clear();
q.clear();
}
_Member() { this->clear(); }
~_Member() { Utils::burn(key,sizeof(key)); }
};
_Member *const _members;
std::vector<uint16_t> _memberIds;
Mutex _memberIds_m;
struct _RemotePeer
{
_RemotePeer() : lastHavePeerReceived(0),lastSentWantPeer(0) {}
~_RemotePeer() { Utils::burn(key,ZT_PEER_SECRET_KEY_LENGTH); }
uint64_t lastHavePeerReceived;
uint64_t lastSentWantPeer;
uint8_t key[ZT_PEER_SECRET_KEY_LENGTH]; // secret key from identity agreement
};
std::map< std::pair<Address,unsigned int>,_RemotePeer > _remotePeers; // we need ordered behavior and lower_bound here
Mutex _remotePeers_m;
uint64_t _lastFlushed;
uint64_t _lastCleanedRemotePeers;
uint64_t _lastCleanedQueue;
};
} // namespace ZeroTier
#endif // ZT_ENABLE_CLUSTER
#endif

168
attic/ClusterDefinition.hpp

@ -1,168 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
#ifndef ZT_CLUSTERDEFINITION_HPP
#define ZT_CLUSTERDEFINITION_HPP
#ifdef ZT_ENABLE_CLUSTER
#include <vector>
#include <algorithm>
#include "../node/Constants.hpp"
#include "../node/Utils.hpp"
#include "../node/NonCopyable.hpp"
#include "../osdep/OSUtils.hpp"
#include "ClusterGeoIpService.hpp"
namespace ZeroTier {
/**
* Parser for cluster definition file
*/
class ClusterDefinition : NonCopyable
{
public:
struct MemberDefinition
{
MemberDefinition() : id(0),x(0),y(0),z(0) { name[0] = (char)0; }
unsigned int id;
int x,y,z;
char name[256];
InetAddress clusterEndpoint;
std::vector<InetAddress> zeroTierEndpoints;
};
/**
* Load and initialize cluster definition and GeoIP data if any
*
* @param myAddress My ZeroTier address
* @param pathToClusterFile Path to cluster definition file
* @throws std::runtime_error Invalid cluster definition or unable to load data
*/
ClusterDefinition(uint64_t myAddress,const char *pathToClusterFile)
{
std::string cf;
if (!OSUtils::readFile(pathToClusterFile,cf))
return;
char myAddressStr[64];
Utils::ztsnprintf(myAddressStr,sizeof(myAddressStr),"%.10llx",myAddress);
std::vector<std::string> lines(OSUtils::split(cf.c_str(),"\r\n","",""));
for(std::vector<std::string>::iterator l(lines.begin());l!=lines.end();++l) {
std::vector<std::string> fields(OSUtils::split(l->c_str()," \t","",""));
if ((fields.size() < 5)||(fields[0][0] == '#')||(fields[0] != myAddressStr))
continue;
// <address> geo <CSV path> <ip start column> <ip end column> <latitutde column> <longitude column>
if (fields[1] == "geo") {
if ((fields.size() >= 7)&&(OSUtils::fileExists(fields[2].c_str()))) {
int ipStartColumn = Utils::strToInt(fields[3].c_str());
int ipEndColumn = Utils::strToInt(fields[4].c_str());
int latitudeColumn = Utils::strToInt(fields[5].c_str());
int longitudeColumn = Utils::strToInt(fields[6].c_str());
if (_geo.load(fields[2].c_str(),ipStartColumn,ipEndColumn,latitudeColumn,longitudeColumn) <= 0)
throw std::runtime_error(std::string("failed to load geo-ip data from ")+fields[2]);
}
continue;
}
// <address> <ID> <name> <backplane IP/port(s)> <ZT frontplane IP/port(s)> <x,y,z>
int id = Utils::strToUInt(fields[1].c_str());
if ((id < 0)||(id > ZT_CLUSTER_MAX_MEMBERS))
throw std::runtime_error(std::string("invalid cluster member ID: ")+fields[1]);
MemberDefinition &md = _md[id];
md.id = (unsigned int)id;
if (fields.size() >= 6) {
std::vector<std::string> xyz(OSUtils::split(fields[5].c_str(),",","",""));
md.x = (xyz.size() > 0) ? Utils::strToInt(xyz[0].c_str()) : 0;
md.y = (xyz.size() > 1) ? Utils::strToInt(xyz[1].c_str()) : 0;
md.z = (xyz.size() > 2) ? Utils::strToInt(xyz[2].c_str()) : 0;
}
Utils::scopy(md.name,sizeof(md.name),fields[2].c_str());
md.clusterEndpoint.fromString(fields[3]);
if (!md.clusterEndpoint)
continue;
std::vector<std::string> zips(OSUtils::split(fields[4].c_str(),",","",""));
for(std::vector<std::string>::iterator zip(zips.begin());zip!=zips.end();++zip) {
InetAddress i;
i.fromString(*zip);
if (i)
md.zeroTierEndpoints.push_back(i);
}
_ids.push_back((unsigned int)id);
}
std::sort(_ids.begin(),_ids.end());
}
/**
* @return All member definitions in this cluster by ID (ID is array index)
*/
inline const MemberDefinition &operator[](unsigned int id) const throw() { return _md[id]; }
/**
* @return Number of members in this cluster
*/
inline unsigned int size() const throw() { return (unsigned int)_ids.size(); }
/**
* @return IDs of members in this cluster sorted by ID
*/
inline const std::vector<unsigned int> &ids() const throw() { return _ids; }
/**
* @return GeoIP service for this cluster
*/
inline ClusterGeoIpService &geo() throw() { return _geo; }
/**
* @return A vector (new copy) containing all cluster members
*/
inline std::vector<MemberDefinition> members() const
{
std::vector<MemberDefinition> m;
for(std::vector<unsigned int>::const_iterator i(_ids.begin());i!=_ids.end();++i)
m.push_back(_md[*i]);
return m;
}
private:
MemberDefinition _md[ZT_CLUSTER_MAX_MEMBERS];
std::vector<unsigned int> _ids;
ClusterGeoIpService _geo;
};
} // namespace ZeroTier
#endif // ZT_ENABLE_CLUSTER
#endif

243
attic/ClusterGeoIpService.cpp

@ -1,243 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
#ifdef ZT_ENABLE_CLUSTER
#include <math.h>
#include <cmath>
#include "ClusterGeoIpService.hpp"
#include "../node/Utils.hpp"
#include "../osdep/OSUtils.hpp"
#define ZT_CLUSTERGEOIPSERVICE_FILE_MODIFICATION_CHECK_EVERY 10000
namespace ZeroTier {
ClusterGeoIpService::ClusterGeoIpService() :
_pathToCsv(),
_ipStartColumn(-1),
_ipEndColumn(-1),
_latitudeColumn(-1),
_longitudeColumn(-1),
_lastFileCheckTime(0),
_csvModificationTime(0),
_csvFileSize(0)
{
}
ClusterGeoIpService::~ClusterGeoIpService()
{
}
bool ClusterGeoIpService::locate(const InetAddress &ip,int &x,int &y,int &z)
{
Mutex::Lock _l(_lock);
if ((_pathToCsv.length() > 0)&&((OSUtils::now() - _lastFileCheckTime) > ZT_CLUSTERGEOIPSERVICE_FILE_MODIFICATION_CHECK_EVERY)) {
_lastFileCheckTime = OSUtils::now();
if ((_csvFileSize != OSUtils::getFileSize(_pathToCsv.c_str()))||(_csvModificationTime != OSUtils::getLastModified(_pathToCsv.c_str())))
_load(_pathToCsv.c_str(),_ipStartColumn,_ipEndColumn,_latitudeColumn,_longitudeColumn);
}
/* We search by looking up the upper bound of the sorted vXdb vectors
* and then iterating down for a matching IP range. We stop when we hit
* the beginning or an entry whose start and end are before the IP we
* are searching. */
if ((ip.ss_family == AF_INET)&&(_v4db.size() > 0)) {
_V4E key;
key.start = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&ip)->sin_addr.s_addr));
std::vector<_V4E>::const_iterator i(std::upper_bound(_v4db.begin(),_v4db.end(),key));
while (i != _v4db.begin()) {
--i;
if ((key.start >= i->start)&&(key.start <= i->end)) {
x = i->x;
y = i->y;
z = i->z;
//printf("%s : %f,%f %d,%d,%d\n",ip.toIpString().c_str(),i->lat,i->lon,x,y,z);
return true;
} else if ((key.start > i->start)&&(key.start > i->end))
break;
}
} else if ((ip.ss_family == AF_INET6)&&(_v6db.size() > 0)) {
_V6E key;
memcpy(key.start,reinterpret_cast<const struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
std::vector<_V6E>::const_iterator i(std::upper_bound(_v6db.begin(),_v6db.end(),key));
while (i != _v6db.begin()) {
--i;
const int s_vs_s = memcmp(key.start,i->start,16);
const int s_vs_e = memcmp(key.start,i->end,16);
if ((s_vs_s >= 0)&&(s_vs_e <= 0)) {
x = i->x;
y = i->y;
z = i->z;
//printf("%s : %f,%f %d,%d,%d\n",ip.toIpString().c_str(),i->lat,i->lon,x,y,z);
return true;
} else if ((s_vs_s > 0)&&(s_vs_e > 0))
break;
}
}
return false;
}
void ClusterGeoIpService::_parseLine(const char *line,std::vector<_V4E> &v4db,std::vector<_V6E> &v6db,int ipStartColumn,int ipEndColumn,int latitudeColumn,int longitudeColumn)
{
std::vector<std::string> ls(OSUtils::split(line,",\t","\\","\"'"));
if ( ((ipStartColumn >= 0)&&(ipStartColumn < (int)ls.size()))&&
((ipEndColumn >= 0)&&(ipEndColumn < (int)ls.size()))&&
((latitudeColumn >= 0)&&(latitudeColumn < (int)ls.size()))&&
((longitudeColumn >= 0)&&(longitudeColumn < (int)ls.size())) ) {
InetAddress ipStart(ls[ipStartColumn].c_str(),0);
InetAddress ipEnd(ls[ipEndColumn].c_str(),0);
const double lat = strtod(ls[latitudeColumn].c_str(),(char **)0);
const double lon = strtod(ls[longitudeColumn].c_str(),(char **)0);
if ((ipStart.ss_family == ipEnd.ss_family)&&(ipStart)&&(ipEnd)&&(std::isfinite(lat))&&(std::isfinite(lon))) {
const double latRadians = lat * 0.01745329251994; // PI / 180
const double lonRadians = lon * 0.01745329251994; // PI / 180
const double cosLat = cos(latRadians);
const int x = (int)round((-6371.0) * cosLat * cos(lonRadians)); // 6371 == Earth's approximate radius in kilometers
const int y = (int)round(6371.0 * sin(latRadians));
const int z = (int)round(6371.0 * cosLat * sin(lonRadians));
if (ipStart.ss_family == AF_INET) {
v4db.push_back(_V4E());
v4db.back().start = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&ipStart)->sin_addr.s_addr));
v4db.back().end = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&ipEnd)->sin_addr.s_addr));
v4db.back().lat = (float)lat;
v4db.back().lon = (float)lon;
v4db.back().x = x;
v4db.back().y = y;
v4db.back().z = z;
//printf("%s - %s : %d,%d,%d\n",ipStart.toIpString().c_str(),ipEnd.toIpString().c_str(),x,y,z);
} else if (ipStart.ss_family == AF_INET6) {
v6db.push_back(_V6E());
memcpy(v6db.back().start,reinterpret_cast<const struct sockaddr_in6 *>(&ipStart)->sin6_addr.s6_addr,16);
memcpy(v6db.back().end,reinterpret_cast<const struct sockaddr_in6 *>(&ipEnd)->sin6_addr.s6_addr,16);
v6db.back().lat = (float)lat;
v6db.back().lon = (float)lon;
v6db.back().x = x;
v6db.back().y = y;
v6db.back().z = z;
//printf("%s - %s : %d,%d,%d\n",ipStart.toIpString().c_str(),ipEnd.toIpString().c_str(),x,y,z);
}
}
}
}
long ClusterGeoIpService::_load(const char *pathToCsv,int ipStartColumn,int ipEndColumn,int latitudeColumn,int longitudeColumn)
{
// assumes _lock is locked
FILE *f = fopen(pathToCsv,"rb");
if (!f)
return -1;
std::vector<_V4E> v4db;
std::vector<_V6E> v6db;
v4db.reserve(16777216);
v6db.reserve(16777216);
char buf[4096];
char linebuf[1024];
unsigned int lineptr = 0;
for(;;) {
int n = (int)fread(buf,1,sizeof(buf),f);
if (n <= 0)
break;
for(int i=0;i<n;++i) {
if ((buf[i] == '\r')||(buf[i] == '\n')||(buf[i] == (char)0)) {
if (lineptr) {
linebuf[lineptr] = (char)0;
_parseLine(linebuf,v4db,v6db,ipStartColumn,ipEndColumn,latitudeColumn,longitudeColumn);
}
lineptr = 0;
} else if (lineptr < (unsigned int)sizeof(linebuf))
linebuf[lineptr++] = buf[i];
}
}
if (lineptr) {
linebuf[lineptr] = (char)0;
_parseLine(linebuf,v4db,v6db,ipStartColumn,ipEndColumn,latitudeColumn,longitudeColumn);
}
fclose(f);
if ((v4db.size() > 0)||(v6db.size() > 0)) {
std::sort(v4db.begin(),v4db.end());
std::sort(v6db.begin(),v6db.end());
_pathToCsv = pathToCsv;
_ipStartColumn = ipStartColumn;
_ipEndColumn = ipEndColumn;
_latitudeColumn = latitudeColumn;
_longitudeColumn = longitudeColumn;
_lastFileCheckTime = OSUtils::now();
_csvModificationTime = OSUtils::getLastModified(pathToCsv);
_csvFileSize = OSUtils::getFileSize(pathToCsv);
_v4db.swap(v4db);
_v6db.swap(v6db);
return (long)(_v4db.size() + _v6db.size());
} else {
return 0;
}
}
} // namespace ZeroTier
#endif // ZT_ENABLE_CLUSTER
/*
int main(int argc,char **argv)
{
char buf[1024];
ZeroTier::ClusterGeoIpService gip;
printf("loading...\n");
gip.load("/Users/api/Code/ZeroTier/Infrastructure/root-servers/zerotier-one/cluster-geoip.csv",0,1,5,6);
printf("... done!\n"); fflush(stdout);
while (gets(buf)) { // unsafe, testing only
ZeroTier::InetAddress addr(buf,0);
printf("looking up: %s\n",addr.toString().c_str()); fflush(stdout);
int x = 0,y = 0,z = 0;
if (gip.locate(addr,x,y,z)) {
//printf("%s: %d,%d,%d\n",addr.toString().c_str(),x,y,z); fflush(stdout);
} else {
printf("%s: not found!\n",addr.toString().c_str()); fflush(stdout);
}
}
return 0;
}
*/

151
attic/ClusterGeoIpService.hpp

@ -1,151 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
#ifndef ZT_CLUSTERGEOIPSERVICE_HPP
#define ZT_CLUSTERGEOIPSERVICE_HPP
#ifdef ZT_ENABLE_CLUSTER
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <algorithm>
#include "../node/Constants.hpp"
#include "../node/Mutex.hpp"
#include "../node/NonCopyable.hpp"
#include "../node/InetAddress.hpp"
namespace ZeroTier {
/**
* Loads a GeoIP CSV into memory for fast lookup, reloading as needed
*
* This was designed around the CSV from https://db-ip.com but can be used
* with any similar GeoIP CSV database that is presented in the form of an
* IP range and lat/long coordinates.
*
* It loads the whole database into memory, which can be kind of large. If
* the CSV file changes, the changes are loaded automatically.
*/
class ClusterGeoIpService : NonCopyable
{
public:
ClusterGeoIpService();
~ClusterGeoIpService();
/**
* Load or reload CSV file
*
* CSV column indexes start at zero. CSVs can be quoted with single or
* double quotes. Whitespace before or after commas is ignored. Backslash
* may be used for escaping whitespace as well.
*
* @param pathToCsv Path to (uncompressed) CSV file
* @param ipStartColumn Column with IP range start
* @param ipEndColumn Column with IP range end (inclusive)
* @param latitudeColumn Column with latitude
* @param longitudeColumn Column with longitude
* @return Number of valid records loaded or -1 on error (invalid file, not found, etc.)
*/
inline long load(const char *pathToCsv,int ipStartColumn,int ipEndColumn,int latitudeColumn,int longitudeColumn)
{
Mutex::Lock _l(_lock);
return _load(pathToCsv,ipStartColumn,ipEndColumn,latitudeColumn,longitudeColumn);
}
/**
* Attempt to locate an IP
*
* This returns true if x, y, and z are set. If the return value is false
* the values of x, y, and z are undefined.
*
* @param ip IPv4 or IPv6 address
* @param x Reference to variable to receive X
* @param y Reference to variable to receive Y
* @param z Reference to variable to receive Z
* @return True if coordinates were set
*/
bool locate(const InetAddress &ip,int &x,int &y,int &z);
/**
* @return True if IP database/service is available for queries (otherwise locate() will always be false)
*/
inline bool available() const
{
Mutex::Lock _l(_lock);
return ((_v4db.size() + _v6db.size()) > 0);
}
private:
struct _V4E
{
uint32_t start;
uint32_t end;
float lat,lon;
int16_t x,y,z;
inline bool operator<(const _V4E &e) const { return (start < e.start); }
};
struct _V6E
{
uint8_t start[16];
uint8_t end[16];
float lat,lon;
int16_t x,y,z;
inline bool operator<(const _V6E &e) const { return (memcmp(start,e.start,16) < 0); }
};
static void _parseLine(const char *line,std::vector<_V4E> &v4db,std::vector<_V6E> &v6db,int ipStartColumn,int ipEndColumn,int latitudeColumn,int longitudeColumn);
long _load(const char *pathToCsv,int ipStartColumn,int ipEndColumn,int latitudeColumn,int longitudeColumn);
std::string _pathToCsv;
int _ipStartColumn;
int _ipEndColumn;
int _latitudeColumn;
int _longitudeColumn;
uint64_t _lastFileCheckTime;
uint64_t _csvModificationTime;
int64_t _csvFileSize;
std::vector<_V4E> _v4db;
std::vector<_V6E> _v6db;
Mutex _lock;
};
} // namespace ZeroTier
#endif // ZT_ENABLE_CLUSTER
#endif

101
attic/FCV.hpp

@ -1,101 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
#include "Constants.hpp"
namespace ZeroTier {
/**
* A really simple fixed capacity vector
*
* This class does no bounds checking, so the user must ensure that
* no more than C elements are ever added and that accesses are in
* bounds.
*
* @tparam T Type to contain
* @tparam C Capacity of vector
*/
template<typename T,unsigned long C>
class FCV
{
public:
FCV() : _s(0) {}
~FCV() { clear(); }
FCV(const FCV &v) :
_s(v._s)
{
for(unsigned long i=0;i<_s;++i) {
new (reinterpret_cast<T *>(_mem + (sizeof(T) * i))) T(reinterpret_cast<const T *>(v._mem)[i]);
}
}
inline FCV &operator=(const FCV &v)
{
clear();
_s = v._s;
for(unsigned long i=0;i<_s;++i) {
new (reinterpret_cast<T *>(_mem + (sizeof(T) * i))) T(reinterpret_cast<const T *>(v._mem)[i]);
}
return *this;
}
typedef T * iterator;
typedef const T * const_iterator;
typedef unsigned long size_type;
inline iterator begin() { return (T *)_mem; }
inline iterator end() { return (T *)(_mem + (sizeof(T) * _s)); }
inline iterator begin() const { return (const T *)_mem; }
inline iterator end() const { return (const T *)(_mem + (sizeof(T) * _s)); }
inline T &operator[](const size_type i) { return reinterpret_cast<T *>(_mem)[i]; }
inline const T &operator[](const size_type i) const { return reinterpret_cast<const T *>(_mem)[i]; }
inline T &front() { return reinterpret_cast<T *>(_mem)[0]; }
inline const T &front() const { return reinterpret_cast<const T *>(_mem)[0]; }
inline T &back() { return reinterpret_cast<T *>(_mem)[_s - 1]; }
inline const T &back() const { return reinterpret_cast<const T *>(_mem)[_s - 1]; }
inline void push_back(const T &v) { new (reinterpret_cast<T *>(_mem + (sizeof(T) * _s++))) T(v); }
inline void pop_back() { reinterpret_cast<T *>(_mem + (sizeof(T) * --_s))->~T(); }
inline size_type size() const { return _s; }
inline size_type capacity() const { return C; }
inline void clear()
{
for(unsigned long i=0;i<_s;++i)
reinterpret_cast<T *>(_mem + (sizeof(T) * i))->~T();
_s = 0;
}
private:
char _mem[sizeof(T) * C];
unsigned long _s;
};
} // namespace ZeroTier

650
attic/OSXEthernetTap.cpp.pcap-with-bridge-test

@ -1,650 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <sys/cdefs.h>
#include <sys/uio.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/route.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_dl.h>
#include <net/if_media.h>
#include <netinet6/in6_var.h>
#include <netinet/in_var.h>
#include <netinet/icmp6.h>
#include <pcap/pcap.h>
// OSX compile fix... in6_var defines this in a struct which namespaces it for C++ ... why?!?
struct prf_ra {
u_char onlink : 1;
u_char autonomous : 1;
u_char reserved : 6;
} prf_ra;
#include <netinet6/nd6.h>
#include <ifaddrs.h>
// These are KERNEL_PRIVATE... why?
#ifndef SIOCAUTOCONF_START
#define SIOCAUTOCONF_START _IOWR('i', 132, struct in6_ifreq) /* accept rtadvd on this interface */
#endif
#ifndef SIOCAUTOCONF_STOP
#define SIOCAUTOCONF_STOP _IOWR('i', 133, struct in6_ifreq) /* stop accepting rtadv for this interface */
#endif
#ifndef ETH_ALEN
#define ETH_ALEN 6
#endif
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// This source is from:
// http://www.opensource.apple.com/source/Libinfo/Libinfo-406.17/gen.subproj/getifmaddrs.c?txt
// It's here because OSX 10.6 does not have this convenience function.
#define SALIGN (sizeof(uint32_t) - 1)
#define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : \
(SALIGN + 1))
#define MAX_SYSCTL_TRY 5
#define RTA_MASKS (RTA_GATEWAY | RTA_IFP | RTA_IFA)
/* FreeBSD uses NET_RT_IFMALIST and RTM_NEWMADDR from <sys/socket.h> */
/* We can use NET_RT_IFLIST2 and RTM_NEWMADDR2 on Darwin */
//#define DARWIN_COMPAT
//#ifdef DARWIN_COMPAT
#define GIM_SYSCTL_MIB NET_RT_IFLIST2
#define GIM_RTM_ADDR RTM_NEWMADDR2
//#else
//#define GIM_SYSCTL_MIB NET_RT_IFMALIST
//#define GIM_RTM_ADDR RTM_NEWMADDR
//#endif
// Not in 10.6 includes so use our own
struct _intl_ifmaddrs {
struct _intl_ifmaddrs *ifma_next;
struct sockaddr *ifma_name;
struct sockaddr *ifma_addr;
struct sockaddr *ifma_lladdr;
};
static inline int _intl_getifmaddrs(struct _intl_ifmaddrs **pif)
{
int icnt = 1;
int dcnt = 0;
int ntry = 0;
size_t len;
size_t needed;
int mib[6];
int i;
char *buf;
char *data;
char *next;
char *p;
struct ifma_msghdr2 *ifmam;
struct _intl_ifmaddrs *ifa, *ift;
struct rt_msghdr *rtm;
struct sockaddr *sa;
mib[0] = CTL_NET;
mib[1] = PF_ROUTE;
mib[2] = 0; /* protocol */
mib[3] = 0; /* wildcard address family */
mib[4] = GIM_SYSCTL_MIB;
mib[5] = 0; /* no flags */
do {
if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
return (-1);
if ((buf = (char *)malloc(needed)) == NULL)
return (-1);
if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) {
free(buf);
return (-1);
}
free(buf);
buf = NULL;
}
} while (buf == NULL);
for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
rtm = (struct rt_msghdr *)(void *)next;
if (rtm->rtm_version != RTM_VERSION)
continue;
switch (rtm->rtm_type) {
case GIM_RTM_ADDR:
ifmam = (struct ifma_msghdr2 *)(void *)rtm;
if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
break;
icnt++;
p = (char *)(ifmam + 1);
for (i = 0; i < RTAX_MAX; i++) {
if ((RTA_MASKS & ifmam->ifmam_addrs &
(1 << i)) == 0)
continue;
sa = (struct sockaddr *)(void *)p;
len = SA_RLEN(sa);
dcnt += len;
p += len;
}
break;
}
}
data = (char *)malloc(sizeof(struct _intl_ifmaddrs) * icnt + dcnt);
if (data == NULL) {
free(buf);
return (-1);
}
ifa = (struct _intl_ifmaddrs *)(void *)data;
data += sizeof(struct _intl_ifmaddrs) * icnt;
memset(ifa, 0, sizeof(struct _intl_ifmaddrs) * icnt);
ift = ifa;
for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
rtm = (struct rt_msghdr *)(void *)next;
if (rtm->rtm_version != RTM_VERSION)
continue;
switch (rtm->rtm_type) {
case GIM_RTM_ADDR:
ifmam = (struct ifma_msghdr2 *)(void *)rtm;
if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
break;
p = (char *)(ifmam + 1);
for (i = 0; i < RTAX_MAX; i++) {
if ((RTA_MASKS & ifmam->ifmam_addrs &
(1 << i)) == 0)
continue;
sa = (struct sockaddr *)(void *)p;
len = SA_RLEN(sa);
switch (i) {
case RTAX_GATEWAY:
ift->ifma_lladdr =
(struct sockaddr *)(void *)data;
memcpy(data, p, len);
data += len;
break;
case RTAX_IFP:
ift->ifma_name =
(struct sockaddr *)(void *)data;
memcpy(data, p, len);
data += len;
break;
case RTAX_IFA:
ift->ifma_addr =
(struct sockaddr *)(void *)data;
memcpy(data, p, len);
data += len;
break;
default:
data += len;
break;
}
p += len;
}
ift->ifma_next = ift + 1;
ift = ift->ifma_next;
break;
}
}
free(buf);
if (ift > ifa) {
ift--;
ift->ifma_next = NULL;
*pif = ifa;
} else {
*pif = NULL;
free(ifa);
}
return (0);
}
static inline void _intl_freeifmaddrs(struct _intl_ifmaddrs *ifmp)
{
free(ifmp);
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include "../node/Constants.hpp"
#include "../node/Utils.hpp"
#include "../node/Mutex.hpp"
#include "../node/Dictionary.hpp"
#include "OSUtils.hpp"
#include "OSXEthernetTap.hpp"
// ff:ff:ff:ff:ff:ff with no ADI
static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
static inline bool _setIpv6Stuff(const char *ifname,bool performNUD,bool acceptRouterAdverts)
{
struct in6_ndireq nd;
struct in6_ifreq ifr;
int s = socket(AF_INET6,SOCK_DGRAM,0);
if (s <= 0)
return false;
memset(&nd,0,sizeof(nd));
strncpy(nd.ifname,ifname,sizeof(nd.ifname));
if (ioctl(s,SIOCGIFINFO_IN6,&nd)) {
close(s);
return false;
}
unsigned long oldFlags = (unsigned long)nd.ndi.flags;
if (performNUD)
nd.ndi.flags |= ND6_IFF_PERFORMNUD;
else nd.ndi.flags &= ~ND6_IFF_PERFORMNUD;
if (oldFlags != (unsigned long)nd.ndi.flags) {
if (ioctl(s,SIOCSIFINFO_FLAGS,&nd)) {
close(s);
return false;
}
}
memset(&ifr,0,sizeof(ifr));
strncpy(ifr.ifr_name,ifname,sizeof(ifr.ifr_name));
if (ioctl(s,acceptRouterAdverts ? SIOCAUTOCONF_START : SIOCAUTOCONF_STOP,&ifr)) {
close(s);
return false;
}
close(s);
return true;
}
namespace ZeroTier {
static std::set<std::string> globalDeviceNames;
static Mutex globalTapCreateLock;
OSXEthernetTap::OSXEthernetTap(
const char *homePath,
const MAC &mac,
unsigned int mtu,
unsigned int metric,
uint64_t nwid,
const char *friendlyName,
void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *data,unsigned int len),
void *arg) :
_handler(handler),
_arg(arg),
_pcap((void *)0),
_nwid(nwid),
_mac(mac),
_homePath(homePath),
_mtu(mtu),
_metric(metric),
_enabled(true)
{
char errbuf[PCAP_ERRBUF_SIZE];
char devname[64],ethaddr[64],mtustr[32],metstr[32],nwids[32];
Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
if (mtu > 2800)
throw std::runtime_error("max tap MTU is 2800");
Mutex::Lock _gl(globalTapCreateLock);
std::string desiredDevice;
Dictionary devmap;
{
std::string devmapbuf;
if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmapbuf)) {
devmap.fromString(devmapbuf);
desiredDevice = devmap.get(nwids,"");
}
}
if ((desiredDevice.length() >= 9)&&(desiredDevice.substr(0,6) == "bridge")) {
// length() >= 9 matches bridge### or bridge####
_dev = desiredDevice;
} else {
if (globalDeviceNames.size() >= (10000 - 128)) // sanity check... this would be nuts
throw std::runtime_error("too many devices!");
unsigned int pseudoBridgeNo = (unsigned int)((nwid ^ (nwid >> 32)) % (10000 - 128)) + 128; // range: bridge128 to bridge9999
sprintf(devname,"bridge%u",pseudoBridgeNo);
while (globalDeviceNames.count(std::string(devname)) > 0) {
++pseudoBridgeNo;
if (pseudoBridgeNo > 9999)
pseudoBridgeNo = 64;
sprintf(devname,"bridge%u",pseudoBridgeNo);
}
_dev = devname;
}
// Configure MAC address and MTU, bring interface up
long cpid = (long)vfork();
if (cpid == 0) {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"create",(const char *)0);
::_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
if (exitcode != 0)
throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
} else throw std::runtime_error("unable to fork()");
Utils::snprintf(ethaddr,sizeof(ethaddr),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(int)mac[0],(int)mac[1],(int)mac[2],(int)mac[3],(int)mac[4],(int)mac[5]);
Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
cpid = (long)vfork();
if (cpid == 0) {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"metric",metstr,"up",(const char *)0);
::_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
if (exitcode != 0)
throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
} else throw std::runtime_error("unable to fork()");
_setIpv6Stuff(_dev.c_str(),true,false);
_pcap = (void *)pcap_create(_dev.c_str(),errbuf);
if (!_pcap) {
cpid = (long)vfork();
if (cpid == 0) {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
::_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
}
throw std::runtime_error((std::string("pcap_create() on new bridge device failed: ") + errbuf).c_str());
}
pcap_set_promisc(reinterpret_cast<pcap_t *>(_pcap),1);
pcap_set_timeout(reinterpret_cast<pcap_t *>(_pcap),120000);
pcap_set_immediate_mode(reinterpret_cast<pcap_t *>(_pcap),1);
if (pcap_set_buffer_size(reinterpret_cast<pcap_t *>(_pcap),1024 * 1024 * 16) != 0) // 16MB
fprintf(stderr,"WARNING: pcap_set_buffer_size() failed!\n");
if (pcap_set_snaplen(reinterpret_cast<pcap_t *>(_pcap),4096) != 0)
fprintf(stderr,"WARNING: pcap_set_snaplen() failed!\n");
if (pcap_activate(reinterpret_cast<pcap_t *>(_pcap)) != 0) {
pcap_close(reinterpret_cast<pcap_t *>(_pcap));
cpid = (long)vfork();
if (cpid == 0) {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
::_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
}
throw std::runtime_error("pcap_activate() on new bridge device failed.");
}
globalDeviceNames.insert(_dev);
devmap[nwids] = _dev;
OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmap.toString());
_thread = Thread::start(this);
}
OSXEthernetTap::~OSXEthernetTap()
{
_enabled = false;
Mutex::Lock _gl(globalTapCreateLock);
globalDeviceNames.erase(_dev);
long cpid = (long)vfork();
if (cpid == 0) {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
::_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
if (exitcode == 0) {
// Destroying the interface nukes pcap and terminates the thread.
Thread::join(_thread);
}
}
pcap_close(reinterpret_cast<pcap_t *>(_pcap));
}
static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
{
long cpid = (long)vfork();
if (cpid == 0) {
execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
waitpid(cpid,&exitcode,0);
return (exitcode == 0);
}
return false; // never reached, make compiler shut up about return value
}
bool OSXEthernetTap::addIp(const InetAddress &ip)
{
if (!ip)
return false;
std::vector<InetAddress> allIps(ips());
if (std::binary_search(allIps.begin(),allIps.end(),ip))
return true;
// Remove and reconfigure if address is the same but netmask is different
for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
if (___removeIp(_dev,*i))
break;
}
}
long cpid = (long)vfork();
if (cpid == 0) {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
::_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
return (exitcode == 0);
} // else return false...
return false;
}
bool OSXEthernetTap::removeIp(const InetAddress &ip)
{
if (!ip)
return true;
std::vector<InetAddress> allIps(ips());
if (!std::binary_search(allIps.begin(),allIps.end(),ip)) {
if (___removeIp(_dev,ip))
return true;
}
return false;
}
std::vector<InetAddress> OSXEthernetTap::ips() const
{
struct ifaddrs *ifa = (struct ifaddrs *)0;
if (getifaddrs(&ifa))
return std::vector<InetAddress>();
std::vector<InetAddress> r;
struct ifaddrs *p = ifa;
while (p) {
if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
switch(p->ifa_addr->sa_family) {
case AF_INET: {
struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
} break;
case AF_INET6: {
struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
uint32_t b[4];
memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
r.push_back(InetAddress(sin->sin6_addr.s6_addr,16,Utils::countBits(b[0]) + Utils::countBits(b[1]) + Utils::countBits(b[2]) + Utils::countBits(b[3])));
} break;
}
}
p = p->ifa_next;
}
if (ifa)
freeifaddrs(ifa);
std::sort(r.begin(),r.end());
std::unique(r.begin(),r.end());
return r;
}
void OSXEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
{
char putBuf[4096];
if ((len <= _mtu)&&(_enabled)) {
to.copyTo(putBuf,6);
from.copyTo(putBuf + 6,6);
*((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
memcpy(putBuf + 14,data,len);
len += 14;
int r = pcap_inject(reinterpret_cast<pcap_t *>(_pcap),putBuf,len);
if (r <= 0) {
printf("%s: pcap_inject() failed\n",_dev.c_str());
return;
}
printf("%s: inject %s -> %s etherType==%u len=%u r==%d\n",_dev.c_str(),from.toString().c_str(),to.toString().c_str(),etherType,len,r);
}
}
std::string OSXEthernetTap::deviceName() const
{
return _dev;
}
void OSXEthernetTap::setFriendlyName(const char *friendlyName)
{
}
void OSXEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
{
std::vector<MulticastGroup> newGroups;
struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
if (!_intl_getifmaddrs(&ifmap)) {
struct _intl_ifmaddrs *p = ifmap;
while (p) {
if (p->ifma_addr->sa_family == AF_LINK) {
struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
}
p = p->ifma_next;
}
_intl_freeifmaddrs(ifmap);
}
std::vector<InetAddress> allIps(ips());
for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
std::sort(newGroups.begin(),newGroups.end());
std::unique(newGroups.begin(),newGroups.end());
for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
added.push_back(*m);
}
for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
removed.push_back(*m);
}
_multicastGroups.swap(newGroups);
}
static void _pcapHandler(u_char *ptr,const struct pcap_pkthdr *hdr,const u_char *data)
{
OSXEthernetTap *tap = reinterpret_cast<OSXEthernetTap *>(ptr);
if (hdr->caplen > 14) {
MAC to(data,6);
MAC from(data + 6,6);
if (from == tap->_mac) {
unsigned int etherType = ntohs(((const uint16_t *)data)[6]);
printf("%s: %s -> %s etherType==%u len==%u\n",tap->_dev.c_str(),from.toString().c_str(),to.toString().c_str(),etherType,(unsigned int)hdr->caplen);
// TODO: VLAN support
tap->_handler(tap->_arg,tap->_nwid,from,to,etherType,0,(const void *)(data + 14),hdr->len - 14);
}
}
}
void OSXEthernetTap::threadMain()
throw()
{
pcap_loop(reinterpret_cast<pcap_t *>(_pcap),-1,&_pcapHandler,reinterpret_cast<u_char *>(this));
}
} // namespace ZeroTier

831
attic/OSXEthernetTap.cpp.utun-work-in-progress

@ -1,831 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <sys/cdefs.h>
#include <sys/uio.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/sys_domain.h>
#include <sys/kern_control.h>
#include <net/if_utun.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/route.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_dl.h>
#include <net/if_media.h>
#include <netinet6/in6_var.h>
#include <netinet/in_var.h>
#include <netinet/icmp6.h>
// OSX compile fix... in6_var defines this in a struct which namespaces it for C++ ... why?!?
struct prf_ra {
u_char onlink : 1;
u_char autonomous : 1;
u_char reserved : 6;
} prf_ra;
#include <netinet6/nd6.h>
#include <ifaddrs.h>
// These are KERNEL_PRIVATE... why?
#ifndef SIOCAUTOCONF_START
#define SIOCAUTOCONF_START _IOWR('i', 132, struct in6_ifreq) /* accept rtadvd on this interface */
#endif
#ifndef SIOCAUTOCONF_STOP
#define SIOCAUTOCONF_STOP _IOWR('i', 133, struct in6_ifreq) /* stop accepting rtadv for this interface */
#endif
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// This source is from:
// http://www.opensource.apple.com/source/Libinfo/Libinfo-406.17/gen.subproj/getifmaddrs.c?txt
// It's here because OSX 10.6 does not have this convenience function.
#define SALIGN (sizeof(uint32_t) - 1)
#define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : \
(SALIGN + 1))
#define MAX_SYSCTL_TRY 5
#define RTA_MASKS (RTA_GATEWAY | RTA_IFP | RTA_IFA)
/* FreeBSD uses NET_RT_IFMALIST and RTM_NEWMADDR from <sys/socket.h> */
/* We can use NET_RT_IFLIST2 and RTM_NEWMADDR2 on Darwin */
//#define DARWIN_COMPAT
//#ifdef DARWIN_COMPAT
#define GIM_SYSCTL_MIB NET_RT_IFLIST2
#define GIM_RTM_ADDR RTM_NEWMADDR2
//#else
//#define GIM_SYSCTL_MIB NET_RT_IFMALIST
//#define GIM_RTM_ADDR RTM_NEWMADDR
//#endif
// Not in 10.6 includes so use our own
struct _intl_ifmaddrs {
struct _intl_ifmaddrs *ifma_next;
struct sockaddr *ifma_name;
struct sockaddr *ifma_addr;
struct sockaddr *ifma_lladdr;
};
static inline int _intl_getifmaddrs(struct _intl_ifmaddrs **pif)
{
int icnt = 1;
int dcnt = 0;
int ntry = 0;
size_t len;
size_t needed;
int mib[6];
int i;
char *buf;
char *data;
char *next;
char *p;
struct ifma_msghdr2 *ifmam;
struct _intl_ifmaddrs *ifa, *ift;
struct rt_msghdr *rtm;
struct sockaddr *sa;
mib[0] = CTL_NET;
mib[1] = PF_ROUTE;
mib[2] = 0; /* protocol */
mib[3] = 0; /* wildcard address family */
mib[4] = GIM_SYSCTL_MIB;
mib[5] = 0; /* no flags */
do {
if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
return (-1);
if ((buf = (char *)malloc(needed)) == NULL)
return (-1);
if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) {
free(buf);
return (-1);
}
free(buf);
buf = NULL;
}
} while (buf == NULL);
for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
rtm = (struct rt_msghdr *)(void *)next;
if (rtm->rtm_version != RTM_VERSION)
continue;
switch (rtm->rtm_type) {
case GIM_RTM_ADDR:
ifmam = (struct ifma_msghdr2 *)(void *)rtm;
if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
break;
icnt++;
p = (char *)(ifmam + 1);
for (i = 0; i < RTAX_MAX; i++) {
if ((RTA_MASKS & ifmam->ifmam_addrs &
(1 << i)) == 0)
continue;
sa = (struct sockaddr *)(void *)p;
len = SA_RLEN(sa);
dcnt += len;
p += len;
}
break;
}
}
data = (char *)malloc(sizeof(struct _intl_ifmaddrs) * icnt + dcnt);
if (data == NULL) {
free(buf);
return (-1);
}
ifa = (struct _intl_ifmaddrs *)(void *)data;
data += sizeof(struct _intl_ifmaddrs) * icnt;
memset(ifa, 0, sizeof(struct _intl_ifmaddrs) * icnt);
ift = ifa;
for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
rtm = (struct rt_msghdr *)(void *)next;
if (rtm->rtm_version != RTM_VERSION)
continue;
switch (rtm->rtm_type) {
case GIM_RTM_ADDR:
ifmam = (struct ifma_msghdr2 *)(void *)rtm;
if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
break;
p = (char *)(ifmam + 1);
for (i = 0; i < RTAX_MAX; i++) {
if ((RTA_MASKS & ifmam->ifmam_addrs &
(1 << i)) == 0)
continue;
sa = (struct sockaddr *)(void *)p;
len = SA_RLEN(sa);
switch (i) {
case RTAX_GATEWAY:
ift->ifma_lladdr =
(struct sockaddr *)(void *)data;
memcpy(data, p, len);
data += len;
break;
case RTAX_IFP:
ift->ifma_name =
(struct sockaddr *)(void *)data;
memcpy(data, p, len);
data += len;
break;
case RTAX_IFA:
ift->ifma_addr =
(struct sockaddr *)(void *)data;
memcpy(data, p, len);
data += len;
break;
default:
data += len;
break;
}
p += len;
}
ift->ifma_next = ift + 1;
ift = ift->ifma_next;
break;
}
}
free(buf);
if (ift > ifa) {
ift--;
ift->ifma_next = NULL;
*pif = ifa;
} else {
*pif = NULL;
free(ifa);
}
return (0);
}
static inline void _intl_freeifmaddrs(struct _intl_ifmaddrs *ifmp)
{
free(ifmp);
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include "../node/Constants.hpp"
#include "../node/Utils.hpp"
#include "../node/Mutex.hpp"
#include "../node/Dictionary.hpp"
#include "Arp.hpp"
#include "OSUtils.hpp"
#include "OSXEthernetTap.hpp"
// ff:ff:ff:ff:ff:ff with no ADI
static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
static inline bool _setIpv6Stuff(const char *ifname,bool performNUD,bool acceptRouterAdverts)
{
struct in6_ndireq nd;
struct in6_ifreq ifr;
int s = socket(AF_INET6,SOCK_DGRAM,0);
if (s <= 0)
return false;
memset(&nd,0,sizeof(nd));
strncpy(nd.ifname,ifname,sizeof(nd.ifname));
if (ioctl(s,SIOCGIFINFO_IN6,&nd)) {
close(s);
return false;
}
unsigned long oldFlags = (unsigned long)nd.ndi.flags;
if (performNUD)
nd.ndi.flags |= ND6_IFF_PERFORMNUD;
else nd.ndi.flags &= ~ND6_IFF_PERFORMNUD;
if (oldFlags != (unsigned long)nd.ndi.flags) {
if (ioctl(s,SIOCSIFINFO_FLAGS,&nd)) {
close(s);
return false;
}
}
memset(&ifr,0,sizeof(ifr));
strncpy(ifr.ifr_name,ifname,sizeof(ifr.ifr_name));
if (ioctl(s,acceptRouterAdverts ? SIOCAUTOCONF_START : SIOCAUTOCONF_STOP,&ifr)) {
close(s);
return false;
}
close(s);
return true;
}
// Create an OSX-native utun device (utun# where # is desiredNumber)
// Adapted from public domain utun example code by Jonathan Levin
static int _make_utun(int desiredNumber)
{
struct sockaddr_ctl sc;
struct ctl_info ctlInfo;
struct ifreq ifr;
memset(&ctlInfo, 0, sizeof(ctlInfo));
if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_name)) >= sizeof(ctlInfo.ctl_name)) {
return -1;
}
int fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
if (fd == -1)
return -1;
if (ioctl(fd, CTLIOCGINFO, &ctlInfo) == -1) {
close(fd);
return -1;
}
sc.sc_id = ctlInfo.ctl_id;
sc.sc_len = sizeof(sc);
sc.sc_family = AF_SYSTEM;
sc.ss_sysaddr = AF_SYS_CONTROL;
sc.sc_unit = desiredNumber + 1;
if (connect(fd, (struct sockaddr *)&sc, sizeof(sc)) == -1) {
close(fd);
return -1;
}
memset(&ifr,0,sizeof(ifr));
sprintf(ifr.ifr_name,"utun%d",desiredNumber);
if (ioctl(fd,SIOCGIFFLAGS,(void *)&ifr) < 0) {
printf("SIOCGIFFLAGS failed\n");
}
ifr.ifr_flags &= ~IFF_POINTOPOINT;
if (ioctl(fd,SIOCSIFFLAGS,(void *)&ifr) < 0) {
printf("clear IFF_POINTOPOINT failed\n");
}
return fd;
}
namespace ZeroTier {
static long globalTapsRunning = 0;
static Mutex globalTapCreateLock;
OSXEthernetTap::OSXEthernetTap(
const char *homePath,
const MAC &mac,
unsigned int mtu,
unsigned int metric,
uint64_t nwid,
const char *friendlyName,
void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *data,unsigned int len),
void *arg) :
_handler(handler),
_arg(arg),
_arp((Arp *)0),
_nwid(nwid),
_homePath(homePath),
_mtu(mtu),
_metric(metric),
_fd(0),
_utun(false),
_enabled(true)
{
char devpath[64],ethaddr[64],mtustr[32],metstr[32],nwids[32];
struct stat stattmp;
Utils::snprintf(nwids,sizeof(nwids),"%.16llx",nwid);
if (mtu > 2800)
throw std::runtime_error("max tap MTU is 2800");
Mutex::Lock _gl(globalTapCreateLock);
// Read remembered previous device name, if any -- we'll try to reuse
Dictionary devmap;
std::string desiredDevice;
{
std::string devmapbuf;
if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmapbuf)) {
devmap.fromString(devmapbuf);
desiredDevice = devmap.get(nwids,"");
}
}
if (::stat((_homePath + ZT_PATH_SEPARATOR_S + "tap.kext").c_str(),&stattmp) == 0) {
// Try to init kext if it's there, otherwise revert to utun mode
if (::stat("/dev/zt0",&stattmp)) {
long kextpid = (long)vfork();
if (kextpid == 0) {
::chdir(homePath);
OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
::execl("/sbin/kextload","/sbin/kextload","-q","-repository",homePath,"tap.kext",(const char *)0);
::_exit(-1);
} else if (kextpid > 0) {
int exitcode = -1;
::waitpid(kextpid,&exitcode,0);
}
::usleep(500); // give tap device driver time to start up and try again
if (::stat("/dev/zt0",&stattmp))
_utun = true;
}
if (!_utun) {
// See if we can re-use the last device we had.
bool recalledDevice = false;
if (desiredDevice.length() > 2) {
Utils::snprintf(devpath,sizeof(devpath),"/dev/%s",desiredDevice.c_str());
if (stat(devpath,&stattmp) == 0) {
_fd = ::open(devpath,O_RDWR);
if (_fd > 0) {
_dev = desiredDevice;
recalledDevice = true;
}
}
}
// Open the first unused tap device if we didn't recall a previous one.
if (!recalledDevice) {
for(int i=0;i<64;++i) {
Utils::snprintf(devpath,sizeof(devpath),"/dev/zt%d",i);
if (stat(devpath,&stattmp)) {
_utun = true;
break;
}
_fd = ::open(devpath,O_RDWR);
if (_fd > 0) {
char foo[16];
Utils::snprintf(foo,sizeof(foo),"zt%d",i);
_dev = foo;
break;
}
}
}
if (_fd <= 0)
_utun = true;
}
} else {
_utun = true;
}
if (_utun) {
// Use OSX built-in utun device if kext is not available or doesn't work
int utunNo = 0;
if ((desiredDevice.length() > 4)&&(desiredDevice.substr(0,4) == "utun")) {
utunNo = Utils::strToInt(desiredDevice.substr(4).c_str());
if (utunNo >= 0)
_fd = _make_utun(utunNo);
}
if (_fd <= 0) {
// Start at utun8 to leave lower utuns unused since other stuff might
// want them -- OpenVPN, cjdns, etc. I'm not sure if those are smart
// enough to scan upward like this.
for(utunNo=8;utunNo<=256;++utunNo) {
if ((_fd = _make_utun(utunNo)) > 0)
break;
}
}
if (_fd <= 0)
throw std::runtime_error("unable to find/load ZeroTier tap driver OR use built-in utun driver in OSX; permission or system problem or too many open devices?");
Utils::snprintf(devpath,sizeof(devpath),"utun%d",utunNo);
_dev = devpath;
// Configure address and bring it up
Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
long cpid = (long)vfork();
if (cpid == 0) {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"mtu",mtustr,"metric",metstr,"up",(const char *)0);
::_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
if (exitcode) {
::close(_fd);
throw std::runtime_error("ifconfig failure activating utun interface");
}
}
} else {
// Use our ZeroTier OSX tun/tap driver for zt# Ethernet tap device
if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
::close(_fd);
throw std::runtime_error("unable to set flags on file descriptor for TAP device");
}
// Configure MAC address and MTU, bring interface up
Utils::snprintf(ethaddr,sizeof(ethaddr),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(int)mac[0],(int)mac[1],(int)mac[2],(int)mac[3],(int)mac[4],(int)mac[5]);
Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
long cpid = (long)vfork();
if (cpid == 0) {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"metric",metstr,"up",(const char *)0);
::_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
if (exitcode) {
::close(_fd);
throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
}
}
_setIpv6Stuff(_dev.c_str(),true,false);
}
// Set close-on-exec so that devices cannot persist if we fork/exec for update
fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
::pipe(_shutdownSignalPipe);
++globalTapsRunning;
devmap[nwids] = _dev;
OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmap.toString());
_thread = Thread::start(this);
}
OSXEthernetTap::~OSXEthernetTap()
{
Mutex::Lock _gl(globalTapCreateLock);
::write(_shutdownSignalPipe[1],(const void *)this,1); // writing a byte causes thread to exit
Thread::join(_thread);
::close(_fd);
::close(_shutdownSignalPipe[0]);
::close(_shutdownSignalPipe[1]);
if (_utun) {
delete _arp;
} else {
if (--globalTapsRunning <= 0) {
globalTapsRunning = 0; // sanity check -- should not be possible
char tmp[16384];
sprintf(tmp,"%s/%s",_homePath.c_str(),"tap.kext");
long kextpid = (long)vfork();
if (kextpid == 0) {
OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
::execl("/sbin/kextunload","/sbin/kextunload",tmp,(const char *)0);
::_exit(-1);
} else if (kextpid > 0) {
int exitcode = -1;
::waitpid(kextpid,&exitcode,0);
}
}
}
}
void OSXEthernetTap::setEnabled(bool en)
{
_enabled = en;
// TODO: interface status change
}
bool OSXEthernetTap::enabled() const
{
return _enabled;
}
static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
{
long cpid = (long)vfork();
if (cpid == 0) {
execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
waitpid(cpid,&exitcode,0);
return (exitcode == 0);
}
return false; // never reached, make compiler shut up about return value
}
bool OSXEthernetTap::addIp(const InetAddress &ip)
{
if (!ip)
return false;
std::vector<InetAddress> allIps(ips());
if (std::binary_search(allIps.begin(),allIps.end(),ip))
return true;
// Remove and reconfigure if address is the same but netmask is different
for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
if (___removeIp(_dev,*i))
break;
}
}
if (_utun) {
long cpid = (long)vfork();
if (cpid == 0) {
if (ip.ss_family == AF_INET6) {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet6",ip.toString().c_str(),"alias",(const char *)0);
} else {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.toString().c_str(),ip.toIpString().c_str(),"alias",(const char *)0);
}
::_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
if (exitcode == 0) {
if (ip.ss_family == AF_INET) {
// Add route to network over tun for IPv4 -- otherwise it behaves
// as a simple point to point tunnel instead of a true route.
cpid = (long)vfork();
if (cpid == 0) {
::close(STDERR_FILENO);
::close(STDOUT_FILENO);
::execl("/sbin/route","/sbin/route","add",ip.network().toString().c_str(),ip.toIpString().c_str(),(const char *)0);
::exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
return (exitcode == 0);
}
} else return true;
}
}
} else {
long cpid = (long)vfork();
if (cpid == 0) {
::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
::_exit(-1);
} else if (cpid > 0) {
int exitcode = -1;
::waitpid(cpid,&exitcode,0);
return (exitcode == 0);
}
}
return false;
}
bool OSXEthernetTap::removeIp(const InetAddress &ip)
{
if (!ip)
return true;
std::vector<InetAddress> allIps(ips());
if (!std::binary_search(allIps.begin(),allIps.end(),ip)) {
if (___removeIp(_dev,ip))
return true;
}
return false;
}
std::vector<InetAddress> OSXEthernetTap::ips() const
{
struct ifaddrs *ifa = (struct ifaddrs *)0;
if (getifaddrs(&ifa))
return std::vector<InetAddress>();
std::vector<InetAddress> r;
struct ifaddrs *p = ifa;
while (p) {
if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
switch(p->ifa_addr->sa_family) {
case AF_INET: {
struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
} break;
case AF_INET6: {
struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
uint32_t b[4];
memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
r.push_back(InetAddress(sin->sin6_addr.s6_addr,16,Utils::countBits(b[0]) + Utils::countBits(b[1]) + Utils::countBits(b[2]) + Utils::countBits(b[3])));
} break;
}
}
p = p->ifa_next;
}
if (ifa)
freeifaddrs(ifa);
std::sort(r.begin(),r.end());
std::unique(r.begin(),r.end());
return r;
}
void OSXEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
{
char putBuf[4096];
if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
to.copyTo(putBuf,6);
from.copyTo(putBuf + 6,6);
*((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
memcpy(putBuf + 14,data,len);
len += 14;
::write(_fd,putBuf,len);
}
}
std::string OSXEthernetTap::deviceName() const
{
return _dev;
}
void OSXEthernetTap::setFriendlyName(const char *friendlyName)
{
}
void OSXEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
{
std::vector<MulticastGroup> newGroups;
struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
if (!_intl_getifmaddrs(&ifmap)) {
struct _intl_ifmaddrs *p = ifmap;
while (p) {
if (p->ifma_addr->sa_family == AF_LINK) {
struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
}
p = p->ifma_next;
}
_intl_freeifmaddrs(ifmap);
}
std::vector<InetAddress> allIps(ips());
for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
std::sort(newGroups.begin(),newGroups.end());
std::unique(newGroups.begin(),newGroups.end());
for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
added.push_back(*m);
}
for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
removed.push_back(*m);
}
_multicastGroups.swap(newGroups);
}
void OSXEthernetTap::threadMain()
throw()
{
fd_set readfds,nullfds;
MAC to,from;
int n,nfds,r;
char getBuf[8194];
Thread::sleep(500);
FD_ZERO(&readfds);
FD_ZERO(&nullfds);
nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
r = 0;
for(;;) {
FD_SET(_shutdownSignalPipe[0],&readfds);
FD_SET(_fd,&readfds);
select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
break;
if (FD_ISSET(_fd,&readfds)) {
n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
if (n < 0) {
if ((errno != EINTR)&&(errno != ETIMEDOUT))
break;
} else {
// Some tap drivers like to send the ethernet frame and the
// payload in two chunks, so handle that by accumulating
// data until we have at least a frame.
r += n;
if (r > 14) {
if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
r = _mtu + 14;
if (_enabled) {
to.setTo(getBuf,6);
from.setTo(getBuf + 6,6);
unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
// TODO: VLAN support
_handler(_arg,_nwid,from,to,etherType,0,(const void *)(getBuf + 14),r - 14);
}
r = 0;
}
}
}
}
}
} // namespace ZeroTier

95
attic/OSXEthernetTap.hpp

@ -1,95 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/
#ifndef ZT_OSXETHERNETTAP_HPP
#define ZT_OSXETHERNETTAP_HPP
#include <stdio.h>
#include <stdlib.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "../node/Constants.hpp"
#include "../node/MAC.hpp"
#include "../node/InetAddress.hpp"
#include "../node/MulticastGroup.hpp"
#include "Thread.hpp"
namespace ZeroTier {
/**
* OSX Ethernet tap using ZeroTier kernel extension zt# devices
*/
class OSXEthernetTap
{
public:
OSXEthernetTap(
const char *homePath,
const MAC &mac,
unsigned int mtu,
unsigned int metric,
uint64_t nwid,
const char *friendlyName,
void (*handler)(void *,void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
void *arg);
~OSXEthernetTap();
void setEnabled(bool en);
bool enabled() const;
bool addIp(const InetAddress &ip);
bool removeIp(const InetAddress &ip);
std::vector<InetAddress> ips() const;
void put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len);
std::string deviceName() const;
void setFriendlyName(const char *friendlyName);
void scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed);
void setMtu(unsigned int mtu);
void threadMain()
throw();
private:
void (*_handler)(void *,void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int);
void *_arg;
uint64_t _nwid;
Thread _thread;
std::string _homePath;
std::string _dev;
std::vector<MulticastGroup> _multicastGroups;
unsigned int _mtu;
unsigned int _metric;
int _fd;
int _shutdownSignalPipe[2];
volatile bool _enabled;
};
} // namespace ZeroTier
#endif

96
attic/OSXEthernetTap.hpp.pcap-with-bridge-test

@ -1,96 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef ZT_OSXETHERNETTAP_HPP
#define ZT_OSXETHERNETTAP_HPP
#include <stdio.h>
#include <stdlib.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "../node/Constants.hpp"
#include "../node/MAC.hpp"
#include "../node/InetAddress.hpp"
#include "../node/MulticastGroup.hpp"
#include "Thread.hpp"
namespace ZeroTier {
/**
* OSX Ethernet tap using ZeroTier kernel extension zt# devices
*/
class OSXEthernetTap
{
public:
OSXEthernetTap(
const char *homePath,
const MAC &mac,
unsigned int mtu,
unsigned int metric,
uint64_t nwid,
const char *friendlyName,
void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
void *arg);
~OSXEthernetTap();
inline void setEnabled(bool en) { _enabled = en; }
inline bool enabled() const { return _enabled; }
bool addIp(const InetAddress &ip);
bool removeIp(const InetAddress &ip);
std::vector<InetAddress> ips() const;
void put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len);
std::string deviceName() const;
void setFriendlyName(const char *friendlyName);
void scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed);
void threadMain()
throw();
// Private members of OSXEthernetTap have public visibility to be accessable
// from an internal bounce function; don't modify directly.
void (*_handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int);
void *_arg;
void *_pcap; // pcap_t *
uint64_t _nwid;
MAC _mac;
Thread _thread;
std::string _homePath;
std::string _dev;
std::vector<MulticastGroup> _multicastGroups;
unsigned int _mtu;
unsigned int _metric;
volatile bool _enabled;
};
} // namespace ZeroTier
#endif

101
attic/OSXEthernetTap.hpp.utun-work-in-progress

@ -1,101 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
#ifndef ZT_OSXETHERNETTAP_HPP
#define ZT_OSXETHERNETTAP_HPP
#include <stdio.h>
#include <stdlib.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "../node/Constants.hpp"
#include "../node/MAC.hpp"
#include "../node/InetAddress.hpp"
#include "../node/MulticastGroup.hpp"
#include "Thread.hpp"
namespace ZeroTier {
class Arp;
/**
* OSX Ethernet tap supporting either ZeroTier tun/tap kext or OSX-native utun
*/
class OSXEthernetTap
{
public:
OSXEthernetTap(
const char *homePath,
const MAC &mac,
unsigned int mtu,
unsigned int metric,
uint64_t nwid,
const char *friendlyName,
void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
void *arg);
~OSXEthernetTap();
void setEnabled(bool en);
bool enabled() const;
bool addIp(const InetAddress &ip);
bool removeIp(const InetAddress &ip);
std::vector<InetAddress> ips() const;
void put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len);
std::string deviceName() const;
void setFriendlyName(const char *friendlyName);
void scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed);
inline bool isNativeUtun() const { return _utun; }
void threadMain()
throw();
private:
void (*_handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int);
void *_arg;
Arp *_arp; // created and used if utun is enabled
uint64_t _nwid;
Thread _thread;
std::string _homePath;
std::string _dev;
std::vector<MulticastGroup> _multicastGroups;
unsigned int _mtu;
unsigned int _metric;
int _fd;
int _shutdownSignalPipe[2];
bool _utun;
volatile bool _enabled;
};
} // namespace ZeroTier
#endif

4
attic/README.md

@ -1,4 +0,0 @@
Retired Code and Miscellaneous Junk
======
This directory is for old code that isn't used but we don't want to lose track of, and for anything else random like debug scripts.

497
attic/RethinkDB.cpp

@ -1,497 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//#define ZT_CONTROLLER_USE_RETHINKDB
#ifdef ZT_CONTROLLER_USE_RETHINKDB
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include "RethinkDB.hpp"
#include "EmbeddedNetworkController.hpp"
#include "../version.h"
#include <chrono>
#include <algorithm>
#include <stdexcept>
#include "../ext/librethinkdbxx/build/include/rethinkdb.h"
namespace R = RethinkDB;
using json = nlohmann::json;
namespace ZeroTier {
static const char *_timestr()
{
time_t t = time(0);
char *ts = ctime(&t);
char *p = ts;
if (!p)
return "";
while (*p) {
if (*p == '\n') {
*p = (char)0;
break;
}
++p;
}
return ts;
}
RethinkDB::RethinkDB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path) :
DB(nc,myId,path),
_ready(2), // two tables need to be synchronized before we're ready, so this is ready when it reaches 0
_run(1),
_waitNoticePrinted(false)
{
// rethinkdb:host:port:db[:auth]
std::vector<std::string> ps(OSUtils::split(path,":","",""));
if ((ps.size() < 4)||(ps[0] != "rethinkdb"))
throw std::runtime_error("invalid rethinkdb database url");
_host = ps[1];
_port = Utils::strToInt(ps[2].c_str());
_db = ps[3];
if (ps.size() > 4)
_auth = ps[4];
_readyLock.lock();
_membersDbWatcher = std::thread([this]() {
try {
while (_run == 1) {
try {
std::unique_ptr<R::Connection> rdb(R::connect(this->_host,this->_port,this->_auth));
if (rdb) {
_membersDbWatcherConnection = (void *)rdb.get();
auto cur = R::db(this->_db).table("Member",R::optargs("read_mode","outdated")).get_all(this->_myAddressStr,R::optargs("index","controllerId")).changes(R::optargs("squash",0.05,"include_initial",true,"include_types",true,"include_states",true)).run(*rdb);
while (cur.has_next()) {
if (_run != 1) break;
json tmp(json::parse(cur.next().as_json()));
if ((tmp["type"] == "state")&&(tmp["state"] == "ready")) {
if (++this->_ready == 2) {
if (_waitNoticePrinted)
fprintf(stderr,"[%s] NOTICE: %.10llx controller RethinkDB data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
this->_readyLock.unlock();
}
} else {
try {
json &ov = tmp["old_val"];
json &nv = tmp["new_val"];
json oldConfig,newConfig;
if (ov.is_object()) oldConfig = ov["config"];
if (nv.is_object()) newConfig = nv["config"];
if (oldConfig.is_object()||newConfig.is_object())
this->_memberChanged(oldConfig,newConfig,(this->_ready <= 0));
} catch ( ... ) {} // ignore bad records
}
}
}
} catch (std::exception &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (member change stream): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what());
} catch (R::Error &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (member change stream): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.message.c_str());
} catch ( ... ) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (member change stream): unknown exception" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
}
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
} catch ( ... ) {}
});
_networksDbWatcher = std::thread([this]() {
try {
while (_run == 1) {
try {
std::unique_ptr<R::Connection> rdb(R::connect(this->_host,this->_port,this->_auth));
if (rdb) {
_networksDbWatcherConnection = (void *)rdb.get();
auto cur = R::db(this->_db).table("Network",R::optargs("read_mode","outdated")).get_all(this->_myAddressStr,R::optargs("index","controllerId")).changes(R::optargs("squash",0.05,"include_initial",true,"include_types",true,"include_states",true)).run(*rdb);
while (cur.has_next()) {
if (_run != 1) break;
json tmp(json::parse(cur.next().as_json()));
if ((tmp["type"] == "state")&&(tmp["state"] == "ready")) {
if (--this->_ready == 0) {
if (_waitNoticePrinted)
fprintf(stderr,"[%s] NOTICE: %.10llx controller RethinkDB data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
this->_readyLock.unlock();
}
} else {
try {
json &ov = tmp["old_val"];
json &nv = tmp["new_val"];
json oldConfig,newConfig;
if (ov.is_object()) oldConfig = ov["config"];
if (nv.is_object()) newConfig = nv["config"];
if (oldConfig.is_object()||newConfig.is_object())
this->_networkChanged(oldConfig,newConfig,(this->_ready <= 0));
} catch ( ... ) {} // ignore bad records
}
}
}
} catch (std::exception &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (network change stream): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what());
} catch (R::Error &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (network change stream): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.message.c_str());
} catch ( ... ) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (network change stream): unknown exception" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
}
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
} catch ( ... ) {}
});
for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t) {
_commitThread[t] = std::thread([this]() {
try {
std::unique_ptr<R::Connection> rdb;
nlohmann::json *config = (nlohmann::json *)0;
while ((this->_commitQueue.get(config))&&(_run == 1)) {
if (!config)
continue;
nlohmann::json record;
const char *table = (const char *)0;
std::string deleteId;
try {
const std::string objtype = (*config)["objtype"];
if (objtype == "member") {
const std::string nwid = (*config)["nwid"];
const std::string id = (*config)["id"];
record["id"] = nwid + "-" + id;
record["controllerId"] = this->_myAddressStr;
record["networkId"] = nwid;
record["nodeId"] = id;
record["config"] = *config;
table = "Member";
} else if (objtype == "network") {
const std::string id = (*config)["id"];
record["id"] = id;
record["controllerId"] = this->_myAddressStr;
record["config"] = *config;
table = "Network";
} else if (objtype == "trace") {
record = *config;
table = "RemoteTrace";
} else if (objtype == "_delete_network") {
deleteId = (*config)["id"];
table = "Network";
} else if (objtype == "_delete_member") {
deleteId = (*config)["nwid"];
deleteId.push_back('-');
const std::string tmp = (*config)["id"];
deleteId.append(tmp);
table = "Member";
}
} catch (std::exception &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update record creation): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what());
table = (const char *)0;
} catch (R::Error &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update record creation): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.message.c_str());
table = (const char *)0;
} catch ( ... ) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update record creation): unknown exception" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
table = (const char *)0;
}
delete config;
if (!table)
continue;
const std::string jdump(OSUtils::jsonDump(record,-1));
while (_run == 1) {
try {
if (!rdb)
rdb = R::connect(this->_host,this->_port,this->_auth);
if (rdb) {
if (deleteId.length() > 0) {
//printf("DELETE: %s" ZT_EOL_S,deleteId.c_str());
R::db(this->_db).table(table).get(deleteId).delete_().run(*rdb);
} else {
//printf("UPSERT: %s" ZT_EOL_S,record.dump().c_str());
R::db(this->_db).table(table).insert(R::Datum::from_json(jdump),R::optargs("conflict","update","return_changes",false)).run(*rdb);
}
break;
} else {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update): connect failed (will retry)" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
rdb.reset();
}
} catch (std::exception &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update): %s [%s]" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what(),jdump.c_str());
rdb.reset();
} catch (R::Error &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update): %s [%s]" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.message.c_str(),jdump.c_str());
rdb.reset();
} catch ( ... ) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update): unknown exception [%s]" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),jdump.c_str());
rdb.reset();
}
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
}
} catch (std::exception &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update outer loop): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what());
} catch (R::Error &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update outer loop): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.message.c_str());
} catch ( ... ) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (insert/update outer loop): unknown exception" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
}
});
}
_onlineNotificationThread = std::thread([this]() {
int64_t lastUpdatedNetworkStatus = 0;
std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
try {
std::unique_ptr<R::Connection> rdb;
while (_run == 1) {
try {
if (!rdb) {
_connected = 0;
rdb = R::connect(this->_host,this->_port,this->_auth);
}
if (rdb) {
_connected = 1;
R::Array batch;
R::Object tmpobj;
std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
{
std::lock_guard<std::mutex> l(_lastOnline_l);
lastOnline.swap(_lastOnline);
}
for(auto i=lastOnline.begin();i!=lastOnline.end();++i) {
lastOnlineCumulative[i->first] = i->second.first;
char tmp[64],tmp2[64];
OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx-%.10llx",i->first.first,i->first.second);
tmpobj["id"] = tmp;
tmpobj["ts"] = i->second.first;
tmpobj["phy"] = i->second.second.toIpString(tmp2);
batch.emplace_back(tmpobj);
if (batch.size() >= 1024) {
R::db(this->_db).table("MemberStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
batch.clear();
}
}
if (batch.size() > 0) {
R::db(this->_db).table("MemberStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
batch.clear();
}
tmpobj.clear();
const int64_t now = OSUtils::now();
if ((now - lastUpdatedNetworkStatus) > 10000) {
lastUpdatedNetworkStatus = now;
std::vector< std::pair< uint64_t,std::shared_ptr<_Network> > > networks;
{
std::lock_guard<std::mutex> l(_networks_l);
networks.reserve(_networks.size() + 1);
for(auto i=_networks.begin();i!=_networks.end();++i)
networks.push_back(*i);
}
for(auto i=networks.begin();i!=networks.end();++i) {
char tmp[64];
Utils::hex(i->first,tmp);
tmpobj["id"] = tmp;
{
std::lock_guard<std::mutex> l2(i->second->lock);
tmpobj["authorizedMemberCount"] = i->second->authorizedMembers.size();
tmpobj["totalMemberCount"] = i->second->members.size();
unsigned long onlineMemberCount = 0;
for(auto m=i->second->members.begin();m!=i->second->members.end();++m) {
auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first,m->first));
if (lo != lastOnlineCumulative.end()) {
if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2))
++onlineMemberCount;
else lastOnlineCumulative.erase(lo);
}
}
tmpobj["onlineMemberCount"] = onlineMemberCount;
tmpobj["bridgeCount"] = i->second->activeBridgeMembers.size();
tmpobj["ts"] = now;
}
batch.emplace_back(tmpobj);
if (batch.size() >= 1024) {
R::db(this->_db).table("NetworkStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
batch.clear();
}
}
if (batch.size() > 0) {
R::db(this->_db).table("NetworkStatus",R::optargs("read_mode","outdated")).insert(batch,R::optargs("conflict","update")).run(*rdb);
batch.clear();
}
}
}
} catch (std::exception &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (node status update): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.what());
rdb.reset();
} catch (R::Error &e) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (node status update): %s" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt(),e.message.c_str());
rdb.reset();
} catch ( ... ) {
fprintf(stderr,"[%s] ERROR: %.10llx controller RethinkDB (node status update): unknown exception" ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
rdb.reset();
}
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
} catch ( ... ) {}
});
_heartbeatThread = std::thread([this]() {
try {
R::Object controllerRecord;
std::unique_ptr<R::Connection> rdb;
{
char publicId[1024];
//char secretId[1024];
char hostname[1024];
this->_myId.toString(false,publicId);
//this->_myId.toString(true,secretId);
if (gethostname(hostname,sizeof(hostname)) != 0) {
hostname[0] = (char)0;
} else {
for(int i=0;i<sizeof(hostname);++i) {
if ((hostname[i] == '.')||(hostname[i] == 0)) {
hostname[i] = (char)0;
break;
}
}
}
controllerRecord["id"] = this->_myAddressStr.c_str();
controllerRecord["publicIdentity"] = publicId;
//controllerRecord["secretIdentity"] = secretId;
if (hostname[0])
controllerRecord["clusterHost"] = hostname;
controllerRecord["vMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
controllerRecord["vMinor"] = ZEROTIER_ONE_VERSION_MINOR;
controllerRecord["vRev"] = ZEROTIER_ONE_VERSION_REVISION;
controllerRecord["vBuild"] = ZEROTIER_ONE_VERSION_BUILD;
}
while (_run == 1) {
try {
if (!rdb)
rdb = R::connect(this->_host,this->_port,this->_auth);
if (rdb) {
controllerRecord["lastAlive"] = OSUtils::now();
//printf("HEARTBEAT: %s" ZT_EOL_S,tmp);
R::db(this->_db).table("Controller",R::optargs("read_mode","outdated")).insert(controllerRecord,R::optargs("conflict","update")).run(*rdb);
}
} catch ( ... ) {
rdb.reset();
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
} catch ( ... ) {}
});
}
RethinkDB::~RethinkDB()
{
_run = 0;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
_commitQueue.stop();
for(int t=0;t<ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS;++t)
_commitThread[t].join();
if (_membersDbWatcherConnection)
((R::Connection *)_membersDbWatcherConnection)->close();
if (_networksDbWatcherConnection)
((R::Connection *)_networksDbWatcherConnection)->close();
_membersDbWatcher.join();
_networksDbWatcher.join();
_heartbeatThread.join();
_onlineNotificationThread.join();
}
bool RethinkDB::waitForReady()
{
while (_ready > 0) {
if (!_waitNoticePrinted) {
_waitNoticePrinted = true;
fprintf(stderr,"[%s] NOTICE: %.10llx controller RethinkDB waiting for initial data download..." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
}
_readyLock.lock();
_readyLock.unlock();
}
return true;
}
bool RethinkDB::isReady()
{
return ((_ready)&&(_connected));
}
void RethinkDB::save(nlohmann::json *orig,nlohmann::json &record)
{
if (!record.is_object()) // sanity check
return;
waitForReady();
if (orig) {
if (*orig != record) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
_commitQueue.post(new nlohmann::json(record));
}
} else {
record["revision"] = 1;
_commitQueue.post(new nlohmann::json(record));
}
}
void RethinkDB::eraseNetwork(const uint64_t networkId)
{
char tmp2[24];
waitForReady();
Utils::hex(networkId,tmp2);
json *tmp = new json();
(*tmp)["id"] = tmp2;
(*tmp)["objtype"] = "_delete_network"; // pseudo-type, tells thread to delete network
_commitQueue.post(tmp);
}
void RethinkDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
{
char tmp2[24];
json *tmp = new json();
waitForReady();
Utils::hex(networkId,tmp2);
(*tmp)["nwid"] = tmp2;
Utils::hex10(memberId,tmp2);
(*tmp)["id"] = tmp2;
(*tmp)["objtype"] = "_delete_member"; // pseudo-type, tells thread to delete network
_commitQueue.post(tmp);
}
void RethinkDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
{
std::lock_guard<std::mutex> l(_lastOnline_l);
std::pair<int64_t,InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId,memberId)];
i.first = OSUtils::now();
if (physicalAddress)
i.second = physicalAddress;
}
} // namespace ZeroTier
#endif // ZT_CONTROLLER_USE_RETHINKDB

84
attic/RethinkDB.hpp

@ -1,84 +0,0 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2018 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef ZT_CONTROLLER_USE_RETHINKDB
#ifndef ZT_CONTROLLER_RETHINKDB_HPP
#define ZT_CONTROLLER_RETHINKDB_HPP
#include "DB.hpp"
#define ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS 4
namespace ZeroTier
{
/**
* A controller database driver that talks to RethinkDB
*
* This is for use with ZeroTier Central. Others are free to build and use it
* but be aware that we might change it at any time.
*/
class RethinkDB : public DB
{
public:
RethinkDB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path);
virtual ~RethinkDB();
virtual bool waitForReady();
virtual bool isReady();
virtual void save(nlohmann::json *orig,nlohmann::json &record);
virtual void eraseNetwork(const uint64_t networkId);
virtual void eraseMember(const uint64_t networkId,const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress);
protected:
struct _PairHasher
{
inline std::size_t operator()(const std::pair<uint64_t,uint64_t> &p) const { return (std::size_t)(p.first ^ p.second); }
};
std::string _host;
std::string _db;
std::string _auth;
int _port;
void *_networksDbWatcherConnection;
void *_membersDbWatcherConnection;
std::thread _networksDbWatcher;
std::thread _membersDbWatcher;
BlockingQueue< nlohmann::json * > _commitQueue;
std::thread _commitThread[ZT_CONTROLLER_RETHINKDB_COMMIT_THREADS];
std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > _lastOnline;
mutable std::mutex _lastOnline_l;
std::thread _onlineNotificationThread;
std::thread _heartbeatThread;
mutable std::mutex _readyLock; // locked until ready
std::atomic<int> _ready,_connected,_run;
mutable volatile bool _waitNoticePrinted;
};
} // namespace ZeroTier
#endif
#endif // ZT_CONTROLLER_USE_RETHINKDB

18
attic/kubernetes_docs/.zerotierCliSettings

@ -1,18 +0,0 @@
{
"configVersion": 1,
"defaultCentral": "@my.zerotier.com",
"defaultController": "@my.zerotier.com",
"defaultOne": "@local",
"things": {
"local": {
"auth": "local_service_auth_token_replaced_automatically",
"type": "one",
"url": "http://127.0.0.1:9993/"
},
"my.zerotier.com": {
"auth": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"type": "central",
"url": "https://my.zerotier.com/"
}
}
}

19
attic/kubernetes_docs/Dockerfile

@ -1,19 +0,0 @@
FROM node:4.4
EXPOSE 8080/tcp 9993/udp
# Install ZT network conf files
RUN mkdir -p /var/lib/zerotier-one/networks.d
ADD *.conf /var/lib/zerotier-one/networks.d/
ADD *.conf /
ADD zerotier-one /
ADD zerotier-cli /
ADD .zerotierCliSettings /
# Install App
ADD server.js /
# script which will start/auth VM on ZT network
ADD entrypoint.sh /
RUN chmod -v +x /entrypoint.sh
CMD ["./entrypoint.sh"]

150
attic/kubernetes_docs/README.md

@ -1,150 +0,0 @@
Kubernetes + ZeroTier
====
A self-authorizing Kubernetes cluster deployment over a private ZeroTier network.
This is a quick tutorial for setting up a Kubernetes deployment which can self-authorize each new replica onto your private ZeroTier network with no additional configuration needed when you scale. The Kubernetes-specific instructions and content is based on the [hellonode](http://kubernetes.io/docs/hellonode/) tutorial. All of the files discussed below can be found [here]();
## Preliminary tasks
**Step 1: Go to [my.zerotier.com](https://my.zerotier.com) and generate a network controller API key. This key will be used by ZeroTier to automatically authorize new instances of your VMs to join your secure deployment network during replication.**
**Step 2: Create a new `private` network. Take note of the network ID, henceforth: `nwid`**
**Step 3: Follow the instructions from the [hellonode](ttp://kubernetes.io/docs/hellonode/) tutorial to set up your development system.**
***
## Construct docker image
**Step 4: Create necessary files for inclusion into image, your resultant directory should contain:**
- `ztkube/<nwid>.conf`
- `ztkube/Dockerfile`
- `ztkube/entrypoint.sh`
- `ztkube/server.js`
- `ztkube/zerotier-cli`
- `ztkube/zerotier-one`
Start by creating a build directory to copy all required files into `mkdir ztkube`. Then build the following:
- `make one`
- `make cli`
Add the following files to the `ztkube` directory. These files will be compiled into the Docker image.
- Create an empty `<nwid>.conf` file to specify the private deployment network you created in *Step 2*:
- Create a CLI tool config file `.zerotierCliSettings` which should only contain your network controller API key to authorize new devices on your network (the local service API key will be filled in automatically). In this example the default controller is hosted by us at [my.zerotier.com](https://my.zerotier.com). Alternatively, you can host your own network controller but you'll need to modify the CLI config file accordingly.
```
{
"configVersion": 1,
"defaultCentral": "@my.zerotier.com",
"defaultController": "@my.zerotier.com",
"defaultOne": "@local",
"things": {
"local": {
"auth": "local_service_auth_token_replaced_automatically",
"type": "one",
"url": "http://127.0.0.1:9993/"
},
"my.zerotier.com": {
"auth": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"type": "central",
"url": "https://my.zerotier.com/"
}
}
}
```
- Create a `Dockerfile` which will copy the ZeroTier service as well as the ZeroTier CLI to the image:
```
FROM node:4.4
EXPOSE 8080/tcp 9993/udp
# Install ZT network conf files
RUN mkdir -p /var/lib/zerotier-one/networks.d
ADD *.conf /var/lib/zerotier-one/networks.d/
ADD *.conf /
ADD zerotier-one /
ADD zerotier-cli /
ADD .zerotierCliSettings /
# Install App
ADD server.js /
# script which will start/auth VM on ZT network
ADD entrypoint.sh /
RUN chmod -v +x /entrypoint.sh
CMD ["./entrypoint.sh"]
```
- Create the `entrypoint.sh` script which will start the ZeroTier service in the VM, attempt to join your deployment network and automatically authorize the new VM if your network is set to private:
```
#!/bin/bash
echo '*** ZeroTier-Kubernetes self-auth test script'
chown -R daemon /var/lib/zerotier-one
chgrp -R daemon /var/lib/zerotier-one
su daemon -s /bin/bash -c '/zerotier-one -d -U -p9993 >>/tmp/zerotier-one.out 2>&1'
dev=""
nwconf=$(ls *.conf)
nwid="${nwconf%.*}"
sleep 10
dev=$(cat /var/lib/zerotier-one/identity.public| cut -d ':' -f 1)
echo '*** Joining'
./zerotier-cli join "$nwid".conf
# Fill out local service auth token
AUTHTOKEN=$(cat /var/lib/zerotier-one/authtoken.secret)
sed "s|\local_service_auth_token_replaced_automatically|${AUTHTOKEN}|" .zerotierCliSettings > /root/.zerotierCliSettings
echo '*** Authorizing'
./zerotier-cli net-auth @my.zerotier.com "$nwid" "$dev"
echo '*** Cleaning up' # Remove controller auth token
rm -rf .zerotierCliSettings /root/.zerotierCliSettings
node server.js
```
**Step 5: Build the image:**
- `docker build -t gcr.io/$PROJECT_ID/hello-node .`
**Step 6: Push the docker image to your *Container Registry***
- `gcloud docker push gcr.io/$PROJECT_ID/hello-node:v1`
***
## Deploy!
**Step 7: Create Kubernetes Cluster**
- `gcloud config set compute/zone us-central1-a`
- `gcloud container clusters create hello-world`
- `gcloud container clusters get-credentials hello-world`
**Step 8: Create your pod**
- `kubectl run hello-node --image=gcr.io/$PROJECT_ID/hello-node:v1 --port=8080`
**Step 9: Scale**
- `kubectl scale deployment hello-node --replicas=4`
***
## Verify
Now, after a minute or so you can use `zerotier-cli net-members <nwid>` to show all of your VM instances on your ZeroTier deployment network. If you haven't [configured your local CLI](https://github.com/zerotier/ZeroTierOne/tree/dev/cli), you can simply log into [my.zerotier.com](https://my.zerotier.com), go to *Networks -> nwid* to check that your VMs are indeed members of your private network. You should also note that the `entrypoint.sh` script will automatically delete your network controller API key once it has authorized your VM. This is merely a security measure and can be removed if needed.

23
attic/kubernetes_docs/entrypoint.sh

@ -1,23 +0,0 @@
#!/bin/bash
echo '*** ZeroTier-Kubernetes self-auth test script'
chown -R daemon /var/lib/zerotier-one
chgrp -R daemon /var/lib/zerotier-one
su daemon -s /bin/bash -c '/zerotier-one -d -U -p9993 >>/tmp/zerotier-one.out 2>&1'
dev=""
nwconf=$(ls *.conf)
nwid="${nwconf%.*}"
sleep 10
dev=$(cat /var/lib/zerotier-one/identity.public| cut -d ':' -f 1)
echo '*** Joining'
./zerotier-cli join "$nwid".conf
# Fill out local service auth token
AUTHTOKEN=$(cat /var/lib/zerotier-one/authtoken.secret)
sed "s|\local_service_auth_token_replaced_automatically|${AUTHTOKEN}|" .zerotierCliSettings > /root/.zerotierCliSettings
echo '*** Authorizing'
./zerotier-cli net-auth @my.zerotier.com "$nwid" "$dev"
echo '*** Cleaning up' # Remove controller auth token
rm -rf .zerotierCliSettings /root/.zerotierCliSettings
node server.js

8
attic/kubernetes_docs/server.js

@ -1,8 +0,0 @@
var http = require('http');
var handleRequest = function(request, response) {
console.log('Received request for URL: ' + request.url);
response.writeHead(200);
response.end('Hello World!');
};
var www = http.createServer(handleRequest);
www.listen(8080);

25
attic/lat_lon_to_xyz.js

@ -1,25 +0,0 @@
'use strict'
/* This is a utility to convert latitude/longitude into X,Y,Z coordinates as used by clustering. */
if (process.argv.length !== 4) {
console.log('Usage: node lat_lon_to_xyz.js <latitude> <longitude');
process.exit(1);
}
var lat = parseFloat(process.argv[2])||0.0;
var lon = parseFloat(process.argv[3])||0.0;
var latRadians = lat * 0.01745329251994; // PI / 180
var lonRadians = lon * 0.01745329251994; // PI / 180
var cosLat = Math.cos(latRadians);
console.log({
lat: lat,
lon: lon,
x: Math.round((-6371.0) * cosLat * Math.cos(lonRadians)),
y: Math.round(6371.0 * Math.sin(latRadians)),
z: Math.round(6371.0 * cosLat * Math.sin(lonRadians))
});
process.exit(0);

4
attic/world/build.sh

@ -1 +1,3 @@
c++ -I.. -o mkworld ../node/C25519.cpp ../node/Salsa20.cpp ../node/SHA512.cpp ../node/Identity.cpp ../node/Utils.cpp ../node/InetAddress.cpp ../osdep/OSUtils.cpp mkworld.cpp #!/bin/bash
c++ -std=c++11 -I../.. -I.. -g -o mkworld ../../node/C25519.cpp ../../node/Salsa20.cpp ../../node/SHA512.cpp ../../node/Identity.cpp ../../node/Utils.cpp ../../node/InetAddress.cpp ../../osdep/OSUtils.cpp mkworld.cpp -lm

96
attic/world/mkworld.cpp

@ -61,11 +61,11 @@ int main(int argc,char **argv)
current = previous; current = previous;
OSUtils::writeFile("previous.c25519",previous); OSUtils::writeFile("previous.c25519",previous);
OSUtils::writeFile("current.c25519",current); OSUtils::writeFile("current.c25519",current);
fprintf(stderr,"INFO: created initial world keys: previous.c25519 and current.c25519 (both initially the same)"ZT_EOL_S); fprintf(stderr,"INFO: created initial world keys: previous.c25519 and current.c25519 (both initially the same)" ZT_EOL_S);
} }
if ((previous.length() != (ZT_C25519_PUBLIC_KEY_LEN + ZT_C25519_PRIVATE_KEY_LEN))||(current.length() != (ZT_C25519_PUBLIC_KEY_LEN + ZT_C25519_PRIVATE_KEY_LEN))) { if ((previous.length() != (ZT_C25519_PUBLIC_KEY_LEN + ZT_C25519_PRIVATE_KEY_LEN))||(current.length() != (ZT_C25519_PUBLIC_KEY_LEN + ZT_C25519_PRIVATE_KEY_LEN))) {
fprintf(stderr,"FATAL: previous.c25519 or current.c25519 empty or invalid"ZT_EOL_S); fprintf(stderr,"FATAL: previous.c25519 or current.c25519 empty or invalid" ZT_EOL_S);
return 1; return 1;
} }
C25519::Pair previousKP; C25519::Pair previousKP;
@ -81,44 +81,68 @@ int main(int argc,char **argv)
std::vector<World::Root> roots; std::vector<World::Root> roots;
const uint64_t id = ZT_WORLD_ID_EARTH; const uint64_t id = ZT_WORLD_ID_EARTH;
const uint64_t ts = 1532555817048ULL; // July 25th, 2018 const uint64_t ts = 1567191349589ULL; // August 30th, 2019
// Alice // Los Angeles
roots.push_back(World::Root()); roots.push_back(World::Root());
roots.back().identity = Identity("9d219039f3:0:01f0922a98e3b34ebcbff333269dc265d7a020aab69d72be4d4acc9c8c9294785771256cd1d942a90d1bd1d2dca3ea84ef7d85afe6611fb43ff0b74126d90a6e"); roots.back().identity = Identity("3a46f1bf30:0:76e66fab33e28549a62ee2064d1843273c2c300ba45c3f20bef02dbad225723bb59a9bb4b13535730961aeecf5a163ace477cceb0727025b99ac14a5166a09a3");
roots.back().stableEndpoints.push_back(InetAddress("188.166.94.177/9993")); // Amsterdam roots.back().stableEndpoints.push_back(InetAddress("185.180.13.82/9993"));
roots.back().stableEndpoints.push_back(InetAddress("2a03:b0c0:2:d0::7d:1/9993")); // Amsterdam roots.back().stableEndpoints.push_back(InetAddress("2a02:6ea0:c815::/9993"));
roots.back().stableEndpoints.push_back(InetAddress("154.66.197.33/9993")); // Johannesburg
roots.back().stableEndpoints.push_back(InetAddress("2c0f:f850:154:197::33/9993")); // Johannesburg
roots.back().stableEndpoints.push_back(InetAddress("159.203.97.171/9993")); // New York
roots.back().stableEndpoints.push_back(InetAddress("2604:a880:800:a1::54:6001/9993")); // New York
roots.back().stableEndpoints.push_back(InetAddress("131.255.6.16/9993")); // Buenos Aires
roots.back().stableEndpoints.push_back(InetAddress("2803:eb80:0:e::2/9993")); // Buenos Aires
roots.back().stableEndpoints.push_back(InetAddress("107.170.197.14/9993")); // San Francisco
roots.back().stableEndpoints.push_back(InetAddress("2604:a880:1:20::200:e001/9993")); // San Francisco
roots.back().stableEndpoints.push_back(InetAddress("128.199.197.217/9993")); // Singapore
roots.back().stableEndpoints.push_back(InetAddress("2400:6180:0:d0::b7:4001/9993")); // Singapore
// Bob // Miami
roots.push_back(World::Root());
roots.back().identity = Identity("de8950a8b2:0:1b3ada8251b91b6b6fa6535b8c7e2460918f4f729abdec97d3c7f3796868fb02f0de0b0ee554b2d59fc3524743eebfcf5315e790ed6d92db5bd10c28c09b40ef");
roots.back().stableEndpoints.push_back(InetAddress("207.246.73.245/443"));
roots.back().stableEndpoints.push_back(InetAddress("2001:19f0:9002:5cb:ec4:7aff:fe8f:69d9/443"));
// Tokyo
roots.push_back(World::Root());
roots.back().identity = Identity("34e0a5e174:0:93efb50934788f856d5cfb9ca5be88e85b40965586b75befac900df77352c145a1ba7007569d37c77bfe52c0999f3bdc67a47a4a6000b720a883ce47aa2fb7f8");
roots.back().stableEndpoints.push_back(InetAddress("147.75.92.2/443"));
roots.back().stableEndpoints.push_back(InetAddress("2604:1380:3000:7100::1/443"));
// Amsterdam
roots.push_back(World::Root()); roots.push_back(World::Root());
roots.back().identity = Identity("8841408a2e:0:bb1d31f2c323e264e9e64172c1a74f77899555ed10751cd56e86405cde118d02dffe555d462ccf6a85b5631c12350c8d5dc409ba10b9025d0f445cf449d92b1c"); roots.back().identity = Identity("992fcf1db7:0:206ed59350b31916f749a1f85dffb3a8787dcbf83b8c6e9448d4e3ea0e3369301be716c3609344a9d1533850fb4460c50af43322bcfc8e13d3301a1f1003ceb6");
roots.back().stableEndpoints.push_back(InetAddress("45.32.198.130/9993")); // Dallas roots.back().stableEndpoints.push_back(InetAddress("195.181.173.159/443"));
roots.back().stableEndpoints.push_back(InetAddress("2001:19f0:6400:81c3:5400:00ff:fe18:1d61/9993")); // Dallas roots.back().stableEndpoints.push_back(InetAddress("2a02:6ea0:c024::/443"));
roots.back().stableEndpoints.push_back(InetAddress("46.101.160.249/9993")); // Frankfurt
roots.back().stableEndpoints.push_back(InetAddress("2a03:b0c0:3:d0::6a:3001/9993")); // Frankfurt // Alice
roots.back().stableEndpoints.push_back(InetAddress("107.191.46.210/9993")); // Paris //roots.push_back(World::Root());
roots.back().stableEndpoints.push_back(InetAddress("2001:19f0:6800:83a4::64/9993")); // Paris //roots.back().identity = Identity("9d219039f3:0:01f0922a98e3b34ebcbff333269dc265d7a020aab69d72be4d4acc9c8c9294785771256cd1d942a90d1bd1d2dca3ea84ef7d85afe6611fb43ff0b74126d90a6e");
roots.back().stableEndpoints.push_back(InetAddress("45.32.246.179/9993")); // Sydney //roots.back().stableEndpoints.push_back(InetAddress("188.166.94.177/9993")); // Amsterdam
roots.back().stableEndpoints.push_back(InetAddress("2001:19f0:5800:8bf8:5400:ff:fe15:b39a/9993")); // Sydney //roots.back().stableEndpoints.push_back(InetAddress("2a03:b0c0:2:d0::7d:1/9993")); // Amsterdam
roots.back().stableEndpoints.push_back(InetAddress("45.32.248.87/9993")); // Tokyo //roots.back().stableEndpoints.push_back(InetAddress("154.66.197.33/9993")); // Johannesburg
roots.back().stableEndpoints.push_back(InetAddress("2001:19f0:7000:9bc9:5400:00ff:fe15:c4f5/9993")); // Tokyo //roots.back().stableEndpoints.push_back(InetAddress("2c0f:f850:154:197::33/9993")); // Johannesburg
roots.back().stableEndpoints.push_back(InetAddress("159.203.2.154/9993")); // Toronto //roots.back().stableEndpoints.push_back(InetAddress("159.203.97.171/9993")); // New York
roots.back().stableEndpoints.push_back(InetAddress("2604:a880:cad:d0::26:7001/9993")); // Toronto //roots.back().stableEndpoints.push_back(InetAddress("2604:a880:800:a1::54:6001/9993")); // New York
//roots.back().stableEndpoints.push_back(InetAddress("131.255.6.16/9993")); // Buenos Aires
//roots.back().stableEndpoints.push_back(InetAddress("2803:eb80:0:e::2/9993")); // Buenos Aires
//roots.back().stableEndpoints.push_back(InetAddress("107.170.197.14/9993")); // San Francisco
//roots.back().stableEndpoints.push_back(InetAddress("2604:a880:1:20::200:e001/9993")); // San Francisco
//roots.back().stableEndpoints.push_back(InetAddress("128.199.197.217/9993")); // Singapore
//roots.back().stableEndpoints.push_back(InetAddress("2400:6180:0:d0::b7:4001/9993")); // Singapore
// Bob
//roots.push_back(World::Root());
//roots.back().identity = Identity("8841408a2e:0:bb1d31f2c323e264e9e64172c1a74f77899555ed10751cd56e86405cde118d02dffe555d462ccf6a85b5631c12350c8d5dc409ba10b9025d0f445cf449d92b1c");
//roots.back().stableEndpoints.push_back(InetAddress("45.32.198.130/9993")); // Dallas
//roots.back().stableEndpoints.push_back(InetAddress("2001:19f0:6400:81c3:5400:00ff:fe18:1d61/9993")); // Dallas
//roots.back().stableEndpoints.push_back(InetAddress("46.101.160.249/9993")); // Frankfurt
//roots.back().stableEndpoints.push_back(InetAddress("2a03:b0c0:3:d0::6a:3001/9993")); // Frankfurt
//roots.back().stableEndpoints.push_back(InetAddress("107.191.46.210/9993")); // Paris
//roots.back().stableEndpoints.push_back(InetAddress("2001:19f0:6800:83a4::64/9993")); // Paris
//roots.back().stableEndpoints.push_back(InetAddress("45.32.246.179/9993")); // Sydney
//roots.back().stableEndpoints.push_back(InetAddress("2001:19f0:5800:8bf8:5400:ff:fe15:b39a/9993")); // Sydney
//roots.back().stableEndpoints.push_back(InetAddress("45.32.248.87/9993")); // Tokyo
//roots.back().stableEndpoints.push_back(InetAddress("2001:19f0:7000:9bc9:5400:00ff:fe15:c4f5/9993")); // Tokyo
//roots.back().stableEndpoints.push_back(InetAddress("159.203.2.154/9993")); // Toronto
//roots.back().stableEndpoints.push_back(InetAddress("2604:a880:cad:d0::26:7001/9993")); // Toronto
// END WORLD DEFINITION // END WORLD DEFINITION
// ========================================================================= // =========================================================================
fprintf(stderr,"INFO: generating and signing id==%llu ts==%llu"ZT_EOL_S,(unsigned long long)id,(unsigned long long)ts); fprintf(stderr,"INFO: generating and signing id==%llu ts==%llu" ZT_EOL_S,(unsigned long long)id,(unsigned long long)ts);
World nw = World::make(World::TYPE_PLANET,id,ts,currentKP.pub,roots,previousKP); World nw = World::make(World::TYPE_PLANET,id,ts,currentKP.pub,roots,previousKP);
@ -127,15 +151,15 @@ int main(int argc,char **argv)
World testw; World testw;
testw.deserialize(outtmp,0); testw.deserialize(outtmp,0);
if (testw != nw) { if (testw != nw) {
fprintf(stderr,"FATAL: serialization test failed!"ZT_EOL_S); fprintf(stderr,"FATAL: serialization test failed!" ZT_EOL_S);
return 1; return 1;
} }
OSUtils::writeFile("world.bin",std::string((const char *)outtmp.data(),outtmp.size())); OSUtils::writeFile("world.bin",std::string((const char *)outtmp.data(),outtmp.size()));
fprintf(stderr,"INFO: world.bin written with %u bytes of binary world data."ZT_EOL_S,outtmp.size()); fprintf(stderr,"INFO: world.bin written with %u bytes of binary world data." ZT_EOL_S,outtmp.size());
fprintf(stdout,ZT_EOL_S); fprintf(stdout,ZT_EOL_S);
fprintf(stdout,"#define ZT_DEFAULT_WORLD_LENGTH %u"ZT_EOL_S,outtmp.size()); fprintf(stdout,"#define ZT_DEFAULT_WORLD_LENGTH %u" ZT_EOL_S,outtmp.size());
fprintf(stdout,"static const unsigned char ZT_DEFAULT_WORLD[ZT_DEFAULT_WORLD_LENGTH] = {"); fprintf(stdout,"static const unsigned char ZT_DEFAULT_WORLD[ZT_DEFAULT_WORLD_LENGTH] = {");
for(unsigned int i=0;i<outtmp.size();++i) { for(unsigned int i=0;i<outtmp.size();++i) {
const unsigned char *d = (const unsigned char *)outtmp.data(); const unsigned char *d = (const unsigned char *)outtmp.data();
@ -143,7 +167,7 @@ int main(int argc,char **argv)
fprintf(stdout,","); fprintf(stdout,",");
fprintf(stdout,"0x%.2x",(unsigned int)d[i]); fprintf(stdout,"0x%.2x",(unsigned int)d[i]);
} }
fprintf(stdout,"};"ZT_EOL_S); fprintf(stdout,"};" ZT_EOL_S);
return 0; return 0;
} }

BIN
attic/world/old/earth-2015-11-16.bin

Binary file not shown.

BIN
attic/world/old/earth-2015-11-20.bin

Binary file not shown.

BIN
attic/world/old/earth-2015-12-17.bin

Binary file not shown.

BIN
attic/world/old/earth-2016-01-13.bin

Binary file not shown.

BIN
attic/world/world.bin

Binary file not shown.

4
attic/world/world.c

@ -1,3 +1,3 @@
#define ZT_DEFAULT_WORLD_LENGTH 634 #define ZT_DEFAULT_WORLD_LENGTH 732
static const unsigned char ZT_DEFAULT_WORLD[ZT_DEFAULT_WORLD_LENGTH] = {0x01,0x00,0x00,0x00,0x00,0x08,0xea,0xc9,0x0a,0x00,0x00,0x01,0x64,0xd3,0x71,0xf0,0x58,0xb8,0xb3,0x88,0xa4,0x69,0x22,0x14,0x91,0xaa,0x9a,0xcd,0x66,0xcc,0x76,0x4c,0xde,0xfd,0x56,0x03,0x9f,0x10,0x67,0xae,0x15,0xe6,0x9c,0x6f,0xb4,0x2d,0x7b,0x55,0x33,0x0e,0x3f,0xda,0xac,0x52,0x9c,0x07,0x92,0xfd,0x73,0x40,0xa6,0xaa,0x21,0xab,0xa8,0xa4,0x89,0xfd,0xae,0xa4,0x4a,0x39,0xbf,0x2d,0x00,0x65,0x9a,0xc9,0xc8,0x18,0xeb,0xbf,0xfd,0xd5,0x32,0xf7,0x15,0x6e,0x02,0x6f,0xb9,0x01,0x0d,0xb5,0x7b,0x04,0xd8,0x3a,0xc5,0x17,0x39,0x04,0x36,0xfd,0x9d,0xc6,0x3d,0xa8,0xf3,0x8e,0x79,0xe7,0xc8,0x77,0x8d,0xcc,0x79,0xb8,0xab,0xc6,0x98,0x7c,0x9f,0x34,0x25,0x14,0xe1,0x2f,0xd7,0x97,0x11,0xec,0x34,0x4c,0x9f,0x0f,0xb4,0x85,0x0d,0x9b,0x11,0xd1,0xc2,0xce,0x00,0xc4,0x0a,0x13,0x4b,0xcb,0xc3,0xae,0x2e,0x16,0x00,0x4b,0xdc,0x90,0x5e,0x7e,0x9b,0x44,0x07,0x15,0x36,0x61,0x3c,0x64,0xaa,0xe9,0x46,0x78,0x3c,0xa7,0x18,0xc8,0xd8,0x02,0x9d,0x21,0x90,0x39,0xf3,0x00,0x01,0xf0,0x92,0x2a,0x98,0xe3,0xb3,0x4e,0xbc,0xbf,0xf3,0x33,0x26,0x9d,0xc2,0x65,0xd7,0xa0,0x20,0xaa,0xb6,0x9d,0x72,0xbe,0x4d,0x4a,0xcc,0x9c,0x8c,0x92,0x94,0x78,0x57,0x71,0x25,0x6c,0xd1,0xd9,0x42,0xa9,0x0d,0x1b,0xd1,0xd2,0xdc,0xa3,0xea,0x84,0xef,0x7d,0x85,0xaf,0xe6,0x61,0x1f,0xb4,0x3f,0xf0,0xb7,0x41,0x26,0xd9,0x0a,0x6e,0x00,0x0c,0x04,0xbc,0xa6,0x5e,0xb1,0x27,0x09,0x06,0x2a,0x03,0xb0,0xc0,0x00,0x02,0x00,0xd0,0x00,0x7d,0x00,0x01,0x00,0x00,0x00,0x00,0x27,0x09,0x04,0x9a,0x42,0xc5,0x21,0x27,0x09,0x06,0x2c,0x0f,0xf8,0x50,0x01,0x54,0x01,0x97,0x00,0x33,0xcc,0x08,0xf8,0xfa,0xcc,0x08,0x27,0x09,0x04,0x9f,0xcb,0x61,0xab,0x27,0x09,0x06,0x26,0x04,0xa8,0x80,0x08,0x00,0x00,0xa1,0x00,0x54,0x60,0x01,0x00,0xfc,0xcc,0x08,0x27,0x09,0x04,0x83,0xff,0x06,0x10,0x27,0x09,0x06,0x28,0x03,0xeb,0x80,0x00,0x00,0x00,0x0e,0x00,0x02,0x60,0x01,0x00,0xfc,0xcc,0x08,0x27,0x09,0x04,0x6b,0xaa,0xc5,0x0e,0x27,0x09,0x06,0x26,0x04,0xa8,0x80,0x00,0x01,0x00,0x20,0x02,0x00,0xe0,0x01,0x08,0xfe,0xcc,0x08,0x27,0x09,0x04,0x80,0xc7,0xc5,0xd9,0x27,0x09,0x06,0x24,0x00,0x61,0x80,0x00,0x00,0x00,0xd0,0x00,0xb7,0x40,0x01,0x08,0xfe,0xcc,0x08,0x27,0x09,0x88,0x41,0x40,0x8a,0x2e,0x00,0xbb,0x1d,0x31,0xf2,0xc3,0x23,0xe2,0x64,0xe9,0xe6,0x41,0x72,0xc1,0xa7,0x4f,0x77,0x89,0x95,0x55,0xed,0x10,0x75,0x1c,0xd5,0x6e,0x86,0x40,0x5c,0xde,0x11,0x8d,0x02,0xdf,0xfe,0x55,0x5d,0x46,0x2c,0xcf,0x6a,0x85,0xb5,0x63,0x1c,0x12,0x35,0x0c,0x8d,0x5d,0xc4,0x09,0xba,0x10,0xb9,0x02,0x5d,0x0f,0x44,0x5c,0xf4,0x49,0xd9,0x2b,0x1c,0x00,0x0c,0x04,0x2d,0x20,0xc6,0x82,0x27,0x09,0x06,0x20,0x01,0x19,0xf0,0x64,0x00,0x81,0xc3,0x54,0x00,0x00,0xff,0xfe,0x18,0x1d,0x61,0x27,0x09,0x04,0x2e,0x65,0xa0,0xf9,0x27,0x09,0x06,0x2a,0x03,0xb0,0xc0,0x00,0x03,0x00,0xd0,0x00,0x6a,0x30,0x01,0x78,0x00,0xcd,0x08,0x27,0x09,0x04,0x6b,0xbf,0x2e,0xd2,0x27,0x09,0x06,0x20,0x01,0x19,0xf0,0x68,0x00,0x83,0xa4,0x00,0x64,0xcd,0x08,0x80,0x01,0xcd,0x08,0x27,0x09,0x04,0x2d,0x20,0xf6,0xb3,0x27,0x09,0x06,0x20,0x01,0x19,0xf0,0x58,0x00,0x8b,0xf8,0x54,0x00,0x00,0xff,0xfe,0x15,0xb3,0x9a,0x27,0x09,0x04,0x2d,0x20,0xf8,0x57,0x27,0x09,0x06,0x20,0x01,0x19,0xf0,0x70,0x00,0x9b,0xc9,0x54,0x00,0x00,0xff,0xfe,0x15,0xc4,0xf5,0x27,0x09,0x04,0x9f,0xcb,0x02,0x9a,0x27,0x09,0x06,0x26,0x04,0xa8,0x80,0x0c,0xad,0x00,0xd0,0x00,0x26,0x70,0x01,0xfe,0x15,0xc4,0xf5,0x27,0x09}; static const unsigned char ZT_DEFAULT_WORLD[ZT_DEFAULT_WORLD_LENGTH] = {0x01,0x00,0x00,0x00,0x00,0x08,0xea,0xc9,0x0a,0x00,0x00,0x01,0x6b,0xd4,0x16,0x08,0xc1,0xb8,0xb3,0x88,0xa4,0x69,0x22,0x14,0x91,0xaa,0x9a,0xcd,0x66,0xcc,0x76,0x4c,0xde,0xfd,0x56,0x03,0x9f,0x10,0x67,0xae,0x15,0xe6,0x9c,0x6f,0xb4,0x2d,0x7b,0x55,0x33,0x0e,0x3f,0xda,0xac,0x52,0x9c,0x07,0x92,0xfd,0x73,0x40,0xa6,0xaa,0x21,0xab,0xa8,0xa4,0x89,0xfd,0xae,0xa4,0x4a,0x39,0xbf,0x2d,0x00,0x65,0x9a,0xc9,0xc8,0x18,0xeb,0x16,0x93,0xf4,0xe5,0xbd,0x20,0xda,0x10,0xad,0xc7,0x05,0xf4,0x99,0xfe,0x04,0x08,0x9b,0xe0,0x9e,0x77,0x1d,0x9f,0x47,0x16,0xaa,0x92,0x4f,0x10,0x16,0x3d,0xc7,0xec,0xd3,0x90,0x9e,0xd1,0x74,0xfc,0xb3,0xb5,0x07,0x9c,0x4d,0x95,0xc5,0x17,0x8b,0x3d,0x0b,0x60,0x76,0xe8,0x51,0xbb,0xb6,0x3d,0x74,0xb5,0x21,0x83,0x7b,0x95,0x1d,0x02,0x9b,0xcd,0xaf,0x5c,0x3e,0x96,0xdf,0x37,0x2c,0x56,0x6d,0xfa,0x75,0x0f,0xda,0x55,0x85,0x13,0xf4,0x76,0x1a,0x66,0x4d,0x3b,0x8d,0xcf,0x12,0xc9,0x34,0xb9,0x0d,0x61,0x03,0x3a,0x46,0xf1,0xbf,0x30,0x00,0x76,0xe6,0x6f,0xab,0x33,0xe2,0x85,0x49,0xa6,0x2e,0xe2,0x06,0x4d,0x18,0x43,0x27,0x3c,0x2c,0x30,0x0b,0xa4,0x5c,0x3f,0x20,0xbe,0xf0,0x2d,0xba,0xd2,0x25,0x72,0x3b,0xb5,0x9a,0x9b,0xb4,0xb1,0x35,0x35,0x73,0x09,0x61,0xae,0xec,0xf5,0xa1,0x63,0xac,0xe4,0x77,0xcc,0xeb,0x07,0x27,0x02,0x5b,0x99,0xac,0x14,0xa5,0x16,0x6a,0x09,0xa3,0x00,0x02,0x04,0xb9,0xb4,0x0d,0x52,0x27,0x09,0x06,0x2a,0x02,0x6e,0xa0,0xc8,0x15,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x27,0x09,0x9d,0x21,0x90,0x39,0xf3,0x00,0x01,0xf0,0x92,0x2a,0x98,0xe3,0xb3,0x4e,0xbc,0xbf,0xf3,0x33,0x26,0x9d,0xc2,0x65,0xd7,0xa0,0x20,0xaa,0xb6,0x9d,0x72,0xbe,0x4d,0x4a,0xcc,0x9c,0x8c,0x92,0x94,0x78,0x57,0x71,0x25,0x6c,0xd1,0xd9,0x42,0xa9,0x0d,0x1b,0xd1,0xd2,0xdc,0xa3,0xea,0x84,0xef,0x7d,0x85,0xaf,0xe6,0x61,0x1f,0xb4,0x3f,0xf0,0xb7,0x41,0x26,0xd9,0x0a,0x6e,0x00,0x0c,0x04,0xbc,0xa6,0x5e,0xb1,0x27,0x09,0x06,0x2a,0x03,0xb0,0xc0,0x00,0x02,0x00,0xd0,0x00,0x00,0x00,0x00,0x00,0x7d,0x00,0x01,0x27,0x09,0x04,0x9a,0x42,0xc5,0x21,0x27,0x09,0x06,0x2c,0x0f,0xf8,0x50,0x01,0x54,0x01,0x97,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x33,0x27,0x09,0x04,0x9f,0xcb,0x61,0xab,0x27,0x09,0x06,0x26,0x04,0xa8,0x80,0x08,0x00,0x00,0xa1,0x00,0x00,0x00,0x00,0x00,0x54,0x60,0x01,0x27,0x09,0x04,0x83,0xff,0x06,0x10,0x27,0x09,0x06,0x28,0x03,0xeb,0x80,0x00,0x00,0x00,0x0e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x27,0x09,0x04,0x6b,0xaa,0xc5,0x0e,0x27,0x09,0x06,0x26,0x04,0xa8,0x80,0x00,0x01,0x00,0x20,0x00,0x00,0x00,0x00,0x02,0x00,0xe0,0x01,0x27,0x09,0x04,0x80,0xc7,0xc5,0xd9,0x27,0x09,0x06,0x24,0x00,0x61,0x80,0x00,0x00,0x00,0xd0,0x00,0x00,0x00,0x00,0x00,0xb7,0x40,0x01,0x27,0x09,0x88,0x41,0x40,0x8a,0x2e,0x00,0xbb,0x1d,0x31,0xf2,0xc3,0x23,0xe2,0x64,0xe9,0xe6,0x41,0x72,0xc1,0xa7,0x4f,0x77,0x89,0x95,0x55,0xed,0x10,0x75,0x1c,0xd5,0x6e,0x86,0x40,0x5c,0xde,0x11,0x8d,0x02,0xdf,0xfe,0x55,0x5d,0x46,0x2c,0xcf,0x6a,0x85,0xb5,0x63,0x1c,0x12,0x35,0x0c,0x8d,0x5d,0xc4,0x09,0xba,0x10,0xb9,0x02,0x5d,0x0f,0x44,0x5c,0xf4,0x49,0xd9,0x2b,0x1c,0x00,0x0c,0x04,0x2d,0x20,0xc6,0x82,0x27,0x09,0x06,0x20,0x01,0x19,0xf0,0x64,0x00,0x81,0xc3,0x54,0x00,0x00,0xff,0xfe,0x18,0x1d,0x61,0x27,0x09,0x04,0x2e,0x65,0xa0,0xf9,0x27,0x09,0x06,0x2a,0x03,0xb0,0xc0,0x00,0x03,0x00,0xd0,0x00,0x00,0x00,0x00,0x00,0x6a,0x30,0x01,0x27,0x09,0x04,0x6b,0xbf,0x2e,0xd2,0x27,0x09,0x06,0x20,0x01,0x19,0xf0,0x68,0x00,0x83,0xa4,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x64,0x27,0x09,0x04,0x2d,0x20,0xf6,0xb3,0x27,0x09,0x06,0x20,0x01,0x19,0xf0,0x58,0x00,0x8b,0xf8,0x54,0x00,0x00,0xff,0xfe,0x15,0xb3,0x9a,0x27,0x09,0x04,0x2d,0x20,0xf8,0x57,0x27,0x09,0x06,0x20,0x01,0x19,0xf0,0x70,0x00,0x9b,0xc9,0x54,0x00,0x00,0xff,0xfe,0x15,0xc4,0xf5,0x27,0x09,0x04,0x9f,0xcb,0x02,0x9a,0x27,0x09,0x06,0x26,0x04,0xa8,0x80,0x0c,0xad,0x00,0xd0,0x00,0x00,0x00,0x00,0x00,0x26,0x70,0x01,0x27,0x09};

107
controller/DB.cpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#include "DB.hpp" #include "DB.hpp"
#include "EmbeddedNetworkController.hpp" #include "EmbeddedNetworkController.hpp"
@ -52,6 +39,7 @@ void DB::initNetwork(nlohmann::json &network)
if (!network.count("mtu")) network["mtu"] = ZT_DEFAULT_MTU; if (!network.count("mtu")) network["mtu"] = ZT_DEFAULT_MTU;
if (!network.count("remoteTraceTarget")) network["remoteTraceTarget"] = nlohmann::json(); if (!network.count("remoteTraceTarget")) network["remoteTraceTarget"] = nlohmann::json();
if (!network.count("removeTraceLevel")) network["remoteTraceLevel"] = 0; if (!network.count("removeTraceLevel")) network["remoteTraceLevel"] = 0;
if (!network.count("rulesSource")) network["rulesSource"] = "";
if (!network.count("rules")) { if (!network.count("rules")) {
// If unspecified, rules are set to allow anything and behave like a flat L2 segment // If unspecified, rules are set to allow anything and behave like a flat L2 segment
network["rules"] = {{ network["rules"] = {{
@ -104,20 +92,8 @@ void DB::cleanMember(nlohmann::json &member)
member.erase("lastRequestMetaData"); member.erase("lastRequestMetaData");
} }
DB::DB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path) : DB::DB() {}
_controller(nc), DB::~DB() {}
_myId(myId),
_myAddress(myId.address()),
_path((path) ? path : "")
{
char tmp[32];
_myAddress.toString(tmp);
_myAddressStr = tmp;
}
DB::~DB()
{
}
bool DB::get(const uint64_t networkId,nlohmann::json &network) bool DB::get(const uint64_t networkId,nlohmann::json &network)
{ {
@ -202,34 +178,15 @@ bool DB::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohma
return true; return true;
} }
bool DB::summary(const uint64_t networkId,NetworkSummaryInfo &info) void DB::networks(std::set<uint64_t> &networks)
{
waitForReady();
std::shared_ptr<_Network> nw;
{
std::lock_guard<std::mutex> l(_networks_l);
auto nwi = _networks.find(networkId);
if (nwi == _networks.end())
return false;
nw = nwi->second;
}
{
std::lock_guard<std::mutex> l2(nw->lock);
_fillSummaryInfo(nw,info);
}
return true;
}
void DB::networks(std::vector<uint64_t> &networks)
{ {
waitForReady(); waitForReady();
std::lock_guard<std::mutex> l(_networks_l); std::lock_guard<std::mutex> l(_networks_l);
networks.reserve(_networks.size() + 1);
for(auto n=_networks.begin();n!=_networks.end();++n) for(auto n=_networks.begin();n!=_networks.end();++n)
networks.push_back(n->first); networks.insert(n->first);
} }
void DB::_memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool push) void DB::_memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool notifyListeners)
{ {
uint64_t memberId = 0; uint64_t memberId = 0;
uint64_t networkId = 0; uint64_t networkId = 0;
@ -313,8 +270,12 @@ void DB::_memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool pu
} }
} }
if (push) if (notifyListeners) {
_controller->onNetworkMemberUpdate(networkId,memberId); std::lock_guard<std::mutex> ll(_changeListeners_l);
for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
(*i)->onNetworkMemberUpdate(this,networkId,memberId,memberConfig);
}
}
} else if (memberId) { } else if (memberId) {
if (nw) { if (nw) {
std::lock_guard<std::mutex> l(nw->lock); std::lock_guard<std::mutex> l(nw->lock);
@ -332,20 +293,24 @@ void DB::_memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool pu
} }
} }
if ((push)&&((wasAuth)&&(!isAuth)&&(networkId)&&(memberId))) if ((notifyListeners)&&((wasAuth)&&(!isAuth)&&(networkId)&&(memberId))) {
_controller->onNetworkMemberDeauthorize(networkId,memberId); std::lock_guard<std::mutex> ll(_changeListeners_l);
for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
(*i)->onNetworkMemberDeauthorize(this,networkId,memberId);
}
}
} }
void DB::_networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool push) void DB::_networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool notifyListeners)
{ {
if (networkConfig.is_object()) { if (networkConfig.is_object()) {
const std::string ids = networkConfig["id"]; const std::string ids = networkConfig["id"];
const uint64_t id = Utils::hexStrToU64(ids.c_str()); const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
if (id) { if (networkId) {
std::shared_ptr<_Network> nw; std::shared_ptr<_Network> nw;
{ {
std::lock_guard<std::mutex> l(_networks_l); std::lock_guard<std::mutex> l(_networks_l);
std::shared_ptr<_Network> &nw2 = _networks[id]; std::shared_ptr<_Network> &nw2 = _networks[networkId];
if (!nw2) if (!nw2)
nw2.reset(new _Network); nw2.reset(new _Network);
nw = nw2; nw = nw2;
@ -354,15 +319,19 @@ void DB::_networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool
std::lock_guard<std::mutex> l2(nw->lock); std::lock_guard<std::mutex> l2(nw->lock);
nw->config = networkConfig; nw->config = networkConfig;
} }
if (push) if (notifyListeners) {
_controller->onNetworkUpdate(id); std::lock_guard<std::mutex> ll(_changeListeners_l);
for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
(*i)->onNetworkUpdate(this,networkId,networkConfig);
}
}
} }
} else if (old.is_object()) { } else if (old.is_object()) {
const std::string ids = old["id"]; const std::string ids = old["id"];
const uint64_t id = Utils::hexStrToU64(ids.c_str()); const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
if (id) { if (networkId) {
std::lock_guard<std::mutex> l(_networks_l); std::lock_guard<std::mutex> l(_networks_l);
_networks.erase(id); _networks.erase(networkId);
} }
} }
} }

118
controller/DB.hpp

@ -1,32 +1,21 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_CONTROLLER_DB_HPP #ifndef ZT_CONTROLLER_DB_HPP
#define ZT_CONTROLLER_DB_HPP #define ZT_CONTROLLER_DB_HPP
//#define ZT_CONTROLLER_USE_LIBPQ
#include "../node/Constants.hpp" #include "../node/Constants.hpp"
#include "../node/Identity.hpp" #include "../node/Identity.hpp"
#include "../node/InetAddress.hpp" #include "../node/InetAddress.hpp"
@ -40,20 +29,30 @@
#include <unordered_set> #include <unordered_set>
#include <vector> #include <vector>
#include <atomic> #include <atomic>
#include <mutex>
#include <set>
#include "../ext/json/json.hpp" #include "../ext/json/json.hpp"
namespace ZeroTier namespace ZeroTier
{ {
class EmbeddedNetworkController;
/** /**
* Base class with common infrastructure for all controller DB implementations * Base class with common infrastructure for all controller DB implementations
*/ */
class DB class DB
{ {
public: public:
class ChangeListener
{
public:
ChangeListener() {}
virtual ~ChangeListener() {}
virtual void onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network) {}
virtual void onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member) {}
virtual void onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId) {}
};
struct NetworkSummaryInfo struct NetworkSummaryInfo
{ {
NetworkSummaryInfo() : authorizedMemberCount(0),totalMemberCount(0),mostRecentDeauthTime(0) {} NetworkSummaryInfo() : authorizedMemberCount(0),totalMemberCount(0),mostRecentDeauthTime(0) {}
@ -64,27 +63,12 @@ public:
int64_t mostRecentDeauthTime; int64_t mostRecentDeauthTime;
}; };
/**
* Ensure that all network fields are present
*/
static void initNetwork(nlohmann::json &network); static void initNetwork(nlohmann::json &network);
/**
* Ensure that all member fields are present
*/
static void initMember(nlohmann::json &member); static void initMember(nlohmann::json &member);
/**
* Remove old and temporary network fields
*/
static void cleanNetwork(nlohmann::json &network); static void cleanNetwork(nlohmann::json &network);
/**
* Remove old and temporary member fields
*/
static void cleanMember(nlohmann::json &member); static void cleanMember(nlohmann::json &member);
DB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path); DB();
virtual ~DB(); virtual ~DB();
virtual bool waitForReady() = 0; virtual bool waitForReady() = 0;
@ -101,19 +85,57 @@ public:
bool get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info); bool get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info);
bool get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members); bool get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members);
bool summary(const uint64_t networkId,NetworkSummaryInfo &info); void networks(std::set<uint64_t> &networks);
void networks(std::vector<uint64_t> &networks); template<typename F>
inline void each(F f)
{
nlohmann::json nullJson;
std::lock_guard<std::mutex> lck(_networks_l);
for(auto nw=_networks.begin();nw!=_networks.end();++nw) {
f(nw->first,nw->second->config,0,nullJson); // first provide network with 0 for member ID
for(auto m=nw->second->members.begin();m!=nw->second->members.end();++m) {
f(nw->first,nw->second->config,m->first,m->second);
}
}
}
virtual void save(nlohmann::json *orig,nlohmann::json &record) = 0; virtual bool save(nlohmann::json &record,bool notifyListeners) = 0;
virtual void eraseNetwork(const uint64_t networkId) = 0; virtual void eraseNetwork(const uint64_t networkId) = 0;
virtual void eraseMember(const uint64_t networkId,const uint64_t memberId) = 0; virtual void eraseMember(const uint64_t networkId,const uint64_t memberId) = 0;
virtual void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress) = 0; virtual void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress) = 0;
inline void addListener(DB::ChangeListener *const listener)
{
std::lock_guard<std::mutex> l(_changeListeners_l);
_changeListeners.push_back(listener);
}
protected: protected:
static inline bool _compareRecords(const nlohmann::json &a,const nlohmann::json &b)
{
if (a.is_object() == b.is_object()) {
if (a.is_object()) {
if (a.size() != b.size())
return false;
auto amap = a.get<nlohmann::json::object_t>();
auto bmap = b.get<nlohmann::json::object_t>();
for(auto ai=amap.begin();ai!=amap.end();++ai) {
if (ai->first != "revision") { // ignore revision, compare only non-revision-counter fields
auto bi = bmap.find(ai->first);
if ((bi == bmap.end())||(bi->second != ai->second))
return false;
}
}
return true;
}
return (a == b);
}
return false;
}
struct _Network struct _Network
{ {
_Network() : mostRecentDeauthTime(0) {} _Network() : mostRecentDeauthTime(0) {}
@ -126,18 +148,14 @@ protected:
std::mutex lock; std::mutex lock;
}; };
void _memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool push); void _memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool notifyListeners);
void _networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool push); void _networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool notifyListeners);
void _fillSummaryInfo(const std::shared_ptr<_Network> &nw,NetworkSummaryInfo &info); void _fillSummaryInfo(const std::shared_ptr<_Network> &nw,NetworkSummaryInfo &info);
EmbeddedNetworkController *const _controller; std::vector<DB::ChangeListener *> _changeListeners;
const Identity _myId;
const Address _myAddress;
const std::string _path;
std::string _myAddressStr;
std::unordered_map< uint64_t,std::shared_ptr<_Network> > _networks; std::unordered_map< uint64_t,std::shared_ptr<_Network> > _networks;
std::unordered_multimap< uint64_t,uint64_t > _networkByMember; std::unordered_multimap< uint64_t,uint64_t > _networkByMember;
mutable std::mutex _changeListeners_l;
mutable std::mutex _networks_l; mutable std::mutex _networks_l;
}; };

231
controller/DBMirrorSet.cpp

@ -0,0 +1,231 @@
/*
* Copyright (c)2019 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2023-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "DBMirrorSet.hpp"
namespace ZeroTier {
DBMirrorSet::DBMirrorSet(DB::ChangeListener *listener) :
_listener(listener),
_running(true)
{
_syncCheckerThread = std::thread([this]() {
for(;;) {
for(int i=0;i<120;++i) { // 1 minute delay between checks
if (!_running)
return;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::vector< std::shared_ptr<DB> > dbs;
{
std::lock_guard<std::mutex> l(_dbs_l);
if (_dbs.size() <= 1)
continue; // no need to do this if there's only one DB, so skip the iteration
dbs = _dbs;
}
for(auto db=dbs.begin();db!=dbs.end();++db) {
(*db)->each([this,&dbs,&db](uint64_t networkId,const nlohmann::json &network,uint64_t memberId,const nlohmann::json &member) {
try {
if (network.is_object()) {
if (memberId == 0) {
for(auto db2=dbs.begin();db2!=dbs.end();++db2) {
if (db->get() != db2->get()) {
nlohmann::json nw2;
if ((!(*db2)->get(networkId,nw2))||((nw2.is_object())&&(OSUtils::jsonInt(nw2["revision"],0) < OSUtils::jsonInt(network["revision"],0)))) {
nw2 = network;
(*db2)->save(nw2,false);
}
}
}
} else if (member.is_object()) {
for(auto db2=dbs.begin();db2!=dbs.end();++db2) {
if (db->get() != db2->get()) {
nlohmann::json nw2,m2;
if ((!(*db2)->get(networkId,nw2,memberId,m2))||((m2.is_object())&&(OSUtils::jsonInt(m2["revision"],0) < OSUtils::jsonInt(member["revision"],0)))) {
m2 = member;
(*db2)->save(m2,false);
}
}
}
}
}
} catch ( ... ) {} // skip entries that generate JSON errors
});
}
}
});
}
DBMirrorSet::~DBMirrorSet()
{
_running = false;
_syncCheckerThread.join();
}
bool DBMirrorSet::hasNetwork(const uint64_t networkId) const
{
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if ((*d)->hasNetwork(networkId))
return true;
}
return false;
}
bool DBMirrorSet::get(const uint64_t networkId,nlohmann::json &network)
{
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if ((*d)->get(networkId,network)) {
return true;
}
}
return false;
}
bool DBMirrorSet::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member)
{
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if ((*d)->get(networkId,network,memberId,member))
return true;
}
return false;
}
bool DBMirrorSet::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,DB::NetworkSummaryInfo &info)
{
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if ((*d)->get(networkId,network,memberId,member,info))
return true;
}
return false;
}
bool DBMirrorSet::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members)
{
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if ((*d)->get(networkId,network,members))
return true;
}
return false;
}
void DBMirrorSet::networks(std::set<uint64_t> &networks)
{
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
(*d)->networks(networks);
}
}
bool DBMirrorSet::waitForReady()
{
bool r = false;
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
r |= (*d)->waitForReady();
}
return r;
}
bool DBMirrorSet::isReady()
{
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if (!(*d)->isReady())
return false;
}
return true;
}
bool DBMirrorSet::save(nlohmann::json &record,bool notifyListeners)
{
std::vector< std::shared_ptr<DB> > dbs;
{
std::lock_guard<std::mutex> l(_dbs_l);
dbs = _dbs;
}
if (notifyListeners) {
for(auto d=dbs.begin();d!=dbs.end();++d) {
if ((*d)->save(record,true))
return true;
}
return false;
} else {
bool modified = false;
for(auto d=dbs.begin();d!=dbs.end();++d) {
modified |= (*d)->save(record,false);
}
return modified;
}
}
void DBMirrorSet::eraseNetwork(const uint64_t networkId)
{
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
(*d)->eraseNetwork(networkId);
}
}
void DBMirrorSet::eraseMember(const uint64_t networkId,const uint64_t memberId)
{
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
(*d)->eraseMember(networkId,memberId);
}
}
void DBMirrorSet::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
{
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
(*d)->nodeIsOnline(networkId,memberId,physicalAddress);
}
}
void DBMirrorSet::onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network)
{
nlohmann::json record(network);
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if (d->get() != db) {
(*d)->save(record,false);
}
}
_listener->onNetworkUpdate(this,networkId,network);
}
void DBMirrorSet::onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member)
{
nlohmann::json record(member);
std::lock_guard<std::mutex> l(_dbs_l);
for(auto d=_dbs.begin();d!=_dbs.end();++d) {
if (d->get() != db) {
(*d)->save(record,false);
}
}
_listener->onNetworkMemberUpdate(this,networkId,memberId,member);
}
void DBMirrorSet::onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId)
{
_listener->onNetworkMemberDeauthorize(this,networkId,memberId);
}
} // namespace ZeroTier

71
controller/DBMirrorSet.hpp

@ -0,0 +1,71 @@
/*
* Copyright (c)2019 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2023-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#ifndef ZT_DBMIRRORSET_HPP
#define ZT_DBMIRRORSET_HPP
#include "DB.hpp"
#include <vector>
#include <memory>
#include <mutex>
#include <set>
#include <thread>
namespace ZeroTier {
class DBMirrorSet : public DB::ChangeListener
{
public:
DBMirrorSet(DB::ChangeListener *listener);
virtual ~DBMirrorSet();
bool hasNetwork(const uint64_t networkId) const;
bool get(const uint64_t networkId,nlohmann::json &network);
bool get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member);
bool get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,DB::NetworkSummaryInfo &info);
bool get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members);
void networks(std::set<uint64_t> &networks);
bool waitForReady();
bool isReady();
bool save(nlohmann::json &record,bool notifyListeners);
void eraseNetwork(const uint64_t networkId);
void eraseMember(const uint64_t networkId,const uint64_t memberId);
void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress);
// These are called by various DB instances when changes occur.
virtual void onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network);
virtual void onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member);
virtual void onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId);
inline void addDB(const std::shared_ptr<DB> &db)
{
db->addListener(this);
std::lock_guard<std::mutex> l(_dbs_l);
_dbs.push_back(db);
}
private:
DB::ChangeListener *const _listener;
std::atomic_bool _running;
std::thread _syncCheckerThread;
std::vector< std::shared_ptr< DB > > _dbs;
mutable std::mutex _dbs_l;
};
} // namespace ZeroTier
#endif

153
controller/EmbeddedNetworkController.cpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#include <stdint.h> #include <stdint.h>
#include <stdio.h> #include <stdio.h>
@ -46,6 +33,11 @@
#include "../version.h" #include "../version.h"
#include "EmbeddedNetworkController.hpp" #include "EmbeddedNetworkController.hpp"
#include "LFDB.hpp"
#include "FileDB.hpp"
#ifdef ZT_CONTROLLER_USE_LIBPQ
#include "PostgreSQL.hpp"
#endif
#include "../node/Node.hpp" #include "../node/Node.hpp"
#include "../node/CertificateOfMembership.hpp" #include "../node/CertificateOfMembership.hpp"
@ -464,12 +456,14 @@ static bool _parseRule(json &r,ZT_VirtualNetworkRule &rule)
} // anonymous namespace } // anonymous namespace
EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *dbPath, int listenPort, MQConfig *mqc) : EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *ztPath,const char *dbPath, int listenPort, MQConfig *mqc) :
_startTime(OSUtils::now()), _startTime(OSUtils::now()),
_listenPort(listenPort), _listenPort(listenPort),
_node(node), _node(node),
_ztPath(ztPath),
_path(dbPath), _path(dbPath),
_sender((NetworkController::Sender *)0), _sender((NetworkController::Sender *)0),
_db(this),
_mqc(mqc) _mqc(mqc)
{ {
} }
@ -488,13 +482,48 @@ void EmbeddedNetworkController::init(const Identity &signingId,Sender *sender)
_signingId = signingId; _signingId = signingId;
_sender = sender; _sender = sender;
_signingIdAddressString = signingId.address().toString(tmp); _signingIdAddressString = signingId.address().toString(tmp);
#ifdef ZT_CONTROLLER_USE_LIBPQ #ifdef ZT_CONTROLLER_USE_LIBPQ
if ((_path.length() > 9)&&(_path.substr(0,9) == "postgres:")) if ((_path.length() > 9)&&(_path.substr(0,9) == "postgres:")) {
_db.reset(new PostgreSQL(this,_signingId,_path.substr(9).c_str(), _listenPort, _mqc)); _db.addDB(std::shared_ptr<DB>(new PostgreSQL(_signingId,_path.substr(9).c_str(), _listenPort, _mqc)));
else // else use FileDB after endif } else {
#endif #endif
_db.reset(new FileDB(this,_signingId,_path.c_str())); _db.addDB(std::shared_ptr<DB>(new FileDB(_path.c_str())));
_db->waitForReady(); #ifdef ZT_CONTROLLER_USE_LIBPQ
}
#endif
std::string lfJSON;
OSUtils::readFile((_ztPath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lfJSON);
if (lfJSON.length() > 0) {
nlohmann::json lfConfig(OSUtils::jsonParse(lfJSON));
nlohmann::json &settings = lfConfig["settings"];
if (settings.is_object()) {
nlohmann::json &controllerDb = settings["controllerDb"];
if (controllerDb.is_object()) {
std::string type = controllerDb["type"];
if (type == "lf") {
std::string lfOwner = controllerDb["owner"];
std::string lfHost = controllerDb["host"];
int lfPort = controllerDb["port"];
bool storeOnlineState = controllerDb["storeOnlineState"];
if ((lfOwner.length())&&(lfHost.length())&&(lfPort > 0)&&(lfPort < 65536)) {
std::size_t pubHdrLoc = lfOwner.find("Public: ");
if ((pubHdrLoc > 0)&&((pubHdrLoc + 8) < lfOwner.length())) {
std::string lfOwnerPublic = lfOwner.substr(pubHdrLoc + 8);
std::size_t pubHdrEnd = lfOwnerPublic.find_first_of("\n\r\t ");
if (pubHdrEnd != std::string::npos) {
lfOwnerPublic = lfOwnerPublic.substr(0,pubHdrEnd);
_db.addDB(std::shared_ptr<DB>(new LFDB(_signingId,_path.c_str(),lfOwner.c_str(),lfOwnerPublic.c_str(),lfHost.c_str(),lfPort,storeOnlineState)));
}
}
}
}
}
}
}
_db.waitForReady();
} }
void EmbeddedNetworkController::request( void EmbeddedNetworkController::request(
@ -525,15 +554,12 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
std::string &responseBody, std::string &responseBody,
std::string &responseContentType) std::string &responseContentType)
{ {
if (!_db)
return 500;
if ((path.size() > 0)&&(path[0] == "network")) { if ((path.size() > 0)&&(path[0] == "network")) {
if ((path.size() >= 2)&&(path[1].length() == 16)) { if ((path.size() >= 2)&&(path[1].length() == 16)) {
const uint64_t nwid = Utils::hexStrToU64(path[1].c_str()); const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
json network; json network;
if (!_db->get(nwid,network)) if (!_db.get(nwid,network))
return 404; return 404;
if (path.size() >= 3) { if (path.size() >= 3) {
@ -545,7 +571,7 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
const uint64_t address = Utils::hexStrToU64(path[3].c_str()); const uint64_t address = Utils::hexStrToU64(path[3].c_str());
json member; json member;
if (!_db->get(nwid,network,address,member)) if (!_db.get(nwid,network,address,member))
return 404; return 404;
responseBody = OSUtils::jsonDump(member); responseBody = OSUtils::jsonDump(member);
responseContentType = "application/json"; responseContentType = "application/json";
@ -555,7 +581,7 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
responseBody = "{"; responseBody = "{";
std::vector<json> members; std::vector<json> members;
if (_db->get(nwid,network,members)) { if (_db.get(nwid,network,members)) {
responseBody.reserve((members.size() + 2) * 32); responseBody.reserve((members.size() + 2) * 32);
std::string mid; std::string mid;
for(auto member=members.begin();member!=members.end();++member) { for(auto member=members.begin();member!=members.end();++member) {
@ -584,12 +610,12 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
} else if (path.size() == 1) { } else if (path.size() == 1) {
// List networks // List networks
std::vector<uint64_t> networkIds; std::set<uint64_t> networkIds;
_db->networks(networkIds); _db.networks(networkIds);
char tmp[64]; char tmp[64];
responseBody = "["; responseBody = "[";
responseBody.reserve((networkIds.size() + 1) * 24); responseBody.reserve((networkIds.size() + 1) * 24);
for(std::vector<uint64_t>::const_iterator i(networkIds.begin());i!=networkIds.end();++i) { for(std::set<uint64_t>::const_iterator i(networkIds.begin());i!=networkIds.end();++i) {
if (responseBody.length() > 1) if (responseBody.length() > 1)
responseBody.push_back(','); responseBody.push_back(',');
OSUtils::ztsnprintf(tmp,sizeof(tmp),"\"%.16llx\"",(unsigned long long)*i); OSUtils::ztsnprintf(tmp,sizeof(tmp),"\"%.16llx\"",(unsigned long long)*i);
@ -606,7 +632,7 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
// Controller status // Controller status
char tmp[4096]; char tmp[4096];
const bool dbOk = _db->isReady(); const bool dbOk = _db.isReady();
OSUtils::ztsnprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu,\n\t\"databaseReady\": %s\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now(),dbOk ? "true" : "false"); OSUtils::ztsnprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu,\n\t\"databaseReady\": %s\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now(),dbOk ? "true" : "false");
responseBody = tmp; responseBody = tmp;
responseContentType = "application/json"; responseContentType = "application/json";
@ -625,8 +651,6 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
std::string &responseBody, std::string &responseBody,
std::string &responseContentType) std::string &responseContentType)
{ {
if (!_db)
return 500;
if (path.empty()) if (path.empty())
return 404; return 404;
@ -660,8 +684,7 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
OSUtils::ztsnprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address); OSUtils::ztsnprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
json member,network; json member,network;
_db->get(nwid,network,address,member); _db.get(nwid,network,address,member);
json origMember(member); // for detecting changes
DB::initMember(member); DB::initMember(member);
try { try {
@ -755,7 +778,7 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
member["nwid"] = nwids; member["nwid"] = nwids;
DB::cleanMember(member); DB::cleanMember(member);
_db->save(&origMember,member); _db.save(member,true);
responseBody = OSUtils::jsonDump(member); responseBody = OSUtils::jsonDump(member);
responseContentType = "application/json"; responseContentType = "application/json";
@ -774,7 +797,7 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix)); Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL); uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL; if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
if (!_db->hasNetwork(tryNwid)) { if (!_db.hasNetwork(tryNwid)) {
nwid = tryNwid; nwid = tryNwid;
break; break;
} }
@ -785,8 +808,7 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid); OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
json network; json network;
_db->get(nwid,network); _db.get(nwid,network);
json origNetwork(network); // for detecting changes
DB::initNetwork(network); DB::initNetwork(network);
try { try {
@ -1017,7 +1039,7 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
network["nwid"] = nwids; // legacy network["nwid"] = nwids; // legacy
DB::cleanNetwork(network); DB::cleanNetwork(network);
_db->save(&origNetwork,network); _db.save(network,true);
responseBody = OSUtils::jsonDump(network); responseBody = OSUtils::jsonDump(network);
responseContentType = "application/json"; responseContentType = "application/json";
@ -1039,8 +1061,6 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
std::string &responseBody, std::string &responseBody,
std::string &responseContentType) std::string &responseContentType)
{ {
if (!_db)
return 500;
if (path.empty()) if (path.empty())
return 404; return 404;
@ -1052,8 +1072,8 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
const uint64_t address = Utils::hexStrToU64(path[3].c_str()); const uint64_t address = Utils::hexStrToU64(path[3].c_str());
json network,member; json network,member;
_db->get(nwid,network,address,member); _db.get(nwid,network,address,member);
_db->eraseMember(nwid, address); _db.eraseMember(nwid, address);
{ {
std::lock_guard<std::mutex> l(_memberStatus_l); std::lock_guard<std::mutex> l(_memberStatus_l);
@ -1068,8 +1088,8 @@ unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
} }
} else { } else {
json network; json network;
_db->get(nwid,network); _db.get(nwid,network);
_db->eraseNetwork(nwid); _db.eraseNetwork(nwid);
{ {
std::lock_guard<std::mutex> l(_memberStatus_l); std::lock_guard<std::mutex> l(_memberStatus_l);
@ -1099,9 +1119,6 @@ void EmbeddedNetworkController::handleRemoteTrace(const ZT_RemoteTrace &rt)
char id[128],tmp[128]; char id[128],tmp[128];
std::string k,v; std::string k,v;
if (!_db)
return;
try { try {
// Convert Dictionary into JSON object // Convert Dictionary into JSON object
json d; json d;
@ -1140,13 +1157,13 @@ void EmbeddedNetworkController::handleRemoteTrace(const ZT_RemoteTrace &rt)
d["objtype"] = "trace"; d["objtype"] = "trace";
d["ts"] = now; d["ts"] = now;
d["nodeId"] = Utils::hex10(rt.origin,tmp); d["nodeId"] = Utils::hex10(rt.origin,tmp);
_db->save((nlohmann::json *)0,d); _db.save(d,true);
} catch ( ... ) { } catch ( ... ) {
// drop invalid trace messages if an error occurs // drop invalid trace messages if an error occurs
} }
} }
void EmbeddedNetworkController::onNetworkUpdate(const uint64_t networkId) void EmbeddedNetworkController::onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network)
{ {
// Send an update to all members of the network that are online // Send an update to all members of the network that are online
const int64_t now = OSUtils::now(); const int64_t now = OSUtils::now();
@ -1157,7 +1174,7 @@ void EmbeddedNetworkController::onNetworkUpdate(const uint64_t networkId)
} }
} }
void EmbeddedNetworkController::onNetworkMemberUpdate(const uint64_t networkId,const uint64_t memberId) void EmbeddedNetworkController::onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member)
{ {
// Push update to member if online // Push update to member if online
try { try {
@ -1168,7 +1185,7 @@ void EmbeddedNetworkController::onNetworkMemberUpdate(const uint64_t networkId,c
} catch ( ... ) {} } catch ( ... ) {}
} }
void EmbeddedNetworkController::onNetworkMemberDeauthorize(const uint64_t networkId,const uint64_t memberId) void EmbeddedNetworkController::onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId)
{ {
const int64_t now = OSUtils::now(); const int64_t now = OSUtils::now();
Revocation rev((uint32_t)_node->prng(),networkId,0,now,ZT_REVOCATION_FLAG_FAST_PROPAGATE,Address(memberId),Revocation::CREDENTIAL_TYPE_COM); Revocation rev((uint32_t)_node->prng(),networkId,0,now,ZT_REVOCATION_FLAG_FAST_PROPAGATE,Address(memberId),Revocation::CREDENTIAL_TYPE_COM);
@ -1191,10 +1208,7 @@ void EmbeddedNetworkController::_request(
{ {
char nwids[24]; char nwids[24];
DB::NetworkSummaryInfo ns; DB::NetworkSummaryInfo ns;
json network,member,origMember; json network,member;
if (!_db)
return;
if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender)) if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
return; return;
@ -1209,15 +1223,14 @@ void EmbeddedNetworkController::_request(
ms.lastRequestTime = now; ms.lastRequestTime = now;
} }
_db->nodeIsOnline(nwid,identity.address().toInt(),fromAddr); _db.nodeIsOnline(nwid,identity.address().toInt(),fromAddr);
Utils::hex(nwid,nwids); Utils::hex(nwid,nwids);
_db->get(nwid,network,identity.address().toInt(),member,ns); _db.get(nwid,network,identity.address().toInt(),member,ns);
if ((!network.is_object())||(network.size() == 0)) { if ((!network.is_object())||(network.size() == 0)) {
_sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_OBJECT_NOT_FOUND); _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_OBJECT_NOT_FOUND);
return; return;
} }
origMember = member;
const bool newMember = ((!member.is_object())||(member.size() == 0)); const bool newMember = ((!member.is_object())||(member.size() == 0));
DB::initMember(member); DB::initMember(member);
@ -1318,7 +1331,7 @@ void EmbeddedNetworkController::_request(
} else { } else {
// If they are not authorized, STOP! // If they are not authorized, STOP!
DB::cleanMember(member); DB::cleanMember(member);
_db->save(&origMember,member); _db.save(member,true);
_sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED); _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED);
return; return;
} }
@ -1620,11 +1633,11 @@ void EmbeddedNetworkController::_request(
if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) { if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr)); uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr)); uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0)) if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
continue; continue;
uint32_t ipRangeLen = ipRangeEnd - ipRangeStart; uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
// Start with the LSB of the member's address // Start with the LSB of the member's address
uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff); uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
@ -1671,7 +1684,7 @@ void EmbeddedNetworkController::_request(
} }
} }
} }
// Issue a certificate of ownership for all static IPs // Issue a certificate of ownership for all static IPs
if (nc->staticIpCount) { if (nc->staticIpCount) {
nc->certificatesOfOwnership[0] = CertificateOfOwnership(nwid,now,identity.address(),1); nc->certificatesOfOwnership[0] = CertificateOfOwnership(nwid,now,identity.address(),1);
@ -1690,7 +1703,7 @@ void EmbeddedNetworkController::_request(
} }
DB::cleanMember(member); DB::cleanMember(member);
_db->save(&origMember,member); _db.save(member,true);
_sender->ncSendConfig(nwid,requestPacketId,identity.address(),*(nc.get()),metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,0) < 6); _sender->ncSendConfig(nwid,requestPacketId,identity.address(),*(nc.get()),metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,0) < 6);
} }

46
controller/EmbeddedNetworkController.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_SQLITENETWORKCONTROLLER_HPP #ifndef ZT_SQLITENETWORKCONTROLLER_HPP
#define ZT_SQLITENETWORKCONTROLLER_HPP #define ZT_SQLITENETWORKCONTROLLER_HPP
@ -51,10 +38,7 @@
#include "../ext/json/json.hpp" #include "../ext/json/json.hpp"
#include "DB.hpp" #include "DB.hpp"
#include "FileDB.hpp" #include "DBMirrorSet.hpp"
#ifdef ZT_CONTROLLER_USE_LIBPQ
#include "PostgreSQL.hpp"
#endif
namespace ZeroTier { namespace ZeroTier {
@ -62,14 +46,14 @@ class Node;
struct MQConfig; struct MQConfig;
class EmbeddedNetworkController : public NetworkController class EmbeddedNetworkController : public NetworkController,public DB::ChangeListener
{ {
public: public:
/** /**
* @param node Parent node * @param node Parent node
* @param dbPath Database path (file path or database credentials) * @param dbPath Database path (file path or database credentials)
*/ */
EmbeddedNetworkController(Node *node,const char *dbPath, int listenPort, MQConfig *mqc = NULL); EmbeddedNetworkController(Node *node,const char *ztPath,const char *dbPath, int listenPort, MQConfig *mqc = NULL);
virtual ~EmbeddedNetworkController(); virtual ~EmbeddedNetworkController();
virtual void init(const Identity &signingId,Sender *sender); virtual void init(const Identity &signingId,Sender *sender);
@ -105,10 +89,9 @@ public:
void handleRemoteTrace(const ZT_RemoteTrace &rt); void handleRemoteTrace(const ZT_RemoteTrace &rt);
// Called on update via POST or by JSONDB on external update of network or network member records virtual void onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network);
void onNetworkUpdate(const uint64_t networkId); virtual void onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member);
void onNetworkMemberUpdate(const uint64_t networkId,const uint64_t memberId); virtual void onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId);
void onNetworkMemberDeauthorize(const uint64_t networkId,const uint64_t memberId);
private: private:
void _request(uint64_t nwid,const InetAddress &fromAddr,uint64_t requestPacketId,const Identity &identity,const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData); void _request(uint64_t nwid,const InetAddress &fromAddr,uint64_t requestPacketId,const Identity &identity,const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData);
@ -153,12 +136,13 @@ private:
const int64_t _startTime; const int64_t _startTime;
int _listenPort; int _listenPort;
Node *const _node; Node *const _node;
std::string _ztPath;
std::string _path; std::string _path;
Identity _signingId; Identity _signingId;
std::string _signingIdAddressString; std::string _signingIdAddressString;
NetworkController::Sender *_sender; NetworkController::Sender *_sender;
std::unique_ptr<DB> _db; DBMirrorSet _db;
BlockingQueue< _RQEntry * > _queue; BlockingQueue< _RQEntry * > _queue;
std::vector<std::thread> _threads; std::vector<std::thread> _threads;

116
controller/FileDB.cpp

@ -1,38 +1,27 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#include "FileDB.hpp" #include "FileDB.hpp"
namespace ZeroTier namespace ZeroTier
{ {
FileDB::FileDB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path) : FileDB::FileDB(const char *path) :
DB(nc,myId,path), DB(),
_path(path),
_networksPath(_path + ZT_PATH_SEPARATOR_S + "network"), _networksPath(_path + ZT_PATH_SEPARATOR_S + "network"),
_tracePath(_path + ZT_PATH_SEPARATOR_S + "trace") _tracePath(_path + ZT_PATH_SEPARATOR_S + "trace"),
_running(true)
{ {
OSUtils::mkdir(_path.c_str()); OSUtils::mkdir(_path.c_str());
OSUtils::lockDownFile(_path.c_str(),true); OSUtils::lockDownFile(_path.c_str(),true);
@ -71,50 +60,52 @@ FileDB::FileDB(EmbeddedNetworkController *const nc,const Identity &myId,const ch
} }
} }
FileDB::~FileDB() {} FileDB::~FileDB()
{
try {
_online_l.lock();
_running = false;
_online_l.unlock();
_onlineUpdateThread.join();
} catch ( ... ) {}
}
bool FileDB::waitForReady() { return true; } bool FileDB::waitForReady() { return true; }
bool FileDB::isReady() { return true; } bool FileDB::isReady() { return true; }
void FileDB::save(nlohmann::json *orig,nlohmann::json &record) bool FileDB::save(nlohmann::json &record,bool notifyListeners)
{ {
char p1[4096],p2[4096],pb[4096]; char p1[4096],p2[4096],pb[4096];
bool modified = false;
try { try {
if (orig) {
if (*orig != record) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
}
} else {
record["revision"] = 1;
}
const std::string objtype = record["objtype"]; const std::string objtype = record["objtype"];
if (objtype == "network") { if (objtype == "network") {
const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL); const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
if (nwid) { if (nwid) {
nlohmann::json old; nlohmann::json old;
get(nwid,old); get(nwid,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
if ((!old.is_object())||(old != record)) { record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json.new",_networksPath.c_str(),nwid); OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),nwid);
OSUtils::ztsnprintf(p2,sizeof(p2),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),nwid);
if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1))) if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1)))
fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1); fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1);
OSUtils::rename(p1,p2); _networkChanged(old,record,notifyListeners);
modified = true;
_networkChanged(old,record,true);
} }
} }
} else if (objtype == "member") { } else if (objtype == "member") {
const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL); const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL); const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
if ((id)&&(nwid)) { if ((id)&&(nwid)) {
nlohmann::json network,old; nlohmann::json network,old;
get(nwid,network,id,old); get(nwid,network,id,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
if ((!old.is_object())||(old != record)) { record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
OSUtils::ztsnprintf(pb,sizeof(pb),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)nwid); OSUtils::ztsnprintf(pb,sizeof(pb),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)nwid);
OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.10llx.json.new",pb,(unsigned long long)id); OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.10llx.json",pb,(unsigned long long)id);
if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1))) { if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1))) {
OSUtils::ztsnprintf(p2,sizeof(p2),"%s" ZT_PATH_SEPARATOR_S "%.16llx",_networksPath.c_str(),(unsigned long long)nwid); OSUtils::ztsnprintf(p2,sizeof(p2),"%s" ZT_PATH_SEPARATOR_S "%.16llx",_networksPath.c_str(),(unsigned long long)nwid);
OSUtils::mkdir(p2); OSUtils::mkdir(p2);
@ -122,20 +113,14 @@ void FileDB::save(nlohmann::json *orig,nlohmann::json &record)
if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1))) if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1)))
fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1); fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1);
} }
OSUtils::ztsnprintf(p2,sizeof(p2),"%s" ZT_PATH_SEPARATOR_S "%.10llx.json",pb,(unsigned long long)id); _memberChanged(old,record,notifyListeners);
OSUtils::rename(p1,p2); modified = true;
_memberChanged(old,record,true);
} }
} }
} else if (objtype == "trace") {
const std::string id = record["id"];
if (id.length() > 0) {
OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%s.json",_tracePath.c_str(),id.c_str());
OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1));
}
} }
} catch ( ... ) {} // drop invalid records missing fields } catch ( ... ) {} // drop invalid records missing fields
return modified;
} }
void FileDB::eraseNetwork(const uint64_t networkId) void FileDB::eraseNetwork(const uint64_t networkId)
@ -144,29 +129,34 @@ void FileDB::eraseNetwork(const uint64_t networkId)
get(networkId,network); get(networkId,network);
char p[16384]; char p[16384];
OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),networkId); OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),networkId);
OSUtils::rm(p);
if (OSUtils::fileExists(p,false)){ OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)networkId);
OSUtils::rm(p); OSUtils::rmDashRf(p);
}
_networkChanged(network,nullJson,true); _networkChanged(network,nullJson,true);
std::lock_guard<std::mutex> l(this->_online_l);
this->_online.erase(networkId);
} }
void FileDB::eraseMember(const uint64_t networkId,const uint64_t memberId) void FileDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
{ {
nlohmann::json network,member,nullJson; nlohmann::json network,member,nullJson;
get(networkId,network); get(networkId,network);
get(memberId,member); get(memberId,member);
char p[16384]; char p[4096];
OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member" ZT_PATH_SEPARATOR_S "%.10llx.json",_networksPath.c_str(),networkId,memberId); OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member" ZT_PATH_SEPARATOR_S "%.10llx.json",_networksPath.c_str(),networkId,memberId);
if (OSUtils::fileExists(p,false)){ OSUtils::rm(p);
OSUtils::rm(p);
}
_memberChanged(member,nullJson,true); _memberChanged(member,nullJson,true);
std::lock_guard<std::mutex> l(this->_online_l);
this->_online[networkId].erase(memberId);
} }
void FileDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress) void FileDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
{ {
// Nothing to do here right now in the filesystem store mode since we can just get this from the peer list char mid[32],atmp[64];
OSUtils::ztsnprintf(mid,sizeof(mid),"%.10llx",(unsigned long long)memberId);
physicalAddress.toString(atmp);
std::lock_guard<std::mutex> l(this->_online_l);
this->_online[networkId][memberId][OSUtils::now()] = physicalAddress;
} }
} // namespace ZeroTier } // namespace ZeroTier

36
controller/FileDB.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_CONTROLLER_FILEDB_HPP #ifndef ZT_CONTROLLER_FILEDB_HPP
#define ZT_CONTROLLER_FILEDB_HPP #define ZT_CONTROLLER_FILEDB_HPP
@ -35,19 +22,24 @@ namespace ZeroTier
class FileDB : public DB class FileDB : public DB
{ {
public: public:
FileDB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path); FileDB(const char *path);
virtual ~FileDB(); virtual ~FileDB();
virtual bool waitForReady(); virtual bool waitForReady();
virtual bool isReady(); virtual bool isReady();
virtual void save(nlohmann::json *orig,nlohmann::json &record); virtual bool save(nlohmann::json &record,bool notifyListeners);
virtual void eraseNetwork(const uint64_t networkId); virtual void eraseNetwork(const uint64_t networkId);
virtual void eraseMember(const uint64_t networkId,const uint64_t memberId); virtual void eraseMember(const uint64_t networkId,const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress); virtual void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress);
protected: protected:
std::string _path;
std::string _networksPath; std::string _networksPath;
std::string _tracePath; std::string _tracePath;
std::thread _onlineUpdateThread;
std::map< uint64_t,std::map<uint64_t,std::map<int64_t,InetAddress> > > _online;
std::mutex _online_l;
bool _running;
}; };
} // namespace ZeroTier } // namespace ZeroTier

406
controller/LFDB.cpp

@ -0,0 +1,406 @@
/*
* Copyright (c)2019 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2023-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "LFDB.hpp"
#include <thread>
#include <chrono>
#include <iostream>
#include <sstream>
#include "../osdep/OSUtils.hpp"
#include "../ext/cpp-httplib/httplib.h"
namespace ZeroTier
{
LFDB::LFDB(const Identity &myId,const char *path,const char *lfOwnerPrivate,const char *lfOwnerPublic,const char *lfNodeHost,int lfNodePort,bool storeOnlineState) :
DB(),
_myId(myId),
_lfOwnerPrivate((lfOwnerPrivate) ? lfOwnerPrivate : ""),
_lfOwnerPublic((lfOwnerPublic) ? lfOwnerPublic : ""),
_lfNodeHost((lfNodeHost) ? lfNodeHost : "127.0.0.1"),
_lfNodePort(((lfNodePort > 0)&&(lfNodePort < 65536)) ? lfNodePort : 9980),
_running(true),
_ready(false),
_storeOnlineState(storeOnlineState)
{
_syncThread = std::thread([this]() {
char controllerAddress[24];
const uint64_t controllerAddressInt = _myId.address().toInt();
_myId.address().toString(controllerAddress);
std::string networksSelectorName("com.zerotier.controller.lfdb:"); networksSelectorName.append(controllerAddress); networksSelectorName.append("/network");
// LF record masking key is the first 32 bytes of SHA512(controller private key) in hex,
// hiding record values from anything but the controller or someone who has its key.
uint8_t sha512pk[64];
_myId.sha512PrivateKey(sha512pk);
char maskingKey [128];
Utils::hex(sha512pk,32,maskingKey);
httplib::Client htcli(_lfNodeHost.c_str(),_lfNodePort,600);
int64_t timeRangeStart = 0;
while (_running.load()) {
{
std::lock_guard<std::mutex> sl(_state_l);
for(auto ns=_state.begin();ns!=_state.end();++ns) {
if (ns->second.dirty) {
nlohmann::json network;
if (get(ns->first,network)) {
nlohmann::json newrec,selector0;
selector0["Name"] = networksSelectorName;
selector0["Ordinal"] = ns->first;
newrec["Selectors"].push_back(selector0);
newrec["Value"] = network.dump();
newrec["OwnerPrivate"] = _lfOwnerPrivate;
newrec["MaskingKey"] = maskingKey;
newrec["PulseIfUnchanged"] = true;
try {
auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
if (resp) {
if (resp->status == 200) {
ns->second.dirty = false;
//printf("SET network %.16llx %s\n",ns->first,resp->body.c_str());
} else {
fprintf(stderr,"ERROR: LFDB: %d from node (create/update network): %s" ZT_EOL_S,resp->status,resp->body.c_str());
}
} else {
fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
}
} catch (std::exception &e) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update network): %s" ZT_EOL_S,e.what());
} catch ( ... ) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update network): unknown exception" ZT_EOL_S);
}
}
}
for(auto ms=ns->second.members.begin();ms!=ns->second.members.end();++ms) {
if ((_storeOnlineState)&&(ms->second.lastOnlineDirty)&&(ms->second.lastOnlineAddress)) {
nlohmann::json newrec,selector0,selector1,selectors,ip;
char tmp[1024],tmp2[128];
OSUtils::ztsnprintf(tmp,sizeof(tmp),"com.zerotier.controller.lfdb:%s/network/%.16llx/online",controllerAddress,(unsigned long long)ns->first);
ms->second.lastOnlineAddress.toIpString(tmp2);
selector0["Name"] = tmp;
selector0["Ordinal"] = ms->first;
selector1["Name"] = tmp2;
selector1["Ordinal"] = 0;
selectors.push_back(selector0);
selectors.push_back(selector1);
newrec["Selectors"] = selectors;
const uint8_t *const rawip = (const uint8_t *)ms->second.lastOnlineAddress.rawIpData();
switch(ms->second.lastOnlineAddress.ss_family) {
case AF_INET:
for(int j=0;j<4;++j)
ip.push_back((unsigned int)rawip[j]);
break;
case AF_INET6:
for(int j=0;j<16;++j)
ip.push_back((unsigned int)rawip[j]);
break;
default:
ip = tmp2; // should never happen since only IP transport is currently supported
break;
}
newrec["Value"] = ip;
newrec["OwnerPrivate"] = _lfOwnerPrivate;
newrec["MaskingKey"] = maskingKey;
newrec["Timestamp"] = ms->second.lastOnlineTime;
newrec["PulseIfUnchanged"] = true;
try {
auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
if (resp) {
if (resp->status == 200) {
ms->second.lastOnlineDirty = false;
//printf("SET member online %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
} else {
fprintf(stderr,"ERROR: LFDB: %d from node (create/update member online status): %s" ZT_EOL_S,resp->status,resp->body.c_str());
}
} else {
fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
}
} catch (std::exception &e) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member online status): %s" ZT_EOL_S,e.what());
} catch ( ... ) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member online status): unknown exception" ZT_EOL_S);
}
}
if (ms->second.dirty) {
nlohmann::json network,member;
if (get(ns->first,network,ms->first,member)) {
nlohmann::json newrec,selector0,selector1,selectors;
selector0["Name"] = networksSelectorName;
selector0["Ordinal"] = ns->first;
selector1["Name"] = "member";
selector1["Ordinal"] = ms->first;
selectors.push_back(selector0);
selectors.push_back(selector1);
newrec["Selectors"] = selectors;
newrec["Value"] = member.dump();
newrec["OwnerPrivate"] = _lfOwnerPrivate;
newrec["MaskingKey"] = maskingKey;
newrec["PulseIfUnchanged"] = true;
try {
auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
if (resp) {
if (resp->status == 200) {
ms->second.dirty = false;
//printf("SET member %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
} else {
fprintf(stderr,"ERROR: LFDB: %d from node (create/update member): %s" ZT_EOL_S,resp->status,resp->body.c_str());
}
} else {
fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
}
} catch (std::exception &e) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member): %s" ZT_EOL_S,e.what());
} catch ( ... ) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member): unknown exception" ZT_EOL_S);
}
}
}
}
}
}
try {
std::ostringstream query;
query <<
"{"
"\"Ranges\":[{"
"\"Name\":\"" << networksSelectorName << "\","
"\"Range\":[0,18446744073709551615]"
"}],"
"\"TimeRange\":[" << timeRangeStart << ",9223372036854775807],"
"\"MaskingKey\":\"" << maskingKey << "\","
"\"Owners\":[\"" << _lfOwnerPublic << "\"]"
"}";
auto resp = htcli.Post("/query",query.str(),"application/json");
if (resp) {
if (resp->status == 200) {
nlohmann::json results(OSUtils::jsonParse(resp->body));
if ((results.is_array())&&(results.size() > 0)) {
for(std::size_t ri=0;ri<results.size();++ri) {
nlohmann::json &rset = results[ri];
if ((rset.is_array())&&(rset.size() > 0)) {
nlohmann::json &result = rset[0];
if (result.is_object()) {
nlohmann::json &record = result["Record"];
if (record.is_object()) {
const std::string recordValue = result["Value"];
//printf("GET network %s\n",recordValue.c_str());
nlohmann::json network(OSUtils::jsonParse(recordValue));
if (network.is_object()) {
const std::string idstr = network["id"];
const uint64_t id = Utils::hexStrToU64(idstr.c_str());
if ((id >> 24) == controllerAddressInt) { // sanity check
nlohmann::json oldNetwork;
if ((timeRangeStart > 0)&&(get(id,oldNetwork))) {
const uint64_t revision = network["revision"];
const uint64_t prevRevision = oldNetwork["revision"];
if (prevRevision < revision) {
_networkChanged(oldNetwork,network,timeRangeStart > 0);
}
} else {
nlohmann::json nullJson;
_networkChanged(nullJson,network,timeRangeStart > 0);
}
}
}
}
}
}
}
}
} else {
fprintf(stderr,"ERROR: LFDB: %d from node (check for network updates): %s" ZT_EOL_S,resp->status,resp->body.c_str());
}
} else {
fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
}
} catch (std::exception &e) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for network updates): %s" ZT_EOL_S,e.what());
} catch ( ... ) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for network updates): unknown exception" ZT_EOL_S);
}
try {
std::ostringstream query;
query <<
"{"
"\"Ranges\":[{"
"\"Name\":\"" << networksSelectorName << "\","
"\"Range\":[0,18446744073709551615]"
"},{"
"\"Name\":\"member\","
"\"Range\":[0,18446744073709551615]"
"}],"
"\"TimeRange\":[" << timeRangeStart << ",9223372036854775807],"
"\"MaskingKey\":\"" << maskingKey << "\","
"\"Owners\":[\"" << _lfOwnerPublic << "\"]"
"}";
auto resp = htcli.Post("/query",query.str(),"application/json");
if (resp) {
if (resp->status == 200) {
nlohmann::json results(OSUtils::jsonParse(resp->body));
if ((results.is_array())&&(results.size() > 0)) {
for(std::size_t ri=0;ri<results.size();++ri) {
nlohmann::json &rset = results[ri];
if ((rset.is_array())&&(rset.size() > 0)) {
nlohmann::json &result = rset[0];
if (result.is_object()) {
nlohmann::json &record = result["Record"];
if (record.is_object()) {
const std::string recordValue = result["Value"];
//printf("GET member %s\n",recordValue.c_str());
nlohmann::json member(OSUtils::jsonParse(recordValue));
if (member.is_object()) {
const std::string nwidstr = member["nwid"];
const std::string idstr = member["id"];
const uint64_t nwid = Utils::hexStrToU64(nwidstr.c_str());
const uint64_t id = Utils::hexStrToU64(idstr.c_str());
if ((id)&&((nwid >> 24) == controllerAddressInt)) { // sanity check
nlohmann::json network,oldMember;
if ((timeRangeStart > 0)&&(get(nwid,network,id,oldMember))) {
const uint64_t revision = member["revision"];
const uint64_t prevRevision = oldMember["revision"];
if (prevRevision < revision)
_memberChanged(oldMember,member,timeRangeStart > 0);
} else if (hasNetwork(nwid)) {
nlohmann::json nullJson;
_memberChanged(nullJson,member,timeRangeStart > 0);
}
}
}
}
}
}
}
}
} else {
fprintf(stderr,"ERROR: LFDB: %d from node (check for member updates): %s" ZT_EOL_S,resp->status,resp->body.c_str());
}
} else {
fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
}
} catch (std::exception &e) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for member updates): %s" ZT_EOL_S,e.what());
} catch ( ... ) {
fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for member updates): unknown exception" ZT_EOL_S);
}
timeRangeStart = time(nullptr) - 120; // start next query 2m before now to avoid losing updates
_ready.store(true);
for(int k=0;k<4;++k) { // 2s delay between queries for remotely modified networks or members
if (!_running.load())
return;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
});
}
LFDB::~LFDB()
{
_running.store(false);
_syncThread.join();
}
bool LFDB::waitForReady()
{
while (!_ready.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
return true;
}
bool LFDB::isReady()
{
return (_ready.load());
}
bool LFDB::save(nlohmann::json &record,bool notifyListeners)
{
bool modified = false;
const std::string objtype = record["objtype"];
if (objtype == "network") {
const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
if (nwid) {
nlohmann::json old;
get(nwid,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
_networkChanged(old,record,notifyListeners);
{
std::lock_guard<std::mutex> l(_state_l);
_state[nwid].dirty = true;
}
modified = true;
}
}
} else if (objtype == "member") {
const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
if ((id)&&(nwid)) {
nlohmann::json network,old;
get(nwid,network,id,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
_memberChanged(old,record,notifyListeners);
{
std::lock_guard<std::mutex> l(_state_l);
_state[nwid].members[id].dirty = true;
}
modified = true;
}
}
}
return modified;
}
void LFDB::eraseNetwork(const uint64_t networkId)
{
// TODO
}
void LFDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
{
// TODO
}
void LFDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
{
std::lock_guard<std::mutex> l(_state_l);
auto nw = _state.find(networkId);
if (nw != _state.end()) {
auto m = nw->second.members.find(memberId);
if (m != nw->second.members.end()) {
m->second.lastOnlineTime = OSUtils::now();
if (physicalAddress)
m->second.lastOnlineAddress = physicalAddress;
m->second.lastOnlineDirty = true;
}
}
}
} // namespace ZeroTier

89
controller/LFDB.hpp

@ -0,0 +1,89 @@
/*
* Copyright (c)2019 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2023-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#ifndef ZT_CONTROLLER_LFDB_HPP
#define ZT_CONTROLLER_LFDB_HPP
#include "DB.hpp"
#include <mutex>
#include <string>
#include <unordered_map>
#include <atomic>
namespace ZeroTier {
/**
* DB implementation for controller that stores data in LF
*/
class LFDB : public DB
{
public:
/**
* @param myId This controller's identity
* @param path Base path for ZeroTier node itself
* @param lfOwnerPrivate LF owner private in PEM format
* @param lfOwnerPublic LF owner public in @base62 format
* @param lfNodeHost LF node host
* @param lfNodePort LF node http (not https) port
* @param storeOnlineState If true, store online/offline state and IP info in LF (a lot of data, only for private networks!)
*/
LFDB(const Identity &myId,const char *path,const char *lfOwnerPrivate,const char *lfOwnerPublic,const char *lfNodeHost,int lfNodePort,bool storeOnlineState);
virtual ~LFDB();
virtual bool waitForReady();
virtual bool isReady();
virtual bool save(nlohmann::json &record,bool notifyListeners);
virtual void eraseNetwork(const uint64_t networkId);
virtual void eraseMember(const uint64_t networkId,const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress);
protected:
const Identity _myId;
std::string _lfOwnerPrivate,_lfOwnerPublic;
std::string _lfNodeHost;
int _lfNodePort;
struct _MemberState
{
_MemberState() :
lastOnlineAddress(),
lastOnlineTime(0),
dirty(false),
lastOnlineDirty(false) {}
InetAddress lastOnlineAddress;
int64_t lastOnlineTime;
bool dirty;
bool lastOnlineDirty;
};
struct _NetworkState
{
_NetworkState() :
members(),
dirty(false) {}
std::unordered_map<uint64_t,_MemberState> members;
bool dirty;
};
std::unordered_map<uint64_t,_NetworkState> _state;
std::mutex _state_l;
std::atomic_bool _running;
std::atomic_bool _ready;
std::thread _syncThread;
bool _storeOnlineState;
};
} // namespace ZeroTier
#endif

379
controller/PostgreSQL.cpp

@ -1,32 +1,21 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#include "PostgreSQL.hpp"
#ifdef ZT_CONTROLLER_USE_LIBPQ #ifdef ZT_CONTROLLER_USE_LIBPQ
#include "PostgreSQL.hpp" #include "../node/Constants.hpp"
#include "EmbeddedNetworkController.hpp" #include "EmbeddedNetworkController.hpp"
#include "RabbitMQ.hpp" #include "RabbitMQ.hpp"
#include "../version.h" #include "../version.h"
@ -37,8 +26,11 @@
#include <amqp_tcp_socket.h> #include <amqp_tcp_socket.h>
using json = nlohmann::json; using json = nlohmann::json;
namespace { namespace {
static const int DB_MINIMUM_VERSION = 5;
static const char *_timestr() static const char *_timestr()
{ {
time_t t = time(0); time_t t = time(0);
@ -56,6 +48,7 @@ static const char *_timestr()
return ts; return ts;
} }
/*
std::string join(const std::vector<std::string> &elements, const char * const separator) std::string join(const std::vector<std::string> &elements, const char * const separator)
{ {
switch(elements.size()) { switch(elements.size()) {
@ -70,21 +63,56 @@ std::string join(const std::vector<std::string> &elements, const char * const se
return os.str(); return os.str();
} }
} }
*/
} } // anonymous namespace
using namespace ZeroTier; using namespace ZeroTier;
PostgreSQL::PostgreSQL(EmbeddedNetworkController *const nc, const Identity &myId, const char *path, int listenPort, MQConfig *mqc) PostgreSQL::PostgreSQL(const Identity &myId, const char *path, int listenPort, MQConfig *mqc)
: DB(nc, myId, path) : DB()
, _ready(0) , _myId(myId)
, _myAddress(myId.address())
, _ready(0)
, _connected(1) , _connected(1)
, _run(1) , _run(1)
, _waitNoticePrinted(false) , _waitNoticePrinted(false)
, _listenPort(listenPort) , _listenPort(listenPort)
, _mqc(mqc) , _mqc(mqc)
{ {
_connString = std::string(path) + " application_name=controller_" +_myAddressStr; char myAddress[64];
_myAddressStr = myId.address().toString(myAddress);
_connString = std::string(path) + " application_name=controller_" + _myAddressStr;
// Database Schema Version Check
PGconn *conn = getPgConn();
if (PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "Bad Database Connection: %s", PQerrorMessage(conn));
exit(1);
}
PGresult *res = PQexec(conn, "SELECT version FROM ztc_database");
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "Error determining database version");
exit(1);
}
if (PQntuples(res) != 1) {
fprintf(stderr, "Invalid number of db version tuples returned.");
exit(1);
}
int dbVersion = std::stoi(PQgetvalue(res, 0, 0));
if (dbVersion < DB_MINIMUM_VERSION) {
fprintf(stderr, "Central database schema version too low. This controller version requires a minimum schema version of %d. Please upgrade your Central instance", DB_MINIMUM_VERSION);
exit(1);
}
PQclear(res);
res = NULL;
PQfinish(conn);
conn = NULL;
_readyLock.lock(); _readyLock.lock();
_heartbeatThread = std::thread(&PostgreSQL::heartbeat, this); _heartbeatThread = std::thread(&PostgreSQL::heartbeat, this);
@ -100,7 +128,7 @@ PostgreSQL::~PostgreSQL()
{ {
_run = 0; _run = 0;
std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::this_thread::sleep_for(std::chrono::milliseconds(100));
_heartbeatThread.join(); _heartbeatThread.join();
_membersDbWatcher.join(); _membersDbWatcher.join();
_networksDbWatcher.join(); _networksDbWatcher.join();
@ -130,27 +158,43 @@ bool PostgreSQL::isReady()
return ((_ready == 2)&&(_connected)); return ((_ready == 2)&&(_connected));
} }
void PostgreSQL::save(nlohmann::json *orig, nlohmann::json &record) bool PostgreSQL::save(nlohmann::json &record,bool notifyListeners)
{ {
bool modified = false;
try { try {
if (!record.is_object()) { if (!record.is_object())
return; return false;
} const std::string objtype = record["objtype"];
waitForReady(); if (objtype == "network") {
if (orig) { const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
if (*orig != record) { if (nwid) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1; nlohmann::json old;
_commitQueue.post(new nlohmann::json(record)); get(nwid,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
_commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
modified = true;
}
}
} else if (objtype == "member") {
const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
if ((id)&&(nwid)) {
nlohmann::json network,old;
get(nwid,network,id,old);
if ((!old.is_object())||(!_compareRecords(old,record))) {
record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
_commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
modified = true;
}
} }
} else {
record["revision"] = 1;
_commitQueue.post(new nlohmann::json(record));
} }
} catch (std::exception &e) { } catch (std::exception &e) {
fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what()); fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
} catch (...) { } catch (...) {
fprintf(stderr, "Unknown error on PostgreSQL::save\n"); fprintf(stderr, "Unknown error on PostgreSQL::save\n");
} }
return modified;
} }
void PostgreSQL::eraseNetwork(const uint64_t networkId) void PostgreSQL::eraseNetwork(const uint64_t networkId)
@ -158,21 +202,23 @@ void PostgreSQL::eraseNetwork(const uint64_t networkId)
char tmp2[24]; char tmp2[24];
waitForReady(); waitForReady();
Utils::hex(networkId, tmp2); Utils::hex(networkId, tmp2);
json *tmp = new json(); std::pair<nlohmann::json,bool> tmp;
(*tmp)["id"] = tmp2; tmp.first["id"] = tmp2;
(*tmp)["objtype"] = "_delete_network"; tmp.first["objtype"] = "_delete_network";
tmp.second = true;
_commitQueue.post(tmp); _commitQueue.post(tmp);
} }
void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId) void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
{ {
char tmp2[24]; char tmp2[24];
json *tmp = new json(); std::pair<nlohmann::json,bool> tmp;
Utils::hex(networkId, tmp2); Utils::hex(networkId, tmp2);
(*tmp)["nwid"] = tmp2; tmp.first["nwid"] = tmp2;
Utils::hex(memberId, tmp2); Utils::hex(memberId, tmp2);
(*tmp)["id"] = tmp2; tmp.first["id"] = tmp2;
(*tmp)["objtype"] = "_delete_member"; tmp.first["objtype"] = "_delete_member";
tmp.second = true;
_commitQueue.post(tmp); _commitQueue.post(tmp);
} }
@ -208,7 +254,7 @@ void PostgreSQL::initializeNetworks(PGconn *conn)
NULL, NULL,
NULL, NULL,
0); 0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) { if (PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "Networks Initialization Failed: %s", PQerrorMessage(conn)); fprintf(stderr, "Networks Initialization Failed: %s", PQerrorMessage(conn));
PQclear(res); PQclear(res);
@ -280,7 +326,7 @@ void PostgreSQL::initializeNetworks(PGconn *conn)
NULL, NULL,
NULL, NULL,
0); 0);
if (PQresultStatus(r2) != PGRES_TUPLES_OK) { if (PQresultStatus(r2) != PGRES_TUPLES_OK) {
fprintf(stderr, "ERROR: Error retreiving IP pools for network: %s\n", PQresultErrorMessage(r2)); fprintf(stderr, "ERROR: Error retreiving IP pools for network: %s\n", PQresultErrorMessage(r2));
PQclear(r2); PQclear(r2);
@ -332,7 +378,7 @@ void PostgreSQL::initializeNetworks(PGconn *conn)
} }
PQclear(r2); PQclear(r2);
_networkChanged(empty, config, false); _networkChanged(empty, config, false);
} }
@ -512,7 +558,7 @@ void PostgreSQL::heartbeat()
if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) { if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
hostnameTmp[0] = (char)0; hostnameTmp[0] = (char)0;
} else { } else {
for (int i = 0; i < sizeof(hostnameTmp); ++i) { for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) { if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
hostnameTmp[i] = (char)0; hostnameTmp[i] = (char)0;
break; break;
@ -557,14 +603,14 @@ void PostgreSQL::heartbeat()
}; };
PGresult *res = PQexecParams(conn, PGresult *res = PQexecParams(conn,
"INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build, host_port, use_rabbitmq) " "INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build, host_port, use_rabbitmq) "
"VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8, $9, $10) " "VALUES ($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5, $6, $7, $8, $9, $10) "
"ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, " "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
"public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, " "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
"v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, " "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, "
"use_rabbitmq = EXCLUDED.use_rabbitmq", "use_rabbitmq = EXCLUDED.use_rabbitmq",
10, // number of parameters 10, // number of parameters
NULL, // oid field. ignore NULL, // oid field. ignore
values, // values for substitution values, // values for substitution
NULL, // lengths in bytes of each value NULL, // lengths in bytes of each value
NULL, // binary? NULL, // binary?
@ -685,7 +731,7 @@ void PostgreSQL::_membersWatcher_RabbitMQ() {
fprintf(stderr, "RABBITMQ ERROR member change: %s\n", e.what()); fprintf(stderr, "RABBITMQ ERROR member change: %s\n", e.what());
} catch(...) { } catch(...) {
fprintf(stderr, "RABBITMQ ERROR member change: unknown error\n"); fprintf(stderr, "RABBITMQ ERROR member change: unknown error\n");
} }
} }
} }
@ -709,12 +755,12 @@ void PostgreSQL::networksDbWatcher()
PQfinish(conn); PQfinish(conn);
conn = NULL; conn = NULL;
} }
if (_run == 1) { if (_run == 1) {
fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str()); fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
exit(8); exit(8);
} }
fprintf(stderr, "Exited membersDbWatcher\n"); fprintf(stderr, "Exited networksDbWatcher\n");
} }
void PostgreSQL::_networksWatcher_Postgres(PGconn *conn) { void PostgreSQL::_networksWatcher_Postgres(PGconn *conn) {
@ -802,18 +848,18 @@ void PostgreSQL::commitThread()
exit(1); exit(1);
} }
json *config = nullptr; std::pair<nlohmann::json,bool> qitem;
while(_commitQueue.get(config)&(_run == 1)) { while(_commitQueue.get(qitem)&(_run == 1)) {
if (!config) { if (!qitem.first.is_object()) {
continue; continue;
} }
if (PQstatus(conn) == CONNECTION_BAD) { if (PQstatus(conn) == CONNECTION_BAD) {
fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn)); fprintf(stderr, "ERROR: Connection to database failed: %s\n", PQerrorMessage(conn));
PQfinish(conn); PQfinish(conn);
delete config;
exit(1); exit(1);
} }
try { try {
nlohmann::json *config = &(qitem.first);
const std::string objtype = (*config)["objtype"]; const std::string objtype = (*config)["objtype"];
if (objtype == "member") { if (objtype == "member") {
try { try {
@ -875,7 +921,7 @@ void PostgreSQL::commitThread()
NULL, NULL,
NULL, NULL,
0); 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK) { if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res)); fprintf(stderr, "ERROR: Error updating member: %s\n", PQresultErrorMessage(res));
fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str()); fprintf(stderr, "%s", OSUtils::jsonDump(*config, 2).c_str());
@ -945,7 +991,7 @@ void PostgreSQL::commitThread()
NULL, NULL,
NULL, NULL,
0); 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK) { if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res)); fprintf(stderr, "ERROR: Error setting IP addresses for member: %s\n", PQresultErrorMessage(res));
PQclear(res); PQclear(res);
@ -968,12 +1014,12 @@ void PostgreSQL::commitThread()
nlohmann::json memOrig; nlohmann::json memOrig;
nlohmann::json memNew(*config); nlohmann::json memNew(*config);
get(nwidInt, nwOrig, memberidInt, memOrig); get(nwidInt, nwOrig, memberidInt, memOrig);
_memberChanged(memOrig, memNew, (this->_ready>=2)); _memberChanged(memOrig, memNew, qitem.second);
} else { } else {
fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %lu-%lu\n", nwidInt, memberidInt); fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", (unsigned long long)nwidInt, (unsigned long long)memberidInt);
} }
} catch (std::exception &e) { } catch (std::exception &e) {
@ -988,7 +1034,10 @@ void PostgreSQL::commitThread()
if (!(*config)["remoteTraceTarget"].is_null()) { if (!(*config)["remoteTraceTarget"].is_null()) {
remoteTraceTarget = (*config)["remoteTraceTarget"]; remoteTraceTarget = (*config)["remoteTraceTarget"];
} }
std::string rulesSource = (*config)["rulesSource"]; std::string rulesSource;
if ((*config)["rulesSource"].is_string()) {
rulesSource = (*config)["rulesSource"];
}
std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1); std::string caps = OSUtils::jsonDump((*config)["capabilitles"], -1);
std::string now = std::to_string(OSUtils::now()); std::string now = std::to_string(OSUtils::now());
std::string mtu = std::to_string((int)(*config)["mtu"]); std::string mtu = std::to_string((int)(*config)["mtu"]);
@ -1020,19 +1069,36 @@ void PostgreSQL::commitThread()
v6mode.c_str(), v6mode.c_str(),
}; };
// This ugly query exists because when we want to mirror networks to/from
// another data store (e.g. FileDB or LFDB) it is possible to get a network
// that doesn't exist in Central's database. This does an upsert and sets
// the owner_id to the "first" global admin in the user DB if the record
// did not previously exist. If the record already exists owner_id is left
// unchanged, so owner_id should be left out of the update clause.
PGresult *res = PQexecParams(conn, PGresult *res = PQexecParams(conn,
"UPDATE ztc_network SET controller_id = $2, capabilities = $3, enable_broadcast = $4, " "INSERT INTO ztc_network (id, creation_time, owner_id, controller_id, capabilities, enable_broadcast, "
"last_updated = $5, mtu = $6, multicast_limit = $7, name = $8, private = $9, " "last_modified, mtu, multicast_limit, name, private, "
"remote_trace_level = $10, remote_trace_target = $11, rules = $12, rules_source = $13, " "remote_trace_level, remote_trace_target, rules, rules_source, "
"tags = $14, v4_assign_mode = $15, v6_assign_mode = $16 " "tags, v4_assign_mode, v6_assign_mode) VALUES ("
"WHERE id = $1", "$1, TO_TIMESTAMP($5::double precision/1000), "
"(SELECT user_id AS owner_id FROM ztc_global_permissions WHERE authorize = true AND del = true AND modify = true AND read = true LIMIT 1),"
"$2, $3, $4, TO_TIMESTAMP($5::double precision/1000), "
"$6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) "
"ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
"capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
"last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
"multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
"private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
"remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
"rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
"v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode",
16, 16,
NULL, NULL,
values, values,
NULL, NULL,
NULL, NULL,
0); 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK) { if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res)); fprintf(stderr, "ERROR: Error updating network record: %s\n", PQresultErrorMessage(res));
PQclear(res); PQclear(res);
@ -1057,7 +1123,7 @@ void PostgreSQL::commitThread()
const char *params[1] = { const char *params[1] = {
id.c_str() id.c_str()
}; };
res = PQexecParams(conn, res = PQexecParams(conn,
"DELETE FROM ztc_network_assignment_pool WHERE network_id = $1", "DELETE FROM ztc_network_assignment_pool WHERE network_id = $1",
1, 1,
NULL, NULL,
@ -1111,7 +1177,7 @@ void PostgreSQL::commitThread()
continue; continue;
} }
res = PQexecParams(conn, res = PQexecParams(conn,
"DELETE FROM ztc_network_route WHERE network_id = $1", "DELETE FROM ztc_network_route WHERE network_id = $1",
1, 1,
NULL, NULL,
@ -1194,16 +1260,14 @@ void PostgreSQL::commitThread()
get(nwidInt, nwOrig); get(nwidInt, nwOrig);
_networkChanged(nwOrig, nwNew, true); _networkChanged(nwOrig, nwNew, qitem.second);
} else { } else {
fprintf(stderr, "Can't notify network changed: %lu\n", nwidInt); fprintf(stderr, "Can't notify network changed: %llu\n", (unsigned long long)nwidInt);
} }
} catch (std::exception &e) { } catch (std::exception &e) {
fprintf(stderr, "ERROR: Error updating member: %s\n", e.what()); fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
} }
} else if (objtype == "trace") {
fprintf(stderr, "ERROR: Trace not yet implemented");
} else if (objtype == "_delete_network") { } else if (objtype == "_delete_network") {
try { try {
std::string networkId = (*config)["nwid"]; std::string networkId = (*config)["nwid"];
@ -1218,7 +1282,7 @@ void PostgreSQL::commitThread()
NULL, NULL,
NULL, NULL,
0); 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK) { if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res)); fprintf(stderr, "ERROR: Error deleting network: %s\n", PQresultErrorMessage(res));
} }
@ -1260,8 +1324,6 @@ void PostgreSQL::commitThread()
} catch (std::exception &e) { } catch (std::exception &e) {
fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what()); fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
} }
delete config;
config = nullptr;
std::this_thread::sleep_for(std::chrono::milliseconds(10)); std::this_thread::sleep_for(std::chrono::milliseconds(10));
} }
@ -1283,9 +1345,9 @@ void PostgreSQL::onlineNotificationThread()
} }
_connected = 1; _connected = 1;
int64_t lastUpdatedNetworkStatus = 0; //int64_t lastUpdatedNetworkStatus = 0;
std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative; std::unordered_map< std::pair<uint64_t,uint64_t>,int64_t,_PairHasher > lastOnlineCumulative;
while (_run == 1) { while (_run == 1) {
if (PQstatus(conn) != CONNECTION_OK) { if (PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres."); fprintf(stderr, "ERROR: Online Notification thread lost connection to Postgres.");
@ -1320,16 +1382,16 @@ void PostgreSQL::onlineNotificationThread()
if (found == _networks.end()) { if (found == _networks.end()) {
continue; // skip members trying to join non-existant networks continue; // skip members trying to join non-existant networks
} }
std::string networkId(nwidTmp); std::string networkId(nwidTmp);
std::string memberId(memTmp); std::string memberId(memTmp);
std::vector<std::string> &members = updateMap[networkId]; std::vector<std::string> &members = updateMap[networkId];
members.push_back(memberId); members.push_back(memberId);
lastOnlineCumulative[i->first] = i->second.first; lastOnlineCumulative[i->first] = i->second.first;
const char *qvals[2] = { const char *qvals[2] = {
networkId.c_str(), networkId.c_str(),
memberId.c_str() memberId.c_str()
@ -1357,7 +1419,7 @@ void PostgreSQL::onlineNotificationThread()
int64_t ts = i->second.first; int64_t ts = i->second.first;
std::string ipAddr = i->second.second.toIpString(ipTmp); std::string ipAddr = i->second.second.toIpString(ipTmp);
std::string timestamp = std::to_string(ts); std::string timestamp = std::to_string(ts);
if (firstRun) { if (firstRun) {
firstRun = false; firstRun = false;
} else { } else {
@ -1389,130 +1451,7 @@ void PostgreSQL::onlineNotificationThread()
PQclear(res); PQclear(res);
} }
const int64_t now = OSUtils::now(); std::this_thread::sleep_for(std::chrono::milliseconds(10));
if ((now - lastUpdatedNetworkStatus) > 10000) {
lastUpdatedNetworkStatus = now;
std::vector<std::pair<uint64_t, std::shared_ptr<_Network>>> networks;
{
std::lock_guard<std::mutex> l(_networks_l);
for (auto i = _networks.begin(); i != _networks.end(); ++i) {
networks.push_back(*i);
}
}
std::stringstream networkUpdate;
networkUpdate << "INSERT INTO ztc_network_status (network_id, bridge_count, authorized_member_count, online_member_count, total_member_count, last_modified) VALUES ";
bool nwFirstRun = true;
bool networkAdded = false;
for (auto i = networks.begin(); i != networks.end(); ++i) {
char tmp[64];
Utils::hex(i->first, tmp);
std::string networkId(tmp);
std::vector<std::string> &_notUsed = updateMap[networkId];
(void)_notUsed;
uint64_t authMemberCount = 0;
uint64_t totalMemberCount = 0;
uint64_t onlineMemberCount = 0;
uint64_t bridgeCount = 0;
uint64_t ts = now;
{
std::lock_guard<std::mutex> l2(i->second->lock);
authMemberCount = i->second->authorizedMembers.size();
totalMemberCount = i->second->members.size();
bridgeCount = i->second->activeBridgeMembers.size();
for (auto m=i->second->members.begin(); m != i->second->members.end(); ++m) {
auto lo = lastOnlineCumulative.find(std::pair<uint64_t,uint64_t>(i->first, m->first));
if (lo != lastOnlineCumulative.end()) {
if ((now - lo->second) <= (ZT_NETWORK_AUTOCONF_DELAY * 2)) {
++onlineMemberCount;
} else {
lastOnlineCumulative.erase(lo);
}
}
}
}
const char *nvals[1] = {
networkId.c_str()
};
res = PQexecParams(conn,
"SELECT id FROM ztc_network WHERE id = $1",
1,
NULL,
nvals,
NULL,
NULL,
0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "Network lookup failed: %s", PQerrorMessage(conn));
PQclear(res);
continue;
}
int nrows = PQntuples(res);
PQclear(res);
if (nrows == 1) {
std::string bc = std::to_string(bridgeCount);
std::string amc = std::to_string(authMemberCount);
std::string omc = std::to_string(onlineMemberCount);
std::string tmc = std::to_string(totalMemberCount);
std::string timestamp = std::to_string(ts);
if (nwFirstRun) {
nwFirstRun = false;
} else {
networkUpdate << ", ";
}
networkUpdate << "('" << networkId << "', " << bc << ", " << amc << ", " << omc << ", " << tmc << ", "
<< "TO_TIMESTAMP(" << timestamp << "::double precision/1000))";
networkAdded = true;
} else if (nrows > 1) {
fprintf(stderr, "Number of networks > 1?!?!?");
continue;
} else {
continue;
}
}
networkUpdate << " ON CONFLICT (network_id) DO UPDATE SET bridge_count = EXCLUDED.bridge_count, "
<< "authorized_member_count = EXCLUDED.authorized_member_count, online_member_count = EXCLUDED.online_member_count, "
<< "total_member_count = EXCLUDED.total_member_count, last_modified = EXCLUDED.last_modified";
if (networkAdded) {
res = PQexec(conn, networkUpdate.str().c_str());
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "Error during multiple network upsert: %s", PQresultErrorMessage(res));
}
PQclear(res);
}
}
// for (auto it = updateMap.begin(); it != updateMap.end(); ++it) {
// std::string networkId = it->first;
// std::vector<std::string> members = it->second;
// std::stringstream queryBuilder;
// std::string membersStr = ::join(members, ",");
// queryBuilder << "NOTIFY controller, '" << networkId << ":" << membersStr << "'";
// std::string query = queryBuilder.str();
// PGresult *res = PQexec(conn,query.c_str());
// if (PQresultStatus(res) != PGRES_COMMAND_OK) {
// fprintf(stderr, "ERROR: Error sending NOTIFY: %s\n", PQresultErrorMessage(res));
// }
// PQclear(res);
// }
std::this_thread::sleep_for(std::chrono::milliseconds(0));
} }
fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str()); fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
PQfinish(conn); PQfinish(conn);
@ -1522,13 +1461,14 @@ void PostgreSQL::onlineNotificationThread()
} }
} }
PGconn *PostgreSQL::getPgConn(OverrideMode m) { PGconn *PostgreSQL::getPgConn(OverrideMode m)
{
if (m == ALLOW_PGBOUNCER_OVERRIDE) { if (m == ALLOW_PGBOUNCER_OVERRIDE) {
char *connStr = getenv("PGBOUNCER_CONNSTR"); char *connStr = getenv("PGBOUNCER_CONNSTR");
if (connStr != NULL) { if (connStr != NULL) {
fprintf(stderr, "PGBouncer Override\n"); fprintf(stderr, "PGBouncer Override\n");
std::string conn(connStr); std::string conn(connStr);
conn += " application_name=controller-"; conn += " application_name=controller-";
conn += _myAddressStr.c_str(); conn += _myAddressStr.c_str();
return PQconnectdb(conn.c_str()); return PQconnectdb(conn.c_str());
} }
@ -1536,4 +1476,5 @@ PGconn *PostgreSQL::getPgConn(OverrideMode m) {
return PQconnectdb(_connString.c_str()); return PQconnectdb(_connString.c_str());
} }
#endif //ZT_CONTROLLER_USE_LIBPQ #endif //ZT_CONTROLLER_USE_LIBPQ

127
controller/PostgreSQL.hpp

@ -1,44 +1,30 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#include "DB.hpp"
#ifdef ZT_CONTROLLER_USE_LIBPQ #ifdef ZT_CONTROLLER_USE_LIBPQ
#ifndef ZT_CONTROLLER_LIBPQ_HPP #ifndef ZT_CONTROLLER_LIBPQ_HPP
#define ZT_CONTROLLER_LIBPQ_HPP #define ZT_CONTROLLER_LIBPQ_HPP
#include "DB.hpp"
#define ZT_CENTRAL_CONTROLLER_COMMIT_THREADS 4 #define ZT_CENTRAL_CONTROLLER_COMMIT_THREADS 4
extern "C" { extern "C" {
typedef struct pg_conn PGconn; typedef struct pg_conn PGconn;
} }
namespace ZeroTier namespace ZeroTier {
{
struct MQConfig; struct MQConfig;
@ -51,69 +37,70 @@ struct MQConfig;
class PostgreSQL : public DB class PostgreSQL : public DB
{ {
public: public:
PostgreSQL(EmbeddedNetworkController *const nc, const Identity &myId, const char *path, int listenPort, MQConfig *mqc = NULL); PostgreSQL(const Identity &myId, const char *path, int listenPort, MQConfig *mqc = NULL);
virtual ~PostgreSQL(); virtual ~PostgreSQL();
virtual bool waitForReady(); virtual bool waitForReady();
virtual bool isReady(); virtual bool isReady();
virtual void save(nlohmann::json *orig, nlohmann::json &record); virtual bool save(nlohmann::json &record,bool notifyListeners);
virtual void eraseNetwork(const uint64_t networkId); virtual void eraseNetwork(const uint64_t networkId);
virtual void eraseMember(const uint64_t networkId, const uint64_t memberId); virtual void eraseMember(const uint64_t networkId, const uint64_t memberId);
virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress); virtual void nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress);
protected: protected:
struct _PairHasher struct _PairHasher
{ {
inline std::size_t operator()(const std::pair<uint64_t,uint64_t> &p) const { return (std::size_t)(p.first ^ p.second); } inline std::size_t operator()(const std::pair<uint64_t,uint64_t> &p) const { return (std::size_t)(p.first ^ p.second); }
}; };
private: private:
void initializeNetworks(PGconn *conn); void initializeNetworks(PGconn *conn);
void initializeMembers(PGconn *conn); void initializeMembers(PGconn *conn);
void heartbeat(); void heartbeat();
void membersDbWatcher(); void membersDbWatcher();
void _membersWatcher_Postgres(PGconn *conn); void _membersWatcher_Postgres(PGconn *conn);
void _membersWatcher_RabbitMQ(); void _membersWatcher_RabbitMQ();
void networksDbWatcher(); void networksDbWatcher();
void _networksWatcher_Postgres(PGconn *conn); void _networksWatcher_Postgres(PGconn *conn);
void _networksWatcher_RabbitMQ(); void _networksWatcher_RabbitMQ();
void commitThread();
void commitThread(); void onlineNotificationThread();
void onlineNotificationThread();
enum OverrideMode {
enum OverrideMode { ALLOW_PGBOUNCER_OVERRIDE = 0,
ALLOW_PGBOUNCER_OVERRIDE = 0, NO_OVERRIDE = 1
NO_OVERRIDE = 1 };
};
PGconn * getPgConn( OverrideMode m = ALLOW_PGBOUNCER_OVERRIDE );
std::string _connString; PGconn * getPgConn( OverrideMode m = ALLOW_PGBOUNCER_OVERRIDE );
BlockingQueue<nlohmann::json *> _commitQueue; const Identity _myId;
const Address _myAddress;
std::string _myAddressStr;
std::string _connString;
BlockingQueue< std::pair<nlohmann::json,bool> > _commitQueue;
std::thread _heartbeatThread; std::thread _heartbeatThread;
std::thread _membersDbWatcher; std::thread _membersDbWatcher;
std::thread _networksDbWatcher; std::thread _networksDbWatcher;
std::thread _commitThread[ZT_CENTRAL_CONTROLLER_COMMIT_THREADS]; std::thread _commitThread[ZT_CENTRAL_CONTROLLER_COMMIT_THREADS];
std::thread _onlineNotificationThread; std::thread _onlineNotificationThread;
std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > _lastOnline; std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > _lastOnline;
mutable std::mutex _lastOnline_l; mutable std::mutex _lastOnline_l;
mutable std::mutex _readyLock; mutable std::mutex _readyLock;
std::atomic<int> _ready, _connected, _run; std::atomic<int> _ready, _connected, _run;
mutable volatile bool _waitNoticePrinted; mutable volatile bool _waitNoticePrinted;
int _listenPort; int _listenPort;
MQConfig *_mqc; MQConfig *_mqc;
}; };
} } // namespace ZeroTier
#endif // ZT_CONTROLLER_LIBPQ_HPP #endif // ZT_CONTROLLER_LIBPQ_HPP
#endif // ZT_CONTROLLER_USE_LIBPQ #endif // ZT_CONTROLLER_USE_LIBPQ

1
controller/README.md

@ -92,7 +92,6 @@ Example:
| v6AssignMode | object | IPv6 management and assign options (see below) | YES | | v6AssignMode | object | IPv6 management and assign options (see below) | YES |
| mtu | integer | Network MTU (default: 2800) | YES | | mtu | integer | Network MTU (default: 2800) | YES |
| multicastLimit | integer | Maximum recipients for a multicast packet | YES | | multicastLimit | integer | Maximum recipients for a multicast packet | YES |
| creationTime | integer | Time network was first created | no |
| revision | integer | Network config revision counter | no | | revision | integer | Network config revision counter | no |
| routes | array[object] | Managed IPv4 and IPv6 routes; see below | YES | | routes | array[object] | Managed IPv4 and IPv6 routes; see below | YES |
| ipAssignmentPools | array[object] | IP auto-assign ranges; see below | YES | | ipAssignmentPools | array[object] | IP auto-assign ranges; see below | YES |

161
controller/RabbitMQ.cpp

@ -1,3 +1,16 @@
/*
* Copyright (c)2019 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2023-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "RabbitMQ.hpp" #include "RabbitMQ.hpp"
#ifdef ZT_CONTROLLER_USE_LIBPQ #ifdef ZT_CONTROLLER_USE_LIBPQ
@ -11,95 +24,95 @@ namespace ZeroTier
{ {
RabbitMQ::RabbitMQ(MQConfig *cfg, const char *queueName) RabbitMQ::RabbitMQ(MQConfig *cfg, const char *queueName)
: _mqc(cfg) : _mqc(cfg)
, _qName(queueName) , _qName(queueName)
, _socket(NULL) , _socket(NULL)
, _status(0) , _status(0)
{ {
} }
RabbitMQ::~RabbitMQ() RabbitMQ::~RabbitMQ()
{ {
amqp_channel_close(_conn, _channel, AMQP_REPLY_SUCCESS); amqp_channel_close(_conn, _channel, AMQP_REPLY_SUCCESS);
amqp_connection_close(_conn, AMQP_REPLY_SUCCESS); amqp_connection_close(_conn, AMQP_REPLY_SUCCESS);
amqp_destroy_connection(_conn); amqp_destroy_connection(_conn);
} }
void RabbitMQ::init() void RabbitMQ::init()
{ {
struct timeval tval; struct timeval tval;
memset(&tval, 0, sizeof(struct timeval)); memset(&tval, 0, sizeof(struct timeval));
tval.tv_sec = 5; tval.tv_sec = 5;
fprintf(stderr, "Initializing RabbitMQ %s\n", _qName); fprintf(stderr, "Initializing RabbitMQ %s\n", _qName);
_conn = amqp_new_connection(); _conn = amqp_new_connection();
_socket = amqp_tcp_socket_new(_conn); _socket = amqp_tcp_socket_new(_conn);
if (!_socket) { if (!_socket) {
throw std::runtime_error("Can't create socket for RabbitMQ"); throw std::runtime_error("Can't create socket for RabbitMQ");
} }
_status = amqp_socket_open_noblock(_socket, _mqc->host, _mqc->port, &tval); _status = amqp_socket_open_noblock(_socket, _mqc->host.c_str(), _mqc->port, &tval);
if (_status) { if (_status) {
throw std::runtime_error("Can't connect to RabbitMQ"); throw std::runtime_error("Can't connect to RabbitMQ");
} }
amqp_rpc_reply_t r = amqp_login(_conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, amqp_rpc_reply_t r = amqp_login(_conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN,
_mqc->username, _mqc->password); _mqc->username.c_str(), _mqc->password.c_str());
if (r.reply_type != AMQP_RESPONSE_NORMAL) { if (r.reply_type != AMQP_RESPONSE_NORMAL) {
throw std::runtime_error("RabbitMQ Login Error"); throw std::runtime_error("RabbitMQ Login Error");
} }
static int chan = 0; static int chan = 0;
{ {
Mutex::Lock l(_chan_m); Mutex::Lock l(_chan_m);
_channel = ++chan; _channel = ++chan;
} }
amqp_channel_open(_conn, _channel); amqp_channel_open(_conn, _channel);
r = amqp_get_rpc_reply(_conn); r = amqp_get_rpc_reply(_conn);
if(r.reply_type != AMQP_RESPONSE_NORMAL) { if(r.reply_type != AMQP_RESPONSE_NORMAL) {
throw std::runtime_error("Error opening communication channel"); throw std::runtime_error("Error opening communication channel");
} }
_q = amqp_queue_declare(_conn, _channel, amqp_cstring_bytes(_qName), 0, 0, 0, 0, amqp_empty_table); _q = amqp_queue_declare(_conn, _channel, amqp_cstring_bytes(_qName), 0, 0, 0, 0, amqp_empty_table);
r = amqp_get_rpc_reply(_conn); r = amqp_get_rpc_reply(_conn);
if (r.reply_type != AMQP_RESPONSE_NORMAL) { if (r.reply_type != AMQP_RESPONSE_NORMAL) {
throw std::runtime_error("Error declaring queue " + std::string(_qName)); throw std::runtime_error("Error declaring queue " + std::string(_qName));
} }
amqp_basic_consume(_conn, _channel, amqp_cstring_bytes(_qName), amqp_empty_bytes, 0, 1, 0, amqp_empty_table); amqp_basic_consume(_conn, _channel, amqp_cstring_bytes(_qName), amqp_empty_bytes, 0, 1, 0, amqp_empty_table);
r = amqp_get_rpc_reply(_conn); r = amqp_get_rpc_reply(_conn);
if (r.reply_type != AMQP_RESPONSE_NORMAL) { if (r.reply_type != AMQP_RESPONSE_NORMAL) {
throw std::runtime_error("Error consuming queue " + std::string(_qName)); throw std::runtime_error("Error consuming queue " + std::string(_qName));
} }
fprintf(stderr, "RabbitMQ Init OK %s\n", _qName); fprintf(stderr, "RabbitMQ Init OK %s\n", _qName);
} }
std::string RabbitMQ::consume() std::string RabbitMQ::consume()
{ {
amqp_rpc_reply_t res; amqp_rpc_reply_t res;
amqp_envelope_t envelope; amqp_envelope_t envelope;
amqp_maybe_release_buffers(_conn); amqp_maybe_release_buffers(_conn);
struct timeval timeout; struct timeval timeout;
timeout.tv_sec = 1; timeout.tv_sec = 1;
timeout.tv_usec = 0; timeout.tv_usec = 0;
res = amqp_consume_message(_conn, &envelope, &timeout, 0); res = amqp_consume_message(_conn, &envelope, &timeout, 0);
if (res.reply_type != AMQP_RESPONSE_NORMAL) { if (res.reply_type != AMQP_RESPONSE_NORMAL) {
if (res.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION && res.library_error == AMQP_STATUS_TIMEOUT) { if (res.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION && res.library_error == AMQP_STATUS_TIMEOUT) {
// timeout waiting for message. Return empty string // timeout waiting for message. Return empty string
return ""; return "";
} else { } else {
throw std::runtime_error("Error getting message"); throw std::runtime_error("Error getting message");
} }
} }
std::string msg( std::string msg(
(const char*)envelope.message.body.bytes, (const char*)envelope.message.body.bytes,
envelope.message.body.len envelope.message.body.len
); );
amqp_destroy_envelope(&envelope); amqp_destroy_envelope(&envelope);
return msg; return msg;
} }
} }

64
controller/RabbitMQ.hpp

@ -1,38 +1,29 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_CONTROLLER_RABBITMQ_HPP #ifndef ZT_CONTROLLER_RABBITMQ_HPP
#define ZT_CONTROLLER_RABBITMQ_HPP #define ZT_CONTROLLER_RABBITMQ_HPP
#include "DB.hpp"
#include <string>
namespace ZeroTier namespace ZeroTier
{ {
struct MQConfig { struct MQConfig {
const char *host; std::string host;
int port; int port;
const char *username; std::string username;
const char *password; std::string password;
}; };
} }
@ -42,33 +33,32 @@ struct MQConfig {
#include <amqp.h> #include <amqp.h>
#include <amqp_tcp_socket.h> #include <amqp_tcp_socket.h>
#include <string>
namespace ZeroTier namespace ZeroTier
{ {
class RabbitMQ { class RabbitMQ {
public: public:
RabbitMQ(MQConfig *cfg, const char *queueName); RabbitMQ(MQConfig *cfg, const char *queueName);
~RabbitMQ(); ~RabbitMQ();
void init(); void init();
std::string consume(); std::string consume();
private: private:
MQConfig *_mqc; MQConfig *_mqc;
const char *_qName; const char *_qName;
amqp_socket_t *_socket; amqp_socket_t *_socket;
amqp_connection_state_t _conn; amqp_connection_state_t _conn;
amqp_queue_declare_ok_t *_q; amqp_queue_declare_ok_t *_q;
int _status; int _status;
int _channel; int _channel;
Mutex _chan_m; Mutex _chan_m;
}; };
} }

36
debian/changelog vendored

@ -1,3 +1,39 @@
zerotier-one (1.4.6) unstable; urgency=medium
* Update default root server list
* Fix build flags on "armhf" (32-bit ARM) platforms for better
compatibility with Pi Zero and other devices.
* Fix license text in one.cpp.
* Add a clarification to LICENSE.txt.
-- Adam Ierymenko <adam.ierymenko@zerotier.com> Fri, 30 Aug 2019 01:00:00 -0700
zerotier-one (1.4.4) unstable; urgency=medium
* See https://github.com/zerotier/ZeroTierOne for release notes.
* License changed to BSL 1.1
-- Adam Ierymenko <adam.ierymenko@zerotier.com> Fri, 23 Aug 2019 01:00:00 -0700
zerotier-one (1.4.2-2) unstable; urgency=medium
* See https://github.com/zerotier/ZeroTierOne for release notes.
* This is a new build that fixes a binary build issue with containers and SELinux
-- Adam Ierymenko <adam.ierymenko@zerotier.com> Thu, 04 Aug 2019 01:00:00 -0700
zerotier-one (1.4.2) unstable; urgency=medium
* See https://github.com/zerotier/ZeroTierOne for release notes.
-- Adam Ierymenko <adam.ierymenko@zerotier.com> Thu, 04 Aug 2019 01:00:00 -0700
zerotier-one (1.4.0) unstable; urgency=medium
* See https://github.com/zerotier/ZeroTierOne for release notes.
-- Adam Ierymenko <adam.ierymenko@zerotier.com> Thu, 29 Jul 2019 01:00:00 -0700
zerotier-one (1.2.12) unstable; urgency=medium zerotier-one (1.2.12) unstable; urgency=medium
* See https://github.com/zerotier/ZeroTierOne for release notes. * See https://github.com/zerotier/ZeroTierOne for release notes.

28
debian/copyright vendored

@ -4,21 +4,15 @@ Source: https://github.com/zerotier/ZeroTierOne
Files: * Files: *
Copyright: 2011-2016 ZeroTier, Inc. Copyright: 2011-2016 ZeroTier, Inc.
License: GPL-3.0+ License: ZeroTier BSL 1.1
License: GPL-3.0+ License: ZeroTier BSL 1.1
This program is free software: you can redistribute it and/or modify Copyright (c)2019 ZeroTier, Inc.
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or Use of this software is governed by the Business Source License included
(at your option) any later version. in the LICENSE.TXT file in the project's root directory.
.
This package is distributed in the hope that it will be useful, Change Date: 2023-01-01
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the On the date above, in accordance with the Business Source License, use
GNU General Public License for more details. of this software will be governed by version 2.0 of the Apache License.
.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
.
On Debian systems, the complete text of the GNU General
Public License version 3 can be found in "/usr/share/common-licenses/GPL-3".

19
docker/Dockerfile

@ -1,19 +0,0 @@
# Dockerfile for ZeroTier Central Controllers
FROM centos:7
MAINTAINER Adam Ierymekno <adam.ierymenko@zerotier.com>, Grant Limberg <grant.limberg@zerotier.com>
RUN yum update -y
RUN yum install -y https://download.postgresql.org/pub/repos/yum/10/redhat/rhel-7-x86_64/pgdg-centos10-10-2.noarch.rpm
RUN yum install -y postgresql10 libpqxx-devel
RUN yum -y install epel-release && yum -y update && yum clean all
RUN yum -y install clang jemalloc jemalloc-devel
ADD zerotier-one /usr/local/bin/zerotier-one
RUN chmod a+x /usr/local/bin/zerotier-one
ADD docker/main.sh /
RUN chmod a+x /main.sh
ENTRYPOINT /main.sh

36
ext/bin/tap-mac/tap.kext/Contents/Info.plist

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>tap</string>
<key>CFBundleIdentifier</key>
<string>com.zerotier.tap</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>tap</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>20150118</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>OSBundleLibraries</key>
<dict>
<key>com.apple.kpi.mach</key>
<string>8.0</string>
<key>com.apple.kpi.bsd</key>
<string>8.0</string>
<key>com.apple.kpi.libkern</key>
<string>8.0</string>
<key>com.apple.kpi.unsupported</key>
<string>8.0</string>
</dict>
</dict>
</plist>

BIN
ext/bin/tap-mac/tap.kext/Contents/MacOS/tap

Binary file not shown.

105
ext/bin/tap-mac/tap.kext/Contents/_CodeSignature/CodeResources

@ -0,0 +1,105 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>files</key>
<dict/>
<key>files2</key>
<dict/>
<key>rules</key>
<dict>
<key>^Resources/</key>
<true/>
<key>^Resources/.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^Resources/.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^version.plist$</key>
<true/>
</dict>
<key>rules2</key>
<dict>
<key>.*\.dSYM($|/)</key>
<dict>
<key>weight</key>
<real>11</real>
</dict>
<key>^(.*/)?\.DS_Store$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>2000</real>
</dict>
<key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^.*</key>
<true/>
<key>^Info\.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^PkgInfo$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^Resources/</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^Resources/.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^Resources/.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^[^/]+$</key>
<dict>
<key>nested</key>
<true/>
<key>weight</key>
<real>10</real>
</dict>
<key>^embedded\.provisionprofile$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^version\.plist$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
</dict>
</dict>
</plist>

26
ext/central-controller-docker/Dockerfile

@ -0,0 +1,26 @@
# Dockerfile for ZeroTier Central Controllers
FROM centos:7 as builder
MAINTAINER Adam Ierymekno <adam.ierymenko@zerotier.com>, Grant Limberg <grant.limberg@zerotier.com>
ARG git_branch=master
RUN yum update -y
RUN yum install -y https://download.postgresql.org/pub/repos/yum/10/redhat/rhel-7-x86_64/pgdg-centos10-10-2.noarch.rpm
RUN yum -y install epel-release && yum -y update && yum clean all
RUN yum groupinstall -y "Development Tools"
RUN yum install -y bash postgresql10 postgresql10-devel libpqxx-devel glibc-static libstdc++-static clang jemalloc jemalloc-devel
RUN git clone http://git.int.zerotier.com/zerotier/ZeroTierOne.git
RUN if [ "$git_branch" != "master" ]; then cd ZeroTierOne && git checkout -b $git_branch origin/$git_branch; fi
RUN ldconfig
RUN cd ZeroTierOne && make central-controller
FROM centos:7
COPY --from=builder /ZeroTierOne/zerotier-one /usr/local/bin/zerotier-one
RUN chmod a+x /usr/local/bin/zerotier-one
ADD ext/central-controller-docker/main.sh /
RUN chmod a+x /main.sh
ENTRYPOINT /main.sh

3
ext/central-controller-docker/README.md

@ -0,0 +1,3 @@
# ZeroTier Central Controller Docker Image
Dockerfile & startup script for use with [ZeroTier Central](https://my.zerotier.com). Not intended for public use.

2
docker/main.sh → ext/central-controller-docker/main.sh

@ -1,4 +1,4 @@
#!/usr/bin/env bash #!/bin/bash
if [ -z "$ZT_IDENTITY_PATH" ]; then if [ -z "$ZT_IDENTITY_PATH" ]; then
echo '*** FAILED: ZT_IDENTITY_PATH environment variable is not defined' echo '*** FAILED: ZT_IDENTITY_PATH environment variable is not defined'

22
ext/cpp-httplib/LICENSE

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2017 yhirose
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.

259
ext/cpp-httplib/README.md

@ -0,0 +1,259 @@
cpp-httplib
===========
[![Build Status](https://travis-ci.org/yhirose/cpp-httplib.svg?branch=master)](https://travis-ci.org/yhirose/cpp-httplib)
[![Bulid Status](https://ci.appveyor.com/api/projects/status/github/yhirose/cpp-httplib?branch=master&svg=true)](https://ci.appveyor.com/project/yhirose/cpp-httplib)
A C++ header-only cross platform HTTP/HTTPS library.
It's extremely easy to setup. Just include **httplib.h** file in your code!
Inspired by [Sinatra](http://www.sinatrarb.com/) and [express](https://github.com/visionmedia/express).
Server Example
--------------
```c++
#include <httplib.h>
int main(void)
{
using namespace httplib;
Server svr;
svr.Get("/hi", [](const Request& req, Response& res) {
res.set_content("Hello World!", "text/plain");
});
svr.Get(R"(/numbers/(\d+))", [&](const Request& req, Response& res) {
auto numbers = req.matches[1];
res.set_content(numbers, "text/plain");
});
svr.listen("localhost", 1234);
}
```
`Post`, `Put`, `Delete` and `Options` methods are also supported.
### Bind a socket to multiple interfaces and any available port
```cpp
int port = svr.bind_to_any_port("0.0.0.0");
svr.listen_after_bind();
```
### Method Chain
```cpp
svr.Get("/get", [](const auto& req, auto& res) {
res.set_content("get", "text/plain");
})
.Post("/post", [](const auto& req, auto& res) {
res.set_content(req.body(), "text/plain");
})
.listen("localhost", 1234);
```
### Static File Server
```cpp
svr.set_base_dir("./www");
```
### Logging
```cpp
svr.set_logger([](const auto& req, const auto& res) {
your_logger(req, res);
});
```
### Error Handler
```cpp
svr.set_error_handler([](const auto& req, auto& res) {
const char* fmt = "<p>Error Status: <span style='color:red;'>%d</span></p>";
char buf[BUFSIZ];
snprintf(buf, sizeof(buf), fmt, res.status);
res.set_content(buf, "text/html");
});
```
### 'multipart/form-data' POST data
```cpp
svr.Post("/multipart", [&](const auto& req, auto& res) {
auto size = req.files.size();
auto ret = req.has_file("name1"));
const auto& file = req.get_file_value("name1");
// file.filename;
// file.content_type;
auto body = req.body.substr(file.offset, file.length));
})
```
Client Example
--------------
### GET
```c++
#include <httplib.h>
#include <iostream>
int main(void)
{
httplib::Client cli("localhost", 1234);
auto res = cli.Get("/hi");
if (res && res->status == 200) {
std::cout << res->body << std::endl;
}
}
```
### GET with Content Receiver
```c++
std::string body;
auto res = cli.Get("/large-data", [&](const char *data, size_t len) {
body.append(data, len);
});
assert(res->body.empty());
```
### POST
```c++
res = cli.Post("/post", "text", "text/plain");
res = cli.Post("/person", "name=john1&note=coder", "application/x-www-form-urlencoded");
```
### POST with parameters
```c++
httplib::Params params;
params.emplace("name", "john");
params.emplace("note", "coder");
auto res = cli.Post("/post", params);
```
or
```c++
httplib::Params params{
{ "name", "john" },
{ "note", "coder" }
};
auto res = cli.Post("/post", params);
```
### PUT
```c++
res = cli.Put("/resource/foo", "text", "text/plain");
```
### DELETE
```c++
res = cli.Delete("/resource/foo");
```
### OPTIONS
```c++
res = cli.Options("*");
res = cli.Options("/resource/foo");
```
### Connection Timeout
```c++
httplib::Client cli("localhost", 8080, 5); // timeouts in 5 seconds
```
### With Progress Callback
```cpp
httplib::Client client(url, port);
// prints: 0 / 000 bytes => 50% complete
std::shared_ptr<httplib::Response> res =
cli.Get("/", [](uint64_t len, uint64_t total) {
printf("%lld / %lld bytes => %d%% complete\n",
len, total,
(int)((len/total)*100));
return true; // return 'false' if you want to cancel the request.
}
);
```
![progress](https://user-images.githubusercontent.com/236374/33138910-495c4ecc-cf86-11e7-8693-2fc6d09615c4.gif)
This feature was contributed by [underscorediscovery](https://github.com/yhirose/cpp-httplib/pull/23).
### Basic Authentication
```cpp
httplib::Client cli("httplib.org");
auto res = cli.Get("/basic-auth/hello/world", {
httplib::make_basic_authentication_header("hello", "world")
});
// res->status should be 200
// res->body should be "{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n".
```
### Range
```cpp
httplib::Client cli("httpbin.org");
auto res = cli.Get("/range/32", {
httplib::make_range_header(1, 10) // 'Range: bytes=1-10'
});
// res->status should be 206.
// res->body should be "bcdefghijk".
```
OpenSSL Support
---------------
SSL support is available with `CPPHTTPLIB_OPENSSL_SUPPORT`. `libssl` and `libcrypto` should be linked.
```c++
#define CPPHTTPLIB_OPENSSL_SUPPORT
SSLServer svr("./cert.pem", "./key.pem");
SSLClient cli("localhost", 8080);
cli.set_ca_cert_path("./ca-bundle.crt");
cli.enable_server_certificate_verification(true);
```
Zlib Support
------------
'gzip' compression is available with `CPPHTTPLIB_ZLIB_SUPPORT`.
The server applies gzip compression to the following MIME type contents:
* all text types
* image/svg+xml
* application/javascript
* application/json
* application/xml
* application/xhtml+xml
NOTE
----
g++ 4.8 cannot build this library since `<regex>` in g++4.8 is [broken](https://stackoverflow.com/questions/12530406/is-gcc-4-8-or-earlier-buggy-about-regular-expressions).
License
-------
MIT license (© 2019 Yuji Hirose)

2779
ext/cpp-httplib/httplib.h

File diff suppressed because it is too large Load Diff

30
ext/installfiles/linux/zerotier-containerized/Dockerfile

@ -1,30 +1,28 @@
FROM debian:stretch as builder ## NOTE: to retain configuration; mount a Docker volume, or use a bind-mount, on /var/lib/zerotier-one
FROM debian:buster-slim as builder
## Supports x86_64, x86, arm, and arm64 ## Supports x86_64, x86, arm, and arm64
RUN apt-get update && apt-get install -y curl gnupg RUN apt-get update && apt-get install -y curl gnupg
RUN apt-key adv --keyserver ha.pool.sks-keyservers.net --recv-keys 0x1657198823e52a61 && \ RUN apt-key adv --keyserver ha.pool.sks-keyservers.net --recv-keys 0x1657198823e52a61 && \
echo "deb http://download.zerotier.com/debian/stretch stretch main" > /etc/apt/sources.list.d/zerotier.list echo "deb http://download.zerotier.com/debian/buster buster main" > /etc/apt/sources.list.d/zerotier.list
RUN apt-get update && apt-get install -y zerotier-one=1.2.12 RUN apt-get update && apt-get install -y zerotier-one=1.4.4
COPY ext/installfiles/linux/zerotier-containerized/main.sh /var/lib/zerotier-one/main.sh
FROM alpine:latest
MAINTAINER Adam Ierymenko <adam.ierymenko@zerotier.com>
LABEL version="1.2.12" FROM debian:buster-slim
LABEL version="1.4.4"
LABEL description="Containerized ZeroTier One for use on CoreOS or other Docker-only Linux hosts." LABEL description="Containerized ZeroTier One for use on CoreOS or other Docker-only Linux hosts."
# Uncomment to build in container # ZeroTier relies on UDP port 9993
#RUN apk add --update alpine-sdk linux-headers EXPOSE 9993/udp
RUN apk add --update libgcc libstdc++
RUN mkdir -p /var/lib/zerotier-one RUN mkdir -p /var/lib/zerotier-one
COPY --from=builder /usr/sbin/zerotier-cli /usr/sbin/zerotier-cli
COPY --from=builder /var/lib/zerotier-one/zerotier-cli /usr/sbin/zerotier-cli COPY --from=builder /usr/sbin/zerotier-idtool /usr/sbin/zerotier-idtool
COPY --from=builder /var/lib/zerotier-one/zerotier-idtool /usr/sbin/zerotier-idtool
COPY --from=builder /usr/sbin/zerotier-one /usr/sbin/zerotier-one COPY --from=builder /usr/sbin/zerotier-one /usr/sbin/zerotier-one
COPY --from=builder /var/lib/zerotier-one/main.sh /main.sh
ADD main.sh /
RUN chmod 0755 /main.sh RUN chmod 0755 /main.sh
ENTRYPOINT ["/main.sh"] ENTRYPOINT ["/main.sh"]
CMD ["zerotier-one"] CMD ["zerotier-one"]

1505
ext/installfiles/mac/ZeroTier One.pkgproj

File diff suppressed because it is too large Load Diff

9
ext/installfiles/mac/postinst.sh

@ -3,6 +3,7 @@
export PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin export PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin
OSX_RELEASE=`sw_vers -productVersion | cut -d . -f 1,2` OSX_RELEASE=`sw_vers -productVersion | cut -d . -f 1,2`
DARWIN_MAJOR=`uname -r | cut -d . -f 1`
launchctl unload /Library/LaunchDaemons/com.zerotier.one.plist >>/dev/null 2>&1 launchctl unload /Library/LaunchDaemons/com.zerotier.one.plist >>/dev/null 2>&1
sleep 0.5 sleep 0.5
@ -43,9 +44,11 @@ rm -f zerotier-cli zerotier-idtool
ln -sf "/Library/Application Support/ZeroTier/One/zerotier-one" zerotier-cli ln -sf "/Library/Application Support/ZeroTier/One/zerotier-one" zerotier-cli
ln -sf "/Library/Application Support/ZeroTier/One/zerotier-one" zerotier-idtool ln -sf "/Library/Application Support/ZeroTier/One/zerotier-one" zerotier-idtool
cd "/Library/Application Support/ZeroTier/One" if [ $DARWIN_MAJOR -le 16 ]; then
kextload -r . tap.kext >>/dev/null 2>&1 & cd "/Library/Application Support/ZeroTier/One"
disown %1 kextload -r . tap.kext >>/dev/null 2>&1 &
disown %1
fi
launchctl load /Library/LaunchDaemons/com.zerotier.one.plist >>/dev/null 2>&1 launchctl load /Library/LaunchDaemons/com.zerotier.one.plist >>/dev/null 2>&1

10
ext/installfiles/windows/ZeroTier One.aip

@ -27,10 +27,10 @@
<ROW Property="CTRLS" Value="2"/> <ROW Property="CTRLS" Value="2"/>
<ROW Property="MSIFASTINSTALL" MultiBuildValue="DefaultBuild:2"/> <ROW Property="MSIFASTINSTALL" MultiBuildValue="DefaultBuild:2"/>
<ROW Property="Manufacturer" Value="ZeroTier, Inc."/> <ROW Property="Manufacturer" Value="ZeroTier, Inc."/>
<ROW Property="ProductCode" Value="1033:{855E8629-580C-4BDF-8B59-B9290C7E7BA5} " Type="16"/> <ROW Property="ProductCode" Value="1033:{80CEE5C9-4DF0-43F5-B232-484D6455978E} " Type="16"/>
<ROW Property="ProductLanguage" Value="1033"/> <ROW Property="ProductLanguage" Value="1033"/>
<ROW Property="ProductName" Value="ZeroTier One"/> <ROW Property="ProductName" Value="ZeroTier One"/>
<ROW Property="ProductVersion" Value="1.2.12" Type="32"/> <ROW Property="ProductVersion" Value="1.4.6" Type="32"/>
<ROW Property="REBOOT" MultiBuildValue="DefaultBuild:ReallySuppress"/> <ROW Property="REBOOT" MultiBuildValue="DefaultBuild:ReallySuppress"/>
<ROW Property="RUNAPPLICATION" Value="1" Type="4"/> <ROW Property="RUNAPPLICATION" Value="1" Type="4"/>
<ROW Property="SecureCustomProperties" Value="OLDPRODUCTS;AI_NEWERPRODUCTFOUND;AI_SETUPEXEPATH;SETUPEXEDIR"/> <ROW Property="SecureCustomProperties" Value="OLDPRODUCTS;AI_NEWERPRODUCTFOUND;AI_SETUPEXEPATH;SETUPEXEDIR"/>
@ -64,7 +64,7 @@
<ROW Directory="x86_Dir" Directory_Parent="tapwindows_Dir" DefaultDir="x86"/> <ROW Directory="x86_Dir" Directory_Parent="tapwindows_Dir" DefaultDir="x86"/>
</COMPONENT> </COMPONENT>
<COMPONENT cid="caphyon.advinst.msicomp.MsiCompsComponent"> <COMPONENT cid="caphyon.advinst.msicomp.MsiCompsComponent">
<ROW Component="AI_CustomARPName" ComponentId="{92D9A995-E340-41B2-98F5-F2DB3F6E8AD8}" Directory_="APPDIR" Attributes="4" KeyPath="DisplayName" Options="1"/> <ROW Component="AI_CustomARPName" ComponentId="{717E3B00-472C-4E07-BC45-AF83F5442898}" Directory_="APPDIR" Attributes="4" KeyPath="DisplayName" Options="1"/>
<ROW Component="AI_DisableModify" ComponentId="{020DCABD-5D56-49B9-AF48-F07F0B55E590}" Directory_="APPDIR" Attributes="4" KeyPath="NoModify" Options="1"/> <ROW Component="AI_DisableModify" ComponentId="{020DCABD-5D56-49B9-AF48-F07F0B55E590}" Directory_="APPDIR" Attributes="4" KeyPath="NoModify" Options="1"/>
<ROW Component="AI_ExePath" ComponentId="{8E02B36C-7A19-429B-A93E-77A9261AC918}" Directory_="APPDIR" Attributes="4" KeyPath="AI_ExePath"/> <ROW Component="AI_ExePath" ComponentId="{8E02B36C-7A19-429B-A93E-77A9261AC918}" Directory_="APPDIR" Attributes="4" KeyPath="AI_ExePath"/>
<ROW Component="Hardcodet.Wpf.TaskbarNotification.dll" ComponentId="{BEA825AF-2555-44AF-BE40-47FFC16DCBA6}" Directory_="APPDIR" Attributes="0" KeyPath="Hardcodet.Wpf.TaskbarNotification.dll"/> <ROW Component="Hardcodet.Wpf.TaskbarNotification.dll" ComponentId="{BEA825AF-2555-44AF-BE40-47FFC16DCBA6}" Directory_="APPDIR" Attributes="0" KeyPath="Hardcodet.Wpf.TaskbarNotification.dll"/>
@ -454,10 +454,10 @@
<ROW XmlAttribute="xsischemaLocation" XmlElement="swidsoftware_identification_tag" Name="xsi:schemaLocation" Flags="14" Order="3" Value="http://standards.iso.org/iso/19770/-2/2008/schema.xsd software_identification_tag.xsd"/> <ROW XmlAttribute="xsischemaLocation" XmlElement="swidsoftware_identification_tag" Name="xsi:schemaLocation" Flags="14" Order="3" Value="http://standards.iso.org/iso/19770/-2/2008/schema.xsd software_identification_tag.xsd"/>
</COMPONENT> </COMPONENT>
<COMPONENT cid="caphyon.advinst.msicomp.XmlElementComponent"> <COMPONENT cid="caphyon.advinst.msicomp.XmlElementComponent">
<ROW XmlElement="swidbuild" ParentElement="swidnumeric" Name="swid:build" Condition="1" Order="2" Flags="14" Text="12"/> <ROW XmlElement="swidbuild" ParentElement="swidnumeric" Name="swid:build" Condition="1" Order="2" Flags="14" Text="6"/>
<ROW XmlElement="swidentitlement_required_indicator" ParentElement="swidsoftware_identification_tag" Name="swid:entitlement_required_indicator" Condition="1" Order="0" Flags="14" Text="false"/> <ROW XmlElement="swidentitlement_required_indicator" ParentElement="swidsoftware_identification_tag" Name="swid:entitlement_required_indicator" Condition="1" Order="0" Flags="14" Text="false"/>
<ROW XmlElement="swidmajor" ParentElement="swidnumeric" Name="swid:major" Condition="1" Order="0" Flags="14" Text="1"/> <ROW XmlElement="swidmajor" ParentElement="swidnumeric" Name="swid:major" Condition="1" Order="0" Flags="14" Text="1"/>
<ROW XmlElement="swidminor" ParentElement="swidnumeric" Name="swid:minor" Condition="1" Order="1" Flags="14" Text="2"/> <ROW XmlElement="swidminor" ParentElement="swidnumeric" Name="swid:minor" Condition="1" Order="1" Flags="14" Text="4"/>
<ROW XmlElement="swidname" ParentElement="swidproduct_version" Name="swid:name" Condition="1" Order="0" Flags="14" Text="[ProductVersion]"/> <ROW XmlElement="swidname" ParentElement="swidproduct_version" Name="swid:name" Condition="1" Order="0" Flags="14" Text="[ProductVersion]"/>
<ROW XmlElement="swidname_1" ParentElement="swidsoftware_creator" Name="swid:name" Condition="1" Order="0" Flags="14" Text="ZeroTier, Inc."/> <ROW XmlElement="swidname_1" ParentElement="swidsoftware_creator" Name="swid:name" Condition="1" Order="0" Flags="14" Text="ZeroTier, Inc."/>
<ROW XmlElement="swidname_2" ParentElement="swidsoftware_licensor" Name="swid:name" Condition="1" Order="0" Flags="14" Text="ZeroTier, Inc."/> <ROW XmlElement="swidname_2" ParentElement="swidsoftware_licensor" Name="swid:name" Condition="1" Order="0" Flags="14" Text="ZeroTier, Inc."/>

11
ext/installfiles/windows/chocolatey/zerotier-one/tools/LICENSE.txt

@ -1,11 +0,0 @@
From: https://raw.githubusercontent.com/zerotier/ZeroTierOne/master/COPYING
LICENSE
ZeroTier One is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
See the file ‘LICENSE.GPL-3’ for the text of the GNU GPL version 3.
If that file is not present, see <http://www.gnu.org/licenses/>.

5
ext/installfiles/windows/chocolatey/zerotier-one/tools/VERIFICATION.txt

@ -1,5 +0,0 @@
VERIFICATION
Verification is intended to assist the Chocolatey moderators and community
in verifying that this package's contents are trustworthy.
Our MSI installer should be signed by ZeroTier, Inc. using a certificate from DigiCert.

8
ext/installfiles/windows/chocolatey/zerotier-one/tools/chocolateyinstall.ps1

@ -1,8 +0,0 @@
$packageName = 'zerotier-one'
$installerType = 'msi'
$url = 'https://download.zerotier.com/RELEASES/1.2.4/dist/ZeroTier%20One.msi'
$url64 = 'https://download.zerotier.com/RELEASES/1.2.4/dist/ZeroTier%20One.msi'
$silentArgs = '/quiet'
$validExitCodes = @(0,3010)
Install-ChocolateyPackage $packageName $installerType $silentArgs $url $url64 -validExitCodes $validExitCodes

30
ext/installfiles/windows/chocolatey/zerotier-one/tools/chocolateyuninstall.ps1

@ -1,30 +0,0 @@
$ErrorActionPreference = 'Stop';
$packageName = 'zerotier-one'
$softwareName = 'ZeroTier One*'
$installerType = 'MSI'
$silentArgs = '/qn /norestart'
$validExitCodes = @(0, 3010, 1605, 1614, 1641)
$uninstalled = $false
[array]$key = Get-UninstallRegistryKey -SoftwareName $softwareName
if ($key.Count -eq 1) {
$key | % {
$silentArgs = "$($_.PSChildName) $silentArgs"
$file = ''
Uninstall-ChocolateyPackage -PackageName $packageName `
-FileType $installerType `
-SilentArgs "$silentArgs" `
-ValidExitCodes $validExitCodes `
-File "$file"
}
} elseif ($key.Count -eq 0) {
Write-Warning "$packageName has already been uninstalled by other means."
} elseif ($key.Count -gt 1) {
Write-Warning "$key.Count matches found!"
Write-Warning "To prevent accidental data loss, no programs will be uninstalled."
Write-Warning "Please alert package maintainer the following keys were matched:"
$key | % {Write-Warning "- $_.DisplayName"}
}

76
ext/installfiles/windows/chocolatey/zerotier-one/zerotier-one.nuspec

@ -1,76 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Read this before creating packages: https://github.com/chocolatey/chocolatey/wiki/CreatePackages -->
<!-- It is especially important to read the above link to understand additional requirements when publishing packages to the community feed aka dot org (https://chocolatey.org/packages). -->
<!-- Test your packages in a test environment: https://github.com/chocolatey/chocolatey-test-environment -->
<!--
This is a nuspec. It mostly adheres to https://docs.nuget.org/create/Nuspec-Reference. Chocolatey uses a special version of NuGet.Core that allows us to do more than was initially possible. As such there are certain things to be aware of:
* the package xmlns schema url may cause issues with nuget.exe
* Any of the following elements can ONLY be used by choco tools - projectSourceUrl, docsUrl, mailingListUrl, bugTrackerUrl, packageSourceUrl, provides, conflicts, replaces
* nuget.exe can still install packages with those elements but they are ignored. Any authoring tools or commands will error on those elements
-->
<!-- You can embed software files directly into packages, as long as you are not bound by distribution rights. -->
<!-- * If you are an organization making private packages, you probably have no issues here -->
<!-- * If you are releasing to the community feed, you need to consider distribution rights. -->
<!-- Do not remove this test for UTF-8: if “Ω” doesn’t appear as greek uppercase omega letter enclosed in quotation marks, you should use an editor that supports UTF-8, not this one. -->
<package xmlns="http://schemas.microsoft.com/packaging/2015/06/nuspec.xsd">
<metadata>
<!-- == PACKAGE SPECIFIC SECTION == -->
<!-- This section is about this package, although id and version have ties back to the software -->
<!-- id is lowercase and if you want a good separator for words, use '-', not '.'. Dots are only acceptable as suffixes for certain types of packages, e.g. .install, .portable, .extension, .template -->
<!-- If the software is cross-platform, attempt to use the same id as the debian/rpm package(s) if possible. -->
<id>zerotier-one</id>
<!-- version should MATCH as closely as possible with the underlying software -->
<!-- Is the version a prerelease of a version? https://docs.nuget.org/create/versioning#creating-prerelease-packages -->
<!-- Note that unstable versions like 0.0.1 can be considered a released version, but it's possible that one can release a 0.0.1-beta before you release a 0.0.1 version. If the version number is final, that is considered a released version and not a prerelease. -->
<version>1.2.12</version>
<!-- <packageSourceUrl>Where is this Chocolatey package located (think GitHub)? packageSourceUrl is highly recommended for the community feed</packageSourceUrl>-->
<!-- owners is a poor name for maintainers of the package. It sticks around by this name for compatibility reasons. It basically means you. -->
<!--<owners>ZeroTier, Inc.</owners>-->
<!-- ============================== -->
<!-- == SOFTWARE SPECIFIC SECTION == -->
<!-- This section is about the software itself -->
<title>zerotier-one (Install)</title>
<authors>ZeroTier, Inc.</authors>
<!-- projectUrl is required for the community feed -->
<projectUrl>https://www.zerotier.com/</projectUrl>
<!--<iconUrl>https://www.zerotier.com/img/ZeroTierIcon.png</iconUrl>-->
<!-- <copyright>2011-2016 ZeroTier, Inc.</copyright> -->
<!-- If there is a license Url available, it is is required for the community feed -->
<!-- <licenseUrl>https://raw.githubusercontent.com/zerotier/ZeroTierOne/master/COPYING</licenseUrl>
<requireLicenseAcceptance>true</requireLicenseAcceptance>-->
<!--<projectSourceUrl>https://github.com/zerotier/ZeroTierOne</projectSourceUrl>-->
<!--<docsUrl>https://www.zerotier.com/</docsUrl>-->
<!--<mailingListUrl></mailingListUrl>-->
<!--<bugTrackerUrl>https://github.com/zerotier/ZeroTierOne/issues</bugTrackerUrl>-->
<tags>zerotier-one admin</tags>
<summary>ZeroTier One Virtual Network Endpoint for Windows</summary>
<description>ZeroTier is a smart switch for Earth with VLAN capability. See https://www.zerotier.com/ for more information.</description>
<!-- <releaseNotes>__REPLACE_OR_REMOVE__MarkDown_Okay</releaseNotes> -->
<!-- =============================== -->
<!-- Specifying dependencies and version ranges? https://docs.nuget.org/create/versioning#specifying-version-ranges-in-.nuspec-files -->
<!--<dependencies>
<dependency id="" version="__MINIMUM_VERSION__" />
<dependency id="" version="[__EXACT_VERSION__]" />
<dependency id="" version="[_MIN_VERSION_INCLUSIVE, MAX_VERSION_INCLUSIVE]" />
<dependency id="" version="[_MIN_VERSION_INCLUSIVE, MAX_VERSION_EXCLUSIVE)" />
<dependency id="" />
<dependency id="chocolatey-uninstall.extension" />
</dependencies>-->
<!-- chocolatey-uninstall.extension - If supporting 0.9.9.x (or below) and including a chocolateyUninstall.ps1 file to uninstall an EXE/MSI, you probably want to include chocolatey-uninstall.extension as a dependency. Please verify whether you are using a helper function from that package. -->
<!--<provides>NOT YET IMPLEMENTED</provides>-->
<!--<conflicts>NOT YET IMPLEMENTED</conflicts>-->
<!--<replaces>NOT YET IMPLEMENTED</replaces>-->
</metadata>
<files>
<!-- this section controls what actually gets packaged into the Chocolatey package -->
<file src="tools\**" target="tools" />
<!--Building from Linux? You may need this instead: <file src="tools/**" target="tools" />-->
</files>
</package>

2538
ext/librabbitmq/macos/include/amqp.h

File diff suppressed because it is too large Load Diff

1144
ext/librabbitmq/macos/include/amqp_framing.h

File diff suppressed because it is too large Load Diff

68
ext/librabbitmq/macos/include/amqp_tcp_socket.h

@ -0,0 +1,68 @@
/** \file */
/*
* Portions created by Alan Antonuk are Copyright (c) 2013-2014 Alan Antonuk.
* All Rights Reserved.
*
* Portions created by Michael Steinert are Copyright (c) 2012-2013 Michael
* Steinert. All Rights Reserved.
*
* 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.
*/
/**
* A TCP socket connection.
*/
#ifndef AMQP_TCP_SOCKET_H
#define AMQP_TCP_SOCKET_H
#include <amqp.h>
AMQP_BEGIN_DECLS
/**
* Create a new TCP socket.
*
* Call amqp_connection_close() to release socket resources.
*
* \return A new socket object or NULL if an error occurred.
*
* \since v0.4.0
*/
AMQP_PUBLIC_FUNCTION
amqp_socket_t *AMQP_CALL amqp_tcp_socket_new(amqp_connection_state_t state);
/**
* Assign an open file descriptor to a socket object.
*
* This function must not be used in conjunction with amqp_socket_open(), i.e.
* the socket connection should already be open(2) when this function is
* called.
*
* \param [in,out] self A TCP socket object.
* \param [in] sockfd An open socket descriptor.
*
* \since v0.4.0
*/
AMQP_PUBLIC_FUNCTION
void AMQP_CALL amqp_tcp_socket_set_sockfd(amqp_socket_t *self, int sockfd);
AMQP_END_DECLS
#endif /* AMQP_TCP_SOCKET_H */

BIN
ext/librabbitmq/macos/lib/librabbitmq.a

Binary file not shown.

29
include/ZeroTierDebug.h

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
/** /**
* @file * @file
@ -80,7 +67,7 @@
#define ZT_THREAD_ID (long)0 // (long)gettid() #define ZT_THREAD_ID (long)0 // (long)gettid()
#endif #endif
#ifdef _WIN32 #ifdef _WIN32
#define ZT_THREAD_ID (long)0 // #define ZT_THREAD_ID (long)0 //
#endif #endif
#if defined(__JNI_LIB__) #if defined(__JNI_LIB__)
#include <jni.h> #include <jni.h>

50
include/ZeroTierOne.h

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
/* /*
* This defines the external C API for ZeroTier's core network virtualization * This defines the external C API for ZeroTier's core network virtualization
@ -198,6 +185,11 @@ extern "C" {
*/ */
#define ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH 7 #define ZT_MAX_CAPABILITY_CUSTODY_CHAIN_LENGTH 7
/**
* Maximum number of multicast groups a device / network interface can be subscribed to at once
*/
#define ZT_MAX_MULTICAST_SUBSCRIPTIONS 1024
/** /**
* Maximum value for link quality (min is 0) * Maximum value for link quality (min is 0)
*/ */
@ -652,7 +644,7 @@ typedef struct
/** /**
* Internal node statistics * Internal node statistics
* *
* This structure is subject to change between versions. * This structure is subject to change between versions.
*/ */
typedef struct typedef struct
@ -1096,7 +1088,8 @@ enum ZT_Architecture
ZT_ARCHITECTURE_SPARC64 = 12, ZT_ARCHITECTURE_SPARC64 = 12,
ZT_ARCHITECTURE_DOTNET_CLR = 13, ZT_ARCHITECTURE_DOTNET_CLR = 13,
ZT_ARCHITECTURE_JAVA_JVM = 14, ZT_ARCHITECTURE_JAVA_JVM = 14,
ZT_ARCHITECTURE_WEB = 15 ZT_ARCHITECTURE_WEB = 15,
ZT_ARCHITECTURE_S390X = 16
}; };
/** /**
@ -1192,6 +1185,19 @@ typedef struct
* Routes (excluding those implied by assigned addresses and their masks) * Routes (excluding those implied by assigned addresses and their masks)
*/ */
ZT_VirtualNetworkRoute routes[ZT_MAX_NETWORK_ROUTES]; ZT_VirtualNetworkRoute routes[ZT_MAX_NETWORK_ROUTES];
/**
* Number of multicast groups subscribed
*/
unsigned int multicastSubscriptionCount;
/**
* Multicast groups to which this network's device is subscribed
*/
struct {
uint64_t mac; /* MAC in lower 48 bits */
uint32_t adi; /* Additional distinguishing information, usually zero except for IPv4 ARP groups */
} multicastSubscriptions[ZT_MAX_MULTICAST_SUBSCRIPTIONS];
} ZT_VirtualNetworkConfig; } ZT_VirtualNetworkConfig;
/** /**

8
macui/ZeroTier One.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>

4
make-bsd.mk

@ -13,7 +13,7 @@ ifeq ($(ZT_SANITIZE),1)
endif endif
# "make debug" is a shortcut for this # "make debug" is a shortcut for this
ifeq ($(ZT_DEBUG),1) ifeq ($(ZT_DEBUG),1)
CFLAGS+=-Wall -Werror -g -pthread $(INCLUDES) $(DEFS) CFLAGS+=-Wall -g -pthread $(INCLUDES) $(DEFS)
LDFLAGS+= LDFLAGS+=
STRIP=echo STRIP=echo
ZT_TRACE=1 ZT_TRACE=1
@ -128,7 +128,7 @@ endif
override DEFS+=-DZT_BUILD_PLATFORM=$(ZT_BUILD_PLATFORM) -DZT_BUILD_ARCHITECTURE=$(ZT_ARCHITECTURE) -DZT_SOFTWARE_UPDATE_DEFAULT="\"disable\"" override DEFS+=-DZT_BUILD_PLATFORM=$(ZT_BUILD_PLATFORM) -DZT_BUILD_ARCHITECTURE=$(ZT_ARCHITECTURE) -DZT_SOFTWARE_UPDATE_DEFAULT="\"disable\""
CXXFLAGS+=$(CFLAGS) -fno-rtti -std=c++11 #-D_GLIBCXX_USE_C99 -D_GLIBCXX_USE_C99_MATH -D_GLIBCXX_USE_C99_MATH_TR1 CXXFLAGS+=$(CFLAGS) -std=c++11 #-D_GLIBCXX_USE_C99 -D_GLIBCXX_USE_C99_MATH -D_GLIBCXX_USE_C99_MATH_TR1
all: one all: one

67
make-linux.mk

@ -1,12 +1,12 @@
# Automagically pick clang or gcc, with preference for clang # Automagically pick CLANG or RH/CentOS newer GCC if present
# This is only done if we have not overridden these with an environment or CLI variable # This is only done if we have not overridden these with an environment or CLI variable
ifeq ($(origin CC),default) ifeq ($(origin CC),default)
CC:=$(shell if [ -e /usr/bin/clang ]; then echo clang; else echo gcc; fi) CC:=$(shell if [ -e /usr/bin/clang ]; then echo clang; else echo gcc; fi)
CC:=$(shell if [ -e /opt/intel/bin/icc ]; then echo /opt/intel/bin/icc -ipo -ansi-alias; else echo $(CC); fi) CC:=$(shell if [ -e /opt/rh/devtoolset-8/root/usr/bin/gcc ]; then echo /opt/rh/devtoolset-8/root/usr/bin/gcc; else echo $(CC); fi)
endif endif
ifeq ($(origin CXX),default) ifeq ($(origin CXX),default)
CXX:=$(shell if [ -e /usr/bin/clang++ ]; then echo clang++; else echo g++; fi) CXX:=$(shell if [ -e /usr/bin/clang++ ]; then echo clang++; else echo g++; fi)
CXX:=$(shell if [ -e /opt/intel/bin/icc ]; then echo /opt/intel/bin/icc -ipo -ansi-alias; else echo $(CXX); fi) CXX:=$(shell if [ -e /opt/rh/devtoolset-8/root/usr/bin/g++ ]; then echo /opt/rh/devtoolset-8/root/usr/bin/g++; else echo $(CXX); fi)
endif endif
INCLUDES?= INCLUDES?=
@ -14,14 +14,10 @@ DEFS?=
LDLIBS?= LDLIBS?=
DESTDIR?= DESTDIR?=
include objects.mk include objects.mk
ONE_OBJS+=osdep/LinuxEthernetTap.o ONE_OBJS+=osdep/LinuxEthernetTap.o
ONE_OBJS+=osdep/LinuxNetLink.o ONE_OBJS+=osdep/LinuxNetLink.o
NLTEST_OBJS+=osdep/LinuxNetLink.o node/InetAddress.o node/Utils.o node/Salsa20.o
NLTEST_OBJS+=nltest.o
# for central controller builds # for central controller builds
TIMESTAMP=$(shell date +"%Y%m%d%H%M") TIMESTAMP=$(shell date +"%Y%m%d%H%M")
@ -96,6 +92,10 @@ ifeq ($(ZT_SYNOLOGY), 1)
override DEFS+=-D__SYNOLOGY__ override DEFS+=-D__SYNOLOGY__
endif endif
ifeq ($(ZT_DISABLE_COMPRESSION), 1)
override DEFS+=-DZT_DISABLE_COMPRESSION
endif
ifeq ($(ZT_TRACE),1) ifeq ($(ZT_TRACE),1)
override DEFS+=-DZT_TRACE override DEFS+=-DZT_TRACE
endif endif
@ -175,6 +175,11 @@ ifeq ($(CC_MACH),armv6)
override DEFS+=-DZT_NO_TYPE_PUNNING override DEFS+=-DZT_NO_TYPE_PUNNING
ZT_USE_ARM32_NEON_ASM_CRYPTO=1 ZT_USE_ARM32_NEON_ASM_CRYPTO=1
endif endif
ifeq ($(CC_MACH),armv6l)
ZT_ARCHITECTURE=3
override DEFS+=-DZT_NO_TYPE_PUNNING
ZT_USE_ARM32_NEON_ASM_CRYPTO=1
endif
ifeq ($(CC_MACH),armv6zk) ifeq ($(CC_MACH),armv6zk)
ZT_ARCHITECTURE=3 ZT_ARCHITECTURE=3
override DEFS+=-DZT_NO_TYPE_PUNNING override DEFS+=-DZT_NO_TYPE_PUNNING
@ -224,6 +229,9 @@ ifeq ($(CC_MACH),mips64el)
ZT_ARCHITECTURE=6 ZT_ARCHITECTURE=6
override DEFS+=-DZT_NO_TYPE_PUNNING override DEFS+=-DZT_NO_TYPE_PUNNING
endif endif
ifeq ($(CC_MACH),s390x)
ZT_ARCHITECTURE=16
endif
# Fail if system architecture could not be determined # Fail if system architecture could not be determined
ifeq ($(ZT_ARCHITECTURE),999) ifeq ($(ZT_ARCHITECTURE),999)
@ -256,8 +264,8 @@ ifeq ($(ZT_ARCHITECTURE),3)
override CXXFLAGS+=-march=armv5 -mfloat-abi=soft -msoft-float -mno-unaligned-access -marm override CXXFLAGS+=-march=armv5 -mfloat-abi=soft -msoft-float -mno-unaligned-access -marm
ZT_USE_ARM32_NEON_ASM_CRYPTO=0 ZT_USE_ARM32_NEON_ASM_CRYPTO=0
else else
override CFLAGS+=-march=armv5 -mno-unaligned-access -marm override CFLAGS+=-march=armv5 -mno-unaligned-access -marm -fexceptions
override CXXFLAGS+=-march=armv5 -mno-unaligned-access -marm override CXXFLAGS+=-march=armv5 -mno-unaligned-access -marm -fexceptions
ZT_USE_ARM32_NEON_ASM_CRYPTO=0 ZT_USE_ARM32_NEON_ASM_CRYPTO=0
endif endif
endif endif
@ -276,19 +284,21 @@ ifeq ($(ZT_USE_ARM32_NEON_ASM_CRYPTO),1)
override CORE_OBJS+=ext/arm32-neon-salsa2012-asm/salsa2012.o override CORE_OBJS+=ext/arm32-neon-salsa2012-asm/salsa2012.o
endif endif
.PHONY: all
all: one all: one
one: $(CORE_OBJS) $(ONE_OBJS) one.o .PHONY: one
one: zerotier-one zerotier-idtool zerotier-cli
zerotier-one: $(CORE_OBJS) $(ONE_OBJS) one.o
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o zerotier-one $(CORE_OBJS) $(ONE_OBJS) one.o $(LDLIBS) $(CXX) $(CXXFLAGS) $(LDFLAGS) -o zerotier-one $(CORE_OBJS) $(ONE_OBJS) one.o $(LDLIBS)
$(STRIP) zerotier-one $(STRIP) zerotier-one
ln -sf zerotier-one zerotier-idtool
ln -sf zerotier-one zerotier-cli
zerotier-one: one
zerotier-idtool: one zerotier-idtool: zerotier-one
ln -sf zerotier-one zerotier-idtool
zerotier-cli: one zerotier-cli: zerotier-one
ln -sf zerotier-one zerotier-cli
libzerotiercore.a: FORCE libzerotiercore.a: FORCE
make CFLAGS="-O3 -fstack-protector -fPIC" CXXFLAGS="-O3 -std=c++11 -fstack-protector -fPIC" $(CORE_OBJS) make CFLAGS="-O3 -fstack-protector -fPIC" CXXFLAGS="-O3 -std=c++11 -fstack-protector -fPIC" $(CORE_OBJS)
@ -309,7 +319,7 @@ manpages: FORCE
doc: manpages doc: manpages
clean: FORCE clean: FORCE
rm -rf *.a *.so *.o node/*.o controller/*.o osdep/*.o service/*.o ext/http-parser/*.o ext/miniupnpc/*.o ext/libnatpmp/*.o $(CORE_OBJS) $(ONE_OBJS) zerotier-one zerotier-idtool zerotier-cli zerotier-selftest build-* ZeroTierOneInstaller-* *.deb *.rpm .depend debian/files debian/zerotier-one*.debhelper debian/zerotier-one.substvars debian/*.log debian/zerotier-one doc/node_modules ext/misc/*.o debian/.debhelper debian/debhelper-build-stamp rm -rf *.a *.so *.o node/*.o controller/*.o osdep/*.o service/*.o ext/http-parser/*.o ext/miniupnpc/*.o ext/libnatpmp/*.o $(CORE_OBJS) $(ONE_OBJS) zerotier-one zerotier-idtool zerotier-cli zerotier-selftest build-* ZeroTierOneInstaller-* *.deb *.rpm .depend debian/files debian/zerotier-one*.debhelper debian/zerotier-one.substvars debian/*.log debian/zerotier-one doc/node_modules ext/misc/*.o debian/.debhelper debian/debhelper-build-stamp docker/zerotier-one
distclean: clean distclean: clean
@ -318,19 +328,19 @@ realclean: distclean
official: FORCE official: FORCE
make -j4 ZT_OFFICIAL=1 all make -j4 ZT_OFFICIAL=1 all
docker: FORCE
docker build -f ext/installfiles/linux/zerotier-containerized/Dockerfile -t zerotier-containerized .
central-controller: FORCE central-controller: FORCE
make -j4 LDLIBS="-L/usr/pgsql-10/lib/ -lpq -Lext/librabbitmq/centos_x64/lib/ -lrabbitmq" CXXFLAGS="-I/usr/pgsql-10/include -I./ext/librabbitmq/centos_x64/include -fPIC" DEFS="-DZT_CONTROLLER_USE_LIBPQ -DZT_CONTROLLER" ZT_OFFICIAL=1 ZT_USE_X64_ASM_ED25519=1 one make -j4 LDLIBS="-L/usr/pgsql-10/lib/ -lpq -Lext/librabbitmq/centos_x64/lib/ -lrabbitmq" CXXFLAGS="-I/usr/pgsql-10/include -I./ext/librabbitmq/centos_x64/include -fPIC" DEFS="-DZT_CONTROLLER_USE_LIBPQ -DZT_CONTROLLER" ZT_OFFICIAL=1 ZT_USE_X64_ASM_ED25519=1 one
central-controller-docker: central-controller central-controller-docker: FORCE
docker build -t docker.zerotier.com/zerotier-central/ztcentral-controller:${TIMESTAMP} -f docker/Dockerfile . docker build -t docker.zerotier.com/zerotier-central/ztcentral-controller:${TIMESTAMP} -f ext/central-controller-docker/Dockerfile --build-arg git_branch=`git name-rev --name-only HEAD` .
debug: FORCE debug: FORCE
make ZT_DEBUG=1 one make ZT_DEBUG=1 one
make ZT_DEBUG=1 selftest make ZT_DEBUG=1 selftest
nltest: $(NLTEST_OBJS)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o nltest $(NLTEST_OBJS) $(LDLIBS)
# Note: keep the symlinks in /var/lib/zerotier-one to the binaries since these # Note: keep the symlinks in /var/lib/zerotier-one to the binaries since these
# provide backward compatibility with old releases where the binaries actually # provide backward compatibility with old releases where the binaries actually
# lived here. Folks got scripts. # lived here. Folks got scripts.
@ -386,6 +396,13 @@ debian-clean: FORCE
rm -rf debian/files debian/zerotier-one*.debhelper debian/zerotier-one.substvars debian/*.log debian/zerotier-one debian/.debhelper debian/debhelper-build-stamp rm -rf debian/files debian/zerotier-one*.debhelper debian/zerotier-one.substvars debian/*.log debian/zerotier-one debian/.debhelper debian/debhelper-build-stamp
redhat: FORCE redhat: FORCE
rpmbuild -ba zerotier-one.spec rpmbuild --target `rpm -q bash --qf "%{arch}"` -ba zerotier-one.spec
# This installs the packages needed to build ZT locally on CentOS 7 and
# is here largely for documentation purposes.
centos-7-setup: FORCE
yum install -y gcc gcc-c++ make epel-release git
yum install -y centos-release-scl
yum install -y devtoolset-8-gcc devtoolset-8-gcc-c++
FORCE: FORCE:

19
make-mac.mk

@ -8,6 +8,8 @@ CODESIGN=echo
PRODUCTSIGN=echo PRODUCTSIGN=echo
CODESIGN_APP_CERT= CODESIGN_APP_CERT=
CODESIGN_INSTALLER_CERT= CODESIGN_INSTALLER_CERT=
NOTARIZE=echo
NOTARIZE_USER_ID=null
ZT_BUILD_PLATFORM=3 ZT_BUILD_PLATFORM=3
ZT_BUILD_ARCHITECTURE=2 ZT_BUILD_ARCHITECTURE=2
@ -16,14 +18,18 @@ ZT_VERSION_MINOR=$(shell cat version.h | grep -F VERSION_MINOR | cut -d ' ' -f 3
ZT_VERSION_REV=$(shell cat version.h | grep -F VERSION_REVISION | cut -d ' ' -f 3) ZT_VERSION_REV=$(shell cat version.h | grep -F VERSION_REVISION | cut -d ' ' -f 3)
ZT_VERSION_BUILD=$(shell cat version.h | grep -F VERSION_BUILD | cut -d ' ' -f 3) ZT_VERSION_BUILD=$(shell cat version.h | grep -F VERSION_BUILD | cut -d ' ' -f 3)
# for central controller builds
TIMESTAMP=$(shell date +"%Y%m%d%H%M")
DEFS+=-DZT_BUILD_PLATFORM=$(ZT_BUILD_PLATFORM) -DZT_BUILD_ARCHITECTURE=$(ZT_BUILD_ARCHITECTURE) DEFS+=-DZT_BUILD_PLATFORM=$(ZT_BUILD_PLATFORM) -DZT_BUILD_ARCHITECTURE=$(ZT_BUILD_ARCHITECTURE)
include objects.mk include objects.mk
ONE_OBJS+=osdep/MacEthernetTap.o ext/http-parser/http_parser.o ONE_OBJS+=osdep/MacEthernetTap.o osdep/MacKextEthernetTap.o ext/http-parser/http_parser.o
ifeq ($(ZT_CONTROLLER),1) ifeq ($(ZT_CONTROLLER),1)
LIBS+=-lpq -lrabbitmq LIBS+=-L/usr/local/opt/libpq/lib -lpq -Lext/librabbitmq/macos/lib -lrabbitmq
DEFS+=-DZT_CONTROLLER_USE_LIBPQ -DZT_CONTROLLER DEFS+=-DZT_CONTROLLER_USE_LIBPQ -DZT_CONTROLLER
INCLUDES+=-Iext/librabbitmq/macos/include -I/usr/local/opt/libpq/include
endif endif
# Official releases are signed with our Apple cert and apply software updates by default # Official releases are signed with our Apple cert and apply software updates by default
@ -34,6 +40,8 @@ ifeq ($(ZT_OFFICIAL_RELEASE),1)
PRODUCTSIGN=productsign PRODUCTSIGN=productsign
CODESIGN_APP_CERT="Developer ID Application: ZeroTier, Inc (8ZD9JUCZ4V)" CODESIGN_APP_CERT="Developer ID Application: ZeroTier, Inc (8ZD9JUCZ4V)"
CODESIGN_INSTALLER_CERT="Developer ID Installer: ZeroTier, Inc (8ZD9JUCZ4V)" CODESIGN_INSTALLER_CERT="Developer ID Installer: ZeroTier, Inc (8ZD9JUCZ4V)"
NOTARIZE=xcrun altool
NOTARIZE_USER_ID="adam.ierymenko@gmail.com"
else else
DEFS+=-DZT_SOFTWARE_UPDATE_DEFAULT="\"download\"" DEFS+=-DZT_SOFTWARE_UPDATE_DEFAULT="\"download\""
endif endif
@ -76,7 +84,7 @@ ifeq ($(ZT_VAULT_SUPPORT),1)
LIBS+=-lcurl LIBS+=-lcurl
endif endif
CXXFLAGS=$(CFLAGS) -std=c++11 -stdlib=libc++ CXXFLAGS=$(CFLAGS) -std=c++11 -stdlib=libc++
all: one macui all: one macui
@ -131,6 +139,8 @@ mac-dist-pkg: FORCE
if [ -f "ZeroTier One Signed.pkg" ]; then mv -f "ZeroTier One Signed.pkg" "ZeroTier One.pkg"; fi if [ -f "ZeroTier One Signed.pkg" ]; then mv -f "ZeroTier One Signed.pkg" "ZeroTier One.pkg"; fi
rm -f zt1_update_$(ZT_BUILD_PLATFORM)_$(ZT_BUILD_ARCHITECTURE)_* rm -f zt1_update_$(ZT_BUILD_PLATFORM)_$(ZT_BUILD_ARCHITECTURE)_*
cat ext/installfiles/mac-update/updater.tmpl.sh "ZeroTier One.pkg" >zt1_update_$(ZT_BUILD_PLATFORM)_$(ZT_BUILD_ARCHITECTURE)_$(ZT_VERSION_MAJOR).$(ZT_VERSION_MINOR).$(ZT_VERSION_REV)_$(ZT_VERSION_BUILD).exe cat ext/installfiles/mac-update/updater.tmpl.sh "ZeroTier One.pkg" >zt1_update_$(ZT_BUILD_PLATFORM)_$(ZT_BUILD_ARCHITECTURE)_$(ZT_VERSION_MAJOR).$(ZT_VERSION_MINOR).$(ZT_VERSION_REV)_$(ZT_VERSION_BUILD).exe
$(NOTARIZE) -t osx -f "ZeroTier One.pkg" --primary-bundle-id --output-format xml --notarize-app -u $(NOTARIZE_USER_ID)
echo '*** When Apple notifies that the app is notarized, run: xcrun stapler staple "ZeroTier One.pkg"'
# For ZeroTier, Inc. to build official signed packages # For ZeroTier, Inc. to build official signed packages
official: FORCE official: FORCE
@ -139,6 +149,9 @@ official: FORCE
make ZT_OFFICIAL_RELEASE=1 macui make ZT_OFFICIAL_RELEASE=1 macui
make ZT_OFFICIAL_RELEASE=1 mac-dist-pkg make ZT_OFFICIAL_RELEASE=1 mac-dist-pkg
central-controller-docker: FORCE
docker build -t docker.zerotier.com/zerotier-central/ztcentral-controller:${TIMESTAMP} -f ext/central-controller-docker/Dockerfile --build-arg git_branch=$(shell git name-rev --name-only HEAD) .
clean: clean:
rm -rf MacEthernetTapAgent *.dSYM build-* *.a *.pkg *.dmg *.o node/*.o controller/*.o service/*.o osdep/*.o ext/http-parser/*.o $(CORE_OBJS) $(ONE_OBJS) zerotier-one zerotier-idtool zerotier-selftest zerotier-cli zerotier doc/node_modules macui/build zt1_update_$(ZT_BUILD_PLATFORM)_$(ZT_BUILD_ARCHITECTURE)_* rm -rf MacEthernetTapAgent *.dSYM build-* *.a *.pkg *.dmg *.o node/*.o controller/*.o service/*.o osdep/*.o ext/http-parser/*.o $(CORE_OBJS) $(ONE_OBJS) zerotier-one zerotier-idtool zerotier-selftest zerotier-cli zerotier doc/node_modules macui/build zt1_update_$(ZT_BUILD_PLATFORM)_$(ZT_BUILD_ARCHITECTURE)_*

27
node/Address.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_ADDRESS_HPP #ifndef ZT_ADDRESS_HPP
#define ZT_ADDRESS_HPP #define ZT_ADDRESS_HPP

27
node/AtomicCounter.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_ATOMICCOUNTER_HPP #ifndef ZT_ATOMICCOUNTER_HPP
#define ZT_ATOMICCOUNTER_HPP #define ZT_ATOMICCOUNTER_HPP

27
node/Buffer.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_BUFFER_HPP #ifndef ZT_BUFFER_HPP
#define ZT_BUFFER_HPP #define ZT_BUFFER_HPP

1069
node/C25519.cpp

File diff suppressed because it is too large Load Diff

27
node/C25519.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_C25519_HPP #ifndef ZT_C25519_HPP
#define ZT_C25519_HPP #define ZT_C25519_HPP

27
node/Capability.cpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#include "Capability.hpp" #include "Capability.hpp"
#include "RuntimeEnvironment.hpp" #include "RuntimeEnvironment.hpp"

27
node/Capability.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_CAPABILITY_HPP #ifndef ZT_CAPABILITY_HPP
#define ZT_CAPABILITY_HPP #define ZT_CAPABILITY_HPP

27
node/CertificateOfMembership.cpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#include "CertificateOfMembership.hpp" #include "CertificateOfMembership.hpp"
#include "RuntimeEnvironment.hpp" #include "RuntimeEnvironment.hpp"

31
node/CertificateOfMembership.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_CERTIFICATEOFMEMBERSHIP_HPP #ifndef ZT_CERTIFICATEOFMEMBERSHIP_HPP
#define ZT_CERTIFICATEOFMEMBERSHIP_HPP #define ZT_CERTIFICATEOFMEMBERSHIP_HPP
@ -113,9 +100,7 @@ public:
* Create an empty certificate of membership * Create an empty certificate of membership
*/ */
CertificateOfMembership() : CertificateOfMembership() :
_qualifierCount(0) _qualifierCount(0) {}
{
}
/** /**
* Create from required fields common to all networks * Create from required fields common to all networks

27
node/CertificateOfOwnership.cpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#include "CertificateOfOwnership.hpp" #include "CertificateOfOwnership.hpp"
#include "RuntimeEnvironment.hpp" #include "RuntimeEnvironment.hpp"

54
node/CertificateOfOwnership.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_CERTIFICATEOFOWNERSHIP_HPP #ifndef ZT_CERTIFICATEOFOWNERSHIP_HPP
#define ZT_CERTIFICATEOFOWNERSHIP_HPP #define ZT_CERTIFICATEOFOWNERSHIP_HPP
@ -67,29 +54,18 @@ public:
THING_IPV6_ADDRESS = 3 THING_IPV6_ADDRESS = 3
}; };
CertificateOfOwnership() : CertificateOfOwnership()
_networkId(0),
_ts(0),
_flags(0),
_id(0),
_thingCount(0)
{ {
memset(_thingTypes,0,sizeof(_thingTypes)); memset(reinterpret_cast<void *>(this),0,sizeof(CertificateOfOwnership));
memset(_thingValues,0,sizeof(_thingValues));
memset(_signature.data,0,sizeof(_signature.data));
} }
CertificateOfOwnership(const uint64_t nwid,const int64_t ts,const Address &issuedTo,const uint32_t id) : CertificateOfOwnership(const uint64_t nwid,const int64_t ts,const Address &issuedTo,const uint32_t id)
_networkId(nwid),
_ts(ts),
_flags(0),
_id(id),
_thingCount(0),
_issuedTo(issuedTo)
{ {
memset(_thingTypes,0,sizeof(_thingTypes)); memset(reinterpret_cast<void *>(this),0,sizeof(CertificateOfOwnership));
memset(_thingValues,0,sizeof(_thingValues)); _networkId = nwid;
memset(_signature.data,0,sizeof(_signature.data)); _ts = ts;
_id = id;
_issuedTo = issuedTo;
} }
inline uint64_t networkId() const { return _networkId; } inline uint64_t networkId() const { return _networkId; }

97
node/Constants.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_CONSTANTS_HPP #ifndef ZT_CONSTANTS_HPP
#define ZT_CONSTANTS_HPP #define ZT_CONSTANTS_HPP
@ -72,14 +59,6 @@
#include <machine/endian.h> #include <machine/endian.h>
#endif #endif
// Defined this macro to disable "type punning" on a number of targets that
// have issues with unaligned memory access.
#if defined(__arm__) || defined(__ARMEL__) || (defined(__APPLE__) && ( (defined(TARGET_OS_IPHONE) && (TARGET_OS_IPHONE != 0)) || (defined(TARGET_OS_WATCH) && (TARGET_OS_WATCH != 0)) || (defined(TARGET_IPHONE_SIMULATOR) && (TARGET_IPHONE_SIMULATOR != 0)) ) )
#ifndef ZT_NO_TYPE_PUNNING
#define ZT_NO_TYPE_PUNNING
#endif
#endif
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
#ifndef __UNIX_LIKE__ #ifndef __UNIX_LIKE__
#define __UNIX_LIKE__ #define __UNIX_LIKE__
@ -107,13 +86,23 @@
#pragma warning(disable : 4101) #pragma warning(disable : 4101)
#undef __UNIX_LIKE__ #undef __UNIX_LIKE__
#undef __BSD__ #undef __BSD__
#define ZT_PATH_SEPARATOR '\\'
#define ZT_PATH_SEPARATOR_S "\\"
#define ZT_EOL_S "\r\n"
#include <WinSock2.h> #include <WinSock2.h>
#include <Windows.h> #include <Windows.h>
#endif #endif
#ifdef __NetBSD__
#ifndef RTF_MULTICAST
#define RTF_MULTICAST 0x20000000
#endif
#endif
// Define ZT_NO_TYPE_PUNNING to disable reckless casts on anything other than x86/x64.
#if (!(defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_AMD64) || defined(_M_X64) || defined(i386) || defined(__i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(_M_IX86) || defined(__X86__) || defined(_X86_) || defined(__I86__) || defined(__INTEL__) || defined(__386)))
#ifndef ZT_NO_TYPE_PUNNING
#define ZT_NO_TYPE_PUNNING
#endif
#endif
// Assume little endian if not defined // Assume little endian if not defined
#if (defined(__APPLE__) || defined(__WINDOWS__)) && (!defined(__BYTE_ORDER)) #if (defined(__APPLE__) || defined(__WINDOWS__)) && (!defined(__BYTE_ORDER))
#undef __BYTE_ORDER #undef __BYTE_ORDER
@ -124,7 +113,11 @@
#define __BYTE_ORDER 1234 #define __BYTE_ORDER 1234
#endif #endif
#ifdef __UNIX_LIKE__ #ifdef __WINDOWS__
#define ZT_PATH_SEPARATOR '\\'
#define ZT_PATH_SEPARATOR_S "\\"
#define ZT_EOL_S "\r\n"
#else
#define ZT_PATH_SEPARATOR '/' #define ZT_PATH_SEPARATOR '/'
#define ZT_PATH_SEPARATOR_S "/" #define ZT_PATH_SEPARATOR_S "/"
#define ZT_EOL_S "\n" #define ZT_EOL_S "\n"
@ -134,10 +127,6 @@
#include <endian.h> #include <endian.h>
#endif #endif
#ifdef __NetBSD__
#define RTF_MULTICAST 0x20000000
#endif
#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__) #if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
#ifndef likely #ifndef likely
#define likely(x) __builtin_expect((x),1) #define likely(x) __builtin_expect((x),1)
@ -225,11 +214,6 @@
*/ */
#define ZT_RECEIVE_QUEUE_TIMEOUT 5000 #define ZT_RECEIVE_QUEUE_TIMEOUT 5000
/**
* Maximum latency to allow for OK(HELLO) before packet is discarded
*/
#define ZT_HELLO_MAX_ALLOWABLE_LATENCY 120000
/** /**
* Maximum number of ZT hops allowed (this is not IP hops/TTL) * Maximum number of ZT hops allowed (this is not IP hops/TTL)
* *
@ -265,7 +249,7 @@
#define ZT_PING_CHECK_INVERVAL 5000 #define ZT_PING_CHECK_INVERVAL 5000
/** /**
* How often the local.conf file is checked for changes * How often the local.conf file is checked for changes (service, should be moved there)
*/ */
#define ZT_LOCAL_CONF_FILE_CHECK_INTERVAL 10000 #define ZT_LOCAL_CONF_FILE_CHECK_INTERVAL 10000
@ -464,8 +448,11 @@
/** /**
* Delay between full-fledge pings of directly connected peers. * Delay between full-fledge pings of directly connected peers.
*
* With multipath bonding enabled ping peers more often to measure * With multipath bonding enabled ping peers more often to measure
* packet loss and latency. * packet loss and latency. This uses more bandwidth so is disabled
* by default to avoid increasing idle bandwidth use for regular
* links.
*/ */
#define ZT_MULTIPATH_PEER_PING_PERIOD 5000 #define ZT_MULTIPATH_PEER_PING_PERIOD 5000
@ -482,7 +469,11 @@
/** /**
* Timeout for overall peer activity (measured from last receive) * Timeout for overall peer activity (measured from last receive)
*/ */
#ifndef ZT_SDK
#define ZT_PEER_ACTIVITY_TIMEOUT 500000 #define ZT_PEER_ACTIVITY_TIMEOUT 500000
#else
#define ZT_PEER_ACTIVITY_TIMEOUT 30000
#endif
/** /**
* General rate limit timeout for multiple packet types (HELLO, etc.) * General rate limit timeout for multiple packet types (HELLO, etc.)
@ -528,14 +519,19 @@
#define ZT_MAX_BRIDGE_ROUTES 67108864 #define ZT_MAX_BRIDGE_ROUTES 67108864
/** /**
* If there is no known route, spam to up to this many active bridges * If there is no known L2 bridging route, spam to up to this many active bridges
*/ */
#define ZT_MAX_BRIDGE_SPAM 32 #define ZT_MAX_BRIDGE_SPAM 32
/** /**
* Interval between direct path pushes in milliseconds * Interval between direct path pushes in milliseconds
*/ */
#define ZT_DIRECT_PATH_PUSH_INTERVAL 120000 #define ZT_DIRECT_PATH_PUSH_INTERVAL 15000
/**
* Interval between direct path pushes in milliseconds if we already have a path
*/
#define ZT_DIRECT_PATH_PUSH_INTERVAL_HAVEPATH 120000
/** /**
* Time horizon for push direct paths cutoff * Time horizon for push direct paths cutoff
@ -620,16 +616,7 @@
*/ */
#define ZT_THREAD_MIN_STACK_SIZE 1048576 #define ZT_THREAD_MIN_STACK_SIZE 1048576
/* Ethernet frame types that might be relevant to us */ // Exceptions thrown in core ZT code
#define ZT_ETHERTYPE_IPV4 0x0800
#define ZT_ETHERTYPE_ARP 0x0806
#define ZT_ETHERTYPE_RARP 0x8035
#define ZT_ETHERTYPE_ATALK 0x809b
#define ZT_ETHERTYPE_AARP 0x80f3
#define ZT_ETHERTYPE_IPX_A 0x8137
#define ZT_ETHERTYPE_IPX_B 0x8138
#define ZT_ETHERTYPE_IPV6 0x86dd
#define ZT_EXCEPTION_OUT_OF_BOUNDS 100 #define ZT_EXCEPTION_OUT_OF_BOUNDS 100
#define ZT_EXCEPTION_OUT_OF_MEMORY 101 #define ZT_EXCEPTION_OUT_OF_MEMORY 101
#define ZT_EXCEPTION_PRIVATE_KEY_REQUIRED 102 #define ZT_EXCEPTION_PRIVATE_KEY_REQUIRED 102

27
node/Credential.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_CREDENTIAL_HPP #ifndef ZT_CREDENTIAL_HPP
#define ZT_CREDENTIAL_HPP #define ZT_CREDENTIAL_HPP

33
node/Dictionary.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_DICTIONARY_HPP #ifndef ZT_DICTIONARY_HPP
#define ZT_DICTIONARY_HPP #define ZT_DICTIONARY_HPP
@ -387,7 +374,7 @@ public:
return this->add(key,(value) ? "1" : "0",1); return this->add(key,(value) ? "1" : "0",1);
} }
/** /**
* Add a 64-bit integer (unsigned) as a hex value * Add a 64-bit integer (unsigned) as a hex value
*/ */
inline bool add(const char *key,uint64_t value) inline bool add(const char *key,uint64_t value)
@ -396,7 +383,7 @@ public:
return this->add(key,Utils::hex(value,tmp),-1); return this->add(key,Utils::hex(value,tmp),-1);
} }
/** /**
* Add a 64-bit integer (unsigned) as a hex value * Add a 64-bit integer (unsigned) as a hex value
*/ */
inline bool add(const char *key,int64_t value) inline bool add(const char *key,int64_t value)
@ -410,7 +397,7 @@ public:
} }
} }
/** /**
* Add a 64-bit integer (unsigned) as a hex value * Add a 64-bit integer (unsigned) as a hex value
*/ */
inline bool add(const char *key,const Address &a) inline bool add(const char *key,const Address &a)

27
node/Hashtable.hpp

@ -1,28 +1,15 @@
/* /*
* ZeroTier One - Network Virtualization Everywhere * Copyright (c)2019 ZeroTier, Inc.
* Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
* *
* This program is free software: you can redistribute it and/or modify * Use of this software is governed by the Business Source License included
* it under the terms of the GNU General Public License as published by * in the LICENSE.TXT file in the project's root directory.
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, * Change Date: 2023-01-01
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * On the date above, in accordance with the Business Source License, use
* along with this program. If not, see <http://www.gnu.org/licenses/>. * of this software will be governed by version 2.0 of the Apache License.
*
* --
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial closed-source software that incorporates or links
* directly against ZeroTier software without disclosing the source code
* of your own application.
*/ */
/****/
#ifndef ZT_HASHTABLE_HPP #ifndef ZT_HASHTABLE_HPP
#define ZT_HASHTABLE_HPP #define ZT_HASHTABLE_HPP

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save