summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--AUTHORS.md75
-rw-r--r--COPYING17
-rw-r--r--LICENSE.GPL-2339
-rw-r--r--LICENSE.GPL-3674
-rw-r--r--LICENSE.txt13
-rw-r--r--README.md2
-rw-r--r--attic/BandwidthAccount.hpp153
-rwxr-xr-xattic/decrypt32
-rwxr-xr-xattic/encrypt32
-rw-r--r--attic/rtbl/BSDRoutingTable.cpp331
-rw-r--r--attic/rtbl/BSDRoutingTable.hpp51
-rw-r--r--attic/rtbl/LinuxRoutingTable.cpp235
-rw-r--r--attic/rtbl/LinuxRoutingTable.hpp49
-rw-r--r--attic/rtbl/RoutingTable.cpp77
-rw-r--r--attic/rtbl/RoutingTable.hpp122
-rw-r--r--attic/rtbl/TestRoutingTable.cpp50
-rw-r--r--attic/rtbl/TestRoutingTable.hpp50
-rw-r--r--attic/rtbl/WindowsRoutingTable.cpp178
-rw-r--r--attic/rtbl/WindowsRoutingTable.hpp49
-rw-r--r--cluster-geo/README.md2
-rw-r--r--cluster-geo/cluster-geo/cluster-geo.js21
-rw-r--r--cluster-geo/cluster-geo/package.json2
-rw-r--r--controller/SqliteNetworkController.cpp405
-rw-r--r--controller/SqliteNetworkController.hpp44
-rw-r--r--controller/schema.sql17
-rw-r--r--controller/schema.sql.c17
-rw-r--r--examples/api/README.md26
-rw-r--r--examples/api/circuit-test-pingpong.json13
-rw-r--r--examples/api/public.json27
-rw-r--r--examples/docker/Dockerfile19
-rw-r--r--examples/docker/README.md8
-rw-r--r--examples/docker/main.sh25
-rwxr-xr-xexamples/docker/maketestenv.sh11
-rw-r--r--ext/bin/win-ui-wrapper/ZeroTier One.exebin763352 -> 0 bytes
-rw-r--r--ext/http-parser/http_parser.c144
-rw-r--r--ext/http-parser/http_parser.h60
-rw-r--r--ext/installfiles/linux/DEBIAN/control.in5
-rw-r--r--ext/installfiles/linux/RPM/README.md24
-rw-r--r--ext/installfiles/linux/RPM/zerotier-one.spec.in4
-rwxr-xr-xext/installfiles/linux/RPM/zerotier.spec194
-rwxr-xr-xext/installfiles/linux/buildinstaller.sh4
-rw-r--r--ext/installfiles/linux/install.tmpl.sh2
-rwxr-xr-xext/installfiles/linux/uninstall.sh2
-rw-r--r--ext/installfiles/windows/ZeroTier One.aip8
-rw-r--r--ext/lz4/lz4.c641
-rw-r--r--ext/lz4/lz4.h208
-rw-r--r--include/ZeroTierOne.h4
-rw-r--r--java/jni/com_zerotierone_sdk_Node.cpp9
-rw-r--r--make-linux.mk12
-rw-r--r--make-mac.mk16
-rw-r--r--netcon/Intercept.c44
-rw-r--r--netcon/Intercept.h24
-rw-r--r--netcon/LWIPStack.hpp6
-rw-r--r--netcon/README.md26
-rw-r--r--netcon/RPC.c16
-rwxr-xr-xnetcon/docker-test/build_tests.sh2
-rw-r--r--netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_dockerfile (renamed from netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/monitor_dockerfile)0
-rw-r--r--netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_entrypoint.sh (renamed from netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/monitor_entrypoint.sh)0
-rw-r--r--netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/netcon_dockerfile (renamed from netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/netcon_dockerfile)2
-rw-r--r--netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/netcon_entrypoint.sh46
-rw-r--r--netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/monitor_dockerfile24
-rw-r--r--netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/monitor_entrypoint.sh80
-rw-r--r--netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/netcon_dockerfile38
-rw-r--r--netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/netcon_entrypoint.sh (renamed from netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/netcon_entrypoint.sh)0
-rw-r--r--netcon/docker-test/python/python/monitor_dockerfile24
-rw-r--r--netcon/docker-test/python/python/monitor_entrypoint.sh80
-rw-r--r--netcon/docker-test/python/python/netcon_dockerfile38
-rw-r--r--netcon/docker-test/python/python/netcon_entrypoint.sh46
-rw-r--r--netcon/docker-test/python/python3/monitor_dockerfile24
-rw-r--r--netcon/docker-test/python/python3/monitor_entrypoint.sh80
-rw-r--r--netcon/docker-test/python/python3/netcon_dockerfile37
-rw-r--r--netcon/docker-test/python/python3/netcon_entrypoint.sh46
-rw-r--r--node/CertificateOfMembership.hpp10
-rw-r--r--node/Cluster.cpp15
-rw-r--r--node/Cluster.hpp13
-rw-r--r--node/Constants.hpp63
-rw-r--r--node/DeferredPackets.cpp48
-rw-r--r--node/DeferredPackets.hpp13
-rw-r--r--node/IncomingPacket.cpp23
-rw-r--r--node/IncomingPacket.hpp47
-rw-r--r--node/InetAddress.cpp4
-rw-r--r--node/Node.cpp11
-rw-r--r--node/Packet.hpp2
-rw-r--r--node/Path.hpp10
-rw-r--r--node/Peer.cpp115
-rw-r--r--node/Peer.hpp6
-rw-r--r--node/SelfAwareness.cpp86
-rw-r--r--node/SelfAwareness.hpp15
-rw-r--r--node/Switch.cpp470
-rw-r--r--node/Switch.hpp41
-rw-r--r--node/Utils.hpp4
-rw-r--r--one.cpp35
-rw-r--r--osdep/Binder.hpp321
-rw-r--r--osdep/Http.cpp2
-rw-r--r--osdep/LinuxEthernetTap.cpp7
-rw-r--r--osdep/Phy.hpp4
-rw-r--r--osdep/RoutingTable.cpp608
-rw-r--r--osdep/RoutingTable.hpp92
-rw-r--r--osdep/WindowsEthernetTap.cpp142
-rw-r--r--selftest.cpp4
-rw-r--r--service/OneService.cpp639
-rw-r--r--version.h2
102 files changed, 5100 insertions, 2938 deletions
diff --git a/AUTHORS.md b/AUTHORS.md
index f72b5740..6b21f572 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -1,4 +1,4 @@
-## Authors
+## Primary Authors
* ZeroTier protocol design and core network virtualization engine, ZeroTier One service, React web UI, packaging for most platforms, kitchen sink...<br>
Adam Ierymenko / adam.ierymenko@zerotier.com
@@ -6,43 +6,72 @@
* Java JNI Interface to enable Android application development, and Android app itself (code for that is elsewhere)<br>
Grant Limberg / glimberg@gmail.com
-## Contributors
+ * Network Containers for Linux, iOS, Android<br>
+ Joseph Henry / joseph.henry@zerotier.com
+
+## Third Party Contributors
* A number of fixes and improvements to the new controller, other stuff.<br>
- Kees Bos / https://github.com/keesbos
+ Kees Bos / https://github.com/keesbos/
* Debugging and testing, OpenWRT support fixes.<br>
Moritz Warning / moritzwarning@web.de
+ * Debian GNU/Linux packaging, manual pages, and license compliance edits.<br>
+ Ben Finney <ben+zerotier@benfinney.id.au>
+
* Several others made smaller contributions, which GitHub tracks here:<br>
- https://github.com/zerotier/ZeroTierOne/graphs/contributors
+ https://github.com/zerotier/ZeroTierOne/graphs/contributors/
- * Documentation additions.
-
- Ben Finney <ben+zerotier@benfinney.id.au>
+## Third-Party Code
+
+ * LZ4 compression algorithm by Yann Collet
-## Third Party Code
+ * Files: ext/lz4/*
+ * Home page: http://code.google.com/p/lz4/
+ * License grant: BSD attribution
- * LZ4 compression algorithm by Yann Collet (BSD license)<br>
- http://code.google.com/p/lz4/
+ * http-parser by Joyent, Inc. (many authors)
- * http-parser by many authors (MIT license)<br>
- https://github.com/joyent/http-parser
+ * Files: ext/http-parser/*
+ * Home page: https://github.com/joyent/http-parser/
+ * License grant: MIT/Expat
- * json-parser by James McLaughlin (BSD license)<br>
- https://github.com/udp/json-parser
+ * json-parser by James McLaughlin
- * TunTapOSX by Mattias Nissler (BSD license)<br>
- http://tuntaposx.sourceforge.net
+ * Files: ext/json-parser/*
+ * Home page: https://github.com/udp/json-parser/
+ * License grant: BSD attribution
- * tap-windows and tap-windows6 by the OpenVPN project (GPL)<br>
- https://github.com/OpenVPN/tap-windows<br>
- https://github.com/OpenVPN/tap-windows6
+ * TunTapOSX by Mattias Nissler
+
+ * Files: ext/tap-mac/tuntap/*
+ * Home page: http://tuntaposx.sourceforge.net/
+ * License grant: BSD attribution no-endorsement
+
+ * tap-windows and tap-windows6 by the OpenVPN project
+
+ * Files: windows/TapDriver6/*
+ * Home page:
+ https://github.com/OpenVPN/tap-windows/
+ https://github.com/OpenVPN/tap-windows6/
+ * License grant: GNU GPL v2
* Salsa20 stream cipher, Curve25519 elliptic curve cipher, Ed25519
digital signature algorithm, and Poly1305 MAC algorithm, all by
- Daniel J. Bernstein (public domain)<br>
- http://cr.yp.to/
+ Daniel J. Bernstein
+
+ * Files:
+ node/Salsa20.hpp
+ node/C25519.hpp
+ node/Poly1305.hpp
+ * Home page: http://cr.yp.to/
+ * License grant: public domain
+
+ * MiniUPNPC by Thomas Bernard
- * MiniUPNPC by Thomas Bernard [BSD]
- http://miniupnp.free.fr
+ * Files:
+ ext/libnatpmp/*
+ ext/miniupnpc/*
+ * Home page: http://miniupnp.free.fr/
+ * License grant: BSD attribution no-endorsement
diff --git a/COPYING b/COPYING
new file mode 100644
index 00000000..23d42dfa
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,17 @@
+ZeroTier One, an endpoint server for the ZeroTier virtual network layer.
+Copyright © 2011–2016 ZeroTier, Inc.
+
+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/>.
+
+..
+ Local variables:
+ coding: utf-8
+ mode: text
+ End:
+ vim: fileencoding=utf-8 filetype=text :
diff --git a/LICENSE.GPL-2 b/LICENSE.GPL-2
new file mode 100644
index 00000000..d159169d
--- /dev/null
+++ b/LICENSE.GPL-2
@@ -0,0 +1,339 @@
+ 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.
diff --git a/LICENSE.GPL-3 b/LICENSE.GPL-3
new file mode 100644
index 00000000..94a9ed02
--- /dev/null
+++ b/LICENSE.GPL-3
@@ -0,0 +1,674 @@
+ 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>.
diff --git a/LICENSE.txt b/LICENSE.txt
deleted file mode 100644
index 01c99074..00000000
--- a/LICENSE.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-ZeroTier One is licensed under the terms of the GNU General Public License
-version 3, which are available here:
-
-http://gplv3.fsf.org/
-
-Modification and redistribution of ZeroTier One is permitted in source form.
-Binary distribution is permitted provided all copyright notices remain
-intact and any modifications to the source code are also distributed.
-
-ZeroTier One may not be embedded into any closed-source application (e.g. via
-linking), nor may closed-source derivatives be created, without a separately
-negotiated license from ZeroTier Networks LLC. See the terms of the GPLv3 for
-details.
diff --git a/README.md b/README.md
index 123fbf01..1a93a434 100644
--- a/README.md
+++ b/README.md
@@ -152,7 +152,7 @@ For most users, it just works.
If you are running a local system firewall, we recommend adding a rule permitting UDP port 9993 inbound and outbound. If you installed binaries for Windows this should be done automatically. Other platforms might require manual editing of local firewall rules depending on your configuration.
-The Mac firewall can be founder under "Security" in System Preferences. Linux has a variety of firewall configuration systems and tools. If you're using Ubuntu's *ufw*, you can do this:
+The Mac firewall can be found under "Security" in System Preferences. Linux has a variety of firewall configuration systems and tools. If you're using Ubuntu's *ufw*, you can do this:
sudo ufw allow 9993/udp
diff --git a/attic/BandwidthAccount.hpp b/attic/BandwidthAccount.hpp
deleted file mode 100644
index 3a6432c4..00000000
--- a/attic/BandwidthAccount.hpp
+++ /dev/null
@@ -1,153 +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_BWACCOUNT_HPP
-#define ZT_BWACCOUNT_HPP
-
-#include "Constants.hpp"
-
-#include <algorithm>
-
-#include <stdint.h>
-#include <math.h>
-
-#include "Utils.hpp"
-
-#ifdef __WINDOWS__
-#define round(x) ((x-floor(x))>0.5 ? ceil(x) : floor(x))
-#endif
-
-namespace ZeroTier {
-
-/**
- * Bandwidth account used for rate limiting multicast groups
- *
- * This is used to apply a bank account model to multicast groups. Each
- * multicast packet counts against a balance, which accrues at a given
- * rate in bytes per second. Debt is possible. These parameters are
- * configurable.
- *
- * A bank account model permits bursting behavior, which correctly models
- * how OSes and apps typically use multicast. It's common for things to
- * spew lots of multicast messages at once, wait a while, then do it
- * again. A consistent bandwidth limit model doesn't fit.
- */
-class BandwidthAccount
-{
-public:
- /**
- * Create an uninitialized account
- *
- * init() must be called before this is used.
- */
- BandwidthAccount() throw() {}
-
- /**
- * Create and initialize
- *
- * @param preload Initial balance to place in account
- * @param maxb Maximum allowed balance (> 0)
- * @param acc Rate of accrual in bytes per second
- * @param now Current time
- */
- BandwidthAccount(uint32_t preload,uint32_t maxb,uint32_t acc,uint64_t now)
- throw()
- {
- init(preload,maxb,acc,now);
- }
-
- /**
- * Initialize or re-initialize account
- *
- * @param preload Initial balance to place in account
- * @param maxb Maximum allowed balance (> 0)
- * @param acc Rate of accrual in bytes per second
- * @param now Current time
- */
- inline void init(uint32_t preload,uint32_t maxb,uint32_t acc,uint64_t now)
- throw()
- {
- _lastTime = ((double)now / 1000.0);
- _balance = preload;
- _maxBalance = maxb;
- _accrual = acc;
- }
-
- /**
- * Update and retrieve balance of this account
- *
- * @param now Current time
- * @return New balance updated from current clock
- */
- inline uint32_t update(uint64_t now)
- throw()
- {
- double lt = _lastTime;
- double nowf = ((double)now / 1000.0);
- _lastTime = nowf;
- return (_balance = std::min(_maxBalance,(uint32_t)round((double)_balance + ((double)_accrual * (nowf - lt)))));
- }
-
- /**
- * Update balance and conditionally deduct
- *
- * If the deduction amount fits, it is deducted after update. Otherwise
- * balance is updated and false is returned.
- *
- * @param amt Amount to deduct
- * @param now Current time
- * @return True if amount fit within balance and was deducted
- */
- inline bool deduct(uint32_t amt,uint64_t now)
- throw()
- {
- if (update(now) >= amt) {
- _balance -= amt;
- return true;
- }
- return false;
- }
-
- /**
- * @return Most recent balance without update
- */
- inline uint32_t balance() const
- throw()
- {
- return _balance;
- }
-
-private:
- double _lastTime;
- uint32_t _balance;
- uint32_t _maxBalance;
- uint32_t _accrual;
-};
-
-} // namespace ZeroTier
-
-#endif
diff --git a/attic/decrypt b/attic/decrypt
deleted file mode 100755
index 5af3acd4..00000000
--- a/attic/decrypt
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/bin/bash
-
-export PATH=/bin:/usr/bin
-
-if [ ! -e /usr/bin/openssl ]; then
- echo $0: requires /usr/bin/openssl, please install openssl tools
- exit 1
-fi
-
-if [ "$#" -lt 1 ]; then
- echo $0: Usage: $0 '<input>' '[output]'
- exit 1
-fi
-
-if [ ! -r "$1" ]; then
- echo $0: $1 does not exist or is not readable.
- exit 1
-fi
-
-outpath=`echo "$1" | sed 's/[.]aes$//'`
-if [ "$#" -ge 2 ]; then
- outpath="$2"
-fi
-
-if [ -f "$outpath" ]; then
- echo $0: $outpath already exists, delete or rename first.
- exit 1
-fi
-
-openssl aes-256-cbc -d -salt -in "$1" -out "$outpath"
-
-echo $0: wrote "$outpath"
diff --git a/attic/encrypt b/attic/encrypt
deleted file mode 100755
index 243a46d7..00000000
--- a/attic/encrypt
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/bin/bash
-
-export PATH=/bin:/usr/bin
-
-if [ ! -e /usr/bin/openssl ]; then
- echo $0: requires /usr/bin/openssl, please install openssl tools
- exit 1
-fi
-
-if [ "$#" -lt 1 ]; then
- echo $0: Usage: $0 '<input>' '[output]'
- exit 1
-fi
-
-if [ ! -r "$1" ]; then
- echo $0: $1 does not exist or is not readable.
- exit 1
-fi
-
-outpath="$1.aes"
-if [ "$#" -ge 2 ]; then
- outpath="$2"
-fi
-
-if [ -f "$outpath" ]; then
- echo $0: $outpath already exists, delete or rename first.
- exit 1
-fi
-
-openssl aes-256-cbc -salt -in "$1" -out "$outpath"
-
-echo $0: wrote "$outpath"
diff --git a/attic/rtbl/BSDRoutingTable.cpp b/attic/rtbl/BSDRoutingTable.cpp
deleted file mode 100644
index 6d44c3ec..00000000
--- a/attic/rtbl/BSDRoutingTable.cpp
+++ /dev/null
@@ -1,331 +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 <unistd.h>
-#include <sys/param.h>
-#include <sys/sysctl.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <net/route.h>
-#include <net/if.h>
-#include <net/if_dl.h>
-#include <ifaddrs.h>
-
-#include <algorithm>
-#include <utility>
-
-#include "../node/Constants.hpp"
-#include "BSDRoutingTable.hpp"
-
-// All I wanted was the bloody rounting table. I didn't expect the Spanish inquisition.
-
-#define ZT_BSD_ROUTE_CMD "/sbin/route"
-
-namespace ZeroTier {
-
-BSDRoutingTable::BSDRoutingTable()
-{
-}
-
-BSDRoutingTable::~BSDRoutingTable()
-{
-}
-
-std::vector<RoutingTable::Entry> BSDRoutingTable::get(bool includeLinkLocal,bool includeLoopback) const
-{
- std::vector<RoutingTable::Entry> entries;
- int mib[6];
- size_t needed;
-
- mib[0] = CTL_NET;
- mib[1] = PF_ROUTE;
- mib[2] = 0;
- mib[3] = 0;
- mib[4] = NET_RT_DUMP;
- mib[5] = 0;
- if (!sysctl(mib,6,NULL,&needed,NULL,0)) {
- if (needed <= 0)
- return entries;
-
- char *buf = (char *)::malloc(needed);
- if (buf) {
- if (!sysctl(mib,6,buf,&needed,NULL,0)) {
- struct rt_msghdr *rtm;
- for(char *next=buf,*end=buf+needed;next<end;) {
- rtm = (struct rt_msghdr *)next;
- char *saptr = (char *)(rtm + 1);
- char *saend = next + rtm->rtm_msglen;
-
- if (((rtm->rtm_flags & RTF_LLINFO) == 0)&&((rtm->rtm_flags & RTF_HOST) == 0)&&((rtm->rtm_flags & RTF_UP) != 0)&&((rtm->rtm_flags & RTF_MULTICAST) == 0)) {
- RoutingTable::Entry e;
- e.deviceIndex = -9999; // unset
-
- int which = 0;
- while (saptr < saend) {
- struct sockaddr *sa = (struct sockaddr *)saptr;
- unsigned int salen = sa->sa_len;
- if (!salen)
- break;
-
- // Skip missing fields in rtm_addrs bit field
- while ((rtm->rtm_addrs & 1) == 0) {
- rtm->rtm_addrs >>= 1;
- ++which;
- if (which > 6)
- break;
- }
- if (which > 6)
- break;
-
- rtm->rtm_addrs >>= 1;
- switch(which++) {
- case 0:
- //printf("RTA_DST\n");
- if (sa->sa_family == AF_INET6) {
- struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
- // Nobody expects the Spanish inquisition!
- if ((sin6->sin6_addr.s6_addr[0] == 0xfe)&&((sin6->sin6_addr.s6_addr[1] & 0xc0) == 0x80)) {
- // Our chief weapon is... in-band signaling!
- // Seriously who in the living fuck thought this was a good idea and
- // then had the sadistic idea to not document it anywhere? Of course it's
- // not like there is any documentation on BSD sysctls anyway.
- unsigned int interfaceIndex = ((((unsigned int)sin6->sin6_addr.s6_addr[2]) << 8) & 0xff) | (((unsigned int)sin6->sin6_addr.s6_addr[3]) & 0xff);
- sin6->sin6_addr.s6_addr[2] = 0;
- sin6->sin6_addr.s6_addr[3] = 0;
- if (!sin6->sin6_scope_id)
- sin6->sin6_scope_id = interfaceIndex;
- }
- }
- e.destination.set(sa);
- break;
- case 1:
- //printf("RTA_GATEWAY\n");
- switch(sa->sa_family) {
- case AF_LINK:
- e.deviceIndex = (int)((const struct sockaddr_dl *)sa)->sdl_index;
- break;
- case AF_INET:
- case AF_INET6:
- e.gateway.set(sa);
- break;
- }
- break;
- case 2: {
- if (e.destination.isV6()) {
- salen = sizeof(struct sockaddr_in6); // Confess!
- unsigned int bits = 0;
- for(int i=0;i<16;++i) {
- unsigned char c = (unsigned char)((const struct sockaddr_in6 *)sa)->sin6_addr.s6_addr[i];
- if (c == 0xff)
- bits += 8;
- else break;
- /* must they be multiples of 8? Most of the BSD source I can find says yes..?
- else {
- while ((c & 0x80) == 0x80) {
- ++bits;
- c <<= 1;
- }
- break;
- }
- */
- }
- e.destination.setPort(bits);
- } else {
- salen = sizeof(struct sockaddr_in); // Confess!
- e.destination.setPort((unsigned int)Utils::countBits((uint32_t)((const struct sockaddr_in *)sa)->sin_addr.s_addr));
- }
- //printf("RTA_NETMASK\n");
- } break;
- /*
- case 3:
- //printf("RTA_GENMASK\n");
- break;
- case 4:
- //printf("RTA_IFP\n");
- break;
- case 5:
- //printf("RTA_IFA\n");
- break;
- case 6:
- //printf("RTA_AUTHOR\n");
- break;
- */
- }
-
- saptr += salen;
- }
-
- e.metric = (int)rtm->rtm_rmx.rmx_hopcount;
- if (e.metric < 0)
- e.metric = 0;
-
- if (((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback()))))
- entries.push_back(e);
- }
-
- next = saend;
- }
- }
-
- ::free(buf);
- }
- }
-
- for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e1(entries.begin());e1!=entries.end();++e1) {
- if ((!e1->device[0])&&(e1->deviceIndex >= 0))
- if_indextoname(e1->deviceIndex,e1->device);
- }
- for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e1(entries.begin());e1!=entries.end();++e1) {
- if ((!e1->device[0])&&(e1->gateway)) {
- int bestMetric = 9999999;
- for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e2(entries.begin());e2!=entries.end();++e2) {
- if ((e1->gateway.within(e2->destination))&&(e2->metric <= bestMetric)) {
- bestMetric = e2->metric;
- Utils::scopy(e1->device,sizeof(e1->device),e2->device);
- }
- }
- }
- }
-
- std::sort(entries.begin(),entries.end());
-
- return entries;
-}
-
-RoutingTable::Entry BSDRoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric)
-{
- if ((!gateway)&&((!device)||(!device[0])))
- return RoutingTable::Entry();
-
- std::vector<RoutingTable::Entry> rtab(get(true,true));
-
- for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
- if (e->destination == destination) {
- if (((!device)||(!device[0]))||(!strcmp(device,e->device))) {
- long p = (long)fork();
- if (p > 0) {
- int exitcode = -1;
- ::waitpid(p,&exitcode,0);
- } else if (p == 0) {
- ::close(STDOUT_FILENO);
- ::close(STDERR_FILENO);
- ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"delete",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),(const char *)0);
- ::_exit(-1);
- }
- }
- }
- }
-
- if (metric < 0)
- return RoutingTable::Entry();
-
- {
- char hcstr[64];
- Utils::snprintf(hcstr,sizeof(hcstr),"%d",metric);
- long p = (long)fork();
- if (p > 0) {
- int exitcode = -1;
- ::waitpid(p,&exitcode,0);
- } else if (p == 0) {
- ::close(STDOUT_FILENO);
- ::close(STDERR_FILENO);
- if (gateway) {
- ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"add",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),gateway.toIpString().c_str(),"-hopcount",hcstr,(const char *)0);
- } else if ((device)&&(device[0])) {
- ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"add",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),"-interface",device,"-hopcount",hcstr,(const char *)0);
- }
- ::_exit(-1);
- }
- }
-
- rtab = get(true,true);
- std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
- for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
- if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
- if ((device)&&(device[0])) {
- if (!strcmp(device,e->device)) {
- if (metric == e->metric)
- bestEntry = e;
- }
- }
- if (bestEntry == rtab.end())
- bestEntry = e;
- }
- }
- if (bestEntry != rtab.end())
- return *bestEntry;
-
- return RoutingTable::Entry();
-}
-
-} // namespace ZeroTier
-
-// Enable and build to test routing table interface
-#if 0
-using namespace ZeroTier;
-int main(int argc,char **argv)
-{
- BSDRoutingTable rt;
-
- printf("<destination> <gateway> <interface> <metric>\n");
- std::vector<RoutingTable::Entry> ents(rt.get());
- for(std::vector<RoutingTable::Entry>::iterator e(ents.begin());e!=ents.end();++e)
- printf("%s\n",e->toString().c_str());
- printf("\n");
-
- printf("adding 1.1.1.0 and 2.2.2.0...\n");
- rt.set(InetAddress("1.1.1.0",24),InetAddress("1.2.3.4",0),(const char *)0,1);
- rt.set(InetAddress("2.2.2.0",24),InetAddress(),"en0",1);
- printf("\n");
-
- printf("<destination> <gateway> <interface> <metric>\n");
- ents = rt.get();
- for(std::vector<RoutingTable::Entry>::iterator e(ents.begin());e!=ents.end();++e)
- printf("%s\n",e->toString().c_str());
- printf("\n");
-
- printf("deleting 1.1.1.0 and 2.2.2.0...\n");
- rt.set(InetAddress("1.1.1.0",24),InetAddress("1.2.3.4",0),(const char *)0,-1);
- rt.set(InetAddress("2.2.2.0",24),InetAddress(),"en0",-1);
- printf("\n");
-
- printf("<destination> <gateway> <interface> <metric>\n");
- ents = rt.get();
- for(std::vector<RoutingTable::Entry>::iterator e(ents.begin());e!=ents.end();++e)
- printf("%s\n",e->toString().c_str());
- printf("\n");
-
- return 0;
-}
-#endif
diff --git a/attic/rtbl/BSDRoutingTable.hpp b/attic/rtbl/BSDRoutingTable.hpp
deleted file mode 100644
index 97969666..00000000
--- a/attic/rtbl/BSDRoutingTable.hpp
+++ /dev/null
@@ -1,51 +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_BSDROUTINGTABLE_HPP
-#define ZT_BSDROUTINGTABLE_HPP
-
-#include "../node/RoutingTable.hpp"
-
-namespace ZeroTier {
-
-/**
- * Routing table interface for BSD with sysctl() and BSD /sbin/route
- *
- * Has currently only been tested on OSX/Darwin.
- */
-class BSDRoutingTable : public RoutingTable
-{
-public:
- BSDRoutingTable();
- virtual ~BSDRoutingTable();
- virtual std::vector<RoutingTable::Entry> get(bool includeLinkLocal = false,bool includeLoopback = false) const;
- virtual RoutingTable::Entry set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric);
-};
-
-} // namespace ZeroTier
-
-#endif
diff --git a/attic/rtbl/LinuxRoutingTable.cpp b/attic/rtbl/LinuxRoutingTable.cpp
deleted file mode 100644
index 581054e2..00000000
--- a/attic/rtbl/LinuxRoutingTable.cpp
+++ /dev/null
@@ -1,235 +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 <unistd.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <fcntl.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <ifaddrs.h>
-
-#include <algorithm>
-#include <utility>
-
-#include "../node/Constants.hpp"
-#include "../node/Utils.hpp"
-#include "LinuxRoutingTable.hpp"
-
-#define ZT_LINUX_IP_COMMAND "/sbin/ip"
-
-namespace ZeroTier {
-
-LinuxRoutingTable::LinuxRoutingTable()
-{
-}
-
-LinuxRoutingTable::~LinuxRoutingTable()
-{
-}
-
-std::vector<RoutingTable::Entry> LinuxRoutingTable::get(bool includeLinkLocal,bool includeLoopback) const
-{
- char buf[131072];
- char *stmp,*stmp2;
- std::vector<RoutingTable::Entry> entries;
-
- {
- int fd = ::open("/proc/net/route",O_RDONLY);
- if (fd <= 0)
- buf[0] = (char)0;
- else {
- int n = (int)::read(fd,buf,sizeof(buf) - 1);
- ::close(fd);
- if (n < 0) n = 0;
- buf[n] = (char)0;
- }
- }
-
- int lineno = 0;
- for(char *line=Utils::stok(buf,"\r\n",&stmp);(line);line=Utils::stok((char *)0,"\r\n",&stmp)) {
- if (lineno == 0) {
- ++lineno;
- continue; // skip header
- }
-
- char *iface = (char *)0;
- uint32_t destination = 0;
- uint32_t gateway = 0;
- int metric = 0;
- uint32_t mask = 0;
-
- int fno = 0;
- for(char *f=Utils::stok(line,"\t \r\n",&stmp2);(f);f=Utils::stok((char *)0,"\t \r\n",&stmp2)) {
- switch(fno) {
- case 0: iface = f; break;
- case 1: destination = (uint32_t)Utils::hexStrToULong(f); break;
- case 2: gateway = (uint32_t)Utils::hexStrToULong(f); break;
- case 6: metric = (int)Utils::strToInt(f); break;
- case 7: mask = (uint32_t)Utils::hexStrToULong(f); break;
- }
- ++fno;
- }
-
- if ((iface)&&(destination)) {
- RoutingTable::Entry e;
- if (destination)
- e.destination.set(&destination,4,Utils::countBits(mask));
- e.gateway.set(&gateway,4,0);
- e.deviceIndex = 0; // not used on Linux
- e.metric = metric;
- Utils::scopy(e.device,sizeof(e.device),iface);
- if ((e.destination)&&((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback())&&(strcmp(iface,"lo")))))
- entries.push_back(e);
- }
-
- ++lineno;
- }
-
- {
- int fd = ::open("/proc/net/ipv6_route",O_RDONLY);
- if (fd <= 0)
- buf[0] = (char)0;
- else {
- int n = (int)::read(fd,buf,sizeof(buf) - 1);
- ::close(fd);
- if (n < 0) n = 0;
- buf[n] = (char)0;
- }
- }
-
- for(char *line=Utils::stok(buf,"\r\n",&stmp);(line);line=Utils::stok((char *)0,"\r\n",&stmp)) {
- char *destination = (char *)0;
- unsigned int destPrefixLen = 0;
- char *gateway = (char *)0; // next hop in ipv6 terminology
- int metric = 0;
- char *device = (char *)0;
-
- int fno = 0;
- for(char *f=Utils::stok(line,"\t \r\n",&stmp2);(f);f=Utils::stok((char *)0,"\t \r\n",&stmp2)) {
- switch(fno) {
- case 0: destination = f; break;
- case 1: destPrefixLen = (unsigned int)Utils::hexStrToULong(f); break;
- case 4: gateway = f; break;
- case 5: metric = (int)Utils::hexStrToLong(f); break;
- case 9: device = f; break;
- }
- ++fno;
- }
-
- if ((device)&&(destination)) {
- unsigned char tmp[16];
- RoutingTable::Entry e;
- Utils::unhex(destination,tmp,16);
- if ((!Utils::isZero(tmp,16))&&(tmp[0] != 0xff))
- e.destination.set(tmp,16,destPrefixLen);
- Utils::unhex(gateway,tmp,16);
- e.gateway.set(tmp,16,0);
- e.deviceIndex = 0; // not used on Linux
- e.metric = metric;
- Utils::scopy(e.device,sizeof(e.device),device);
- if ((e.destination)&&((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback())&&(strcmp(device,"lo")))))
- entries.push_back(e);
- }
- }
-
- std::sort(entries.begin(),entries.end());
- return entries;
-}
-
-RoutingTable::Entry LinuxRoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric)
-{
- char metstr[128];
-
- if ((!gateway)&&((!device)||(!device[0])))
- return RoutingTable::Entry();
-
- Utils::snprintf(metstr,sizeof(metstr),"%d",metric);
-
- if (metric < 0) {
- long pid = (long)vfork();
- if (pid == 0) {
- if (gateway) {
- if ((device)&&(device[0])) {
- ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","del",destination.toString().c_str(),"via",gateway.toIpString().c_str(),"dev",device,(const char *)0);
- } else {
- ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","del",destination.toString().c_str(),"via",gateway.toIpString().c_str(),(const char *)0);
- }
- } else {
- ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","del",destination.toString().c_str(),"dev",device,(const char *)0);
- }
- ::_exit(-1);
- } else if (pid > 0) {
- int exitcode = -1;
- ::waitpid(pid,&exitcode,0);
- }
- } else {
- long pid = (long)vfork();
- if (pid == 0) {
- if (gateway) {
- if ((device)&&(device[0])) {
- ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","replace",destination.toString().c_str(),"metric",metstr,"via",gateway.toIpString().c_str(),"dev",device,(const char *)0);
- } else {
- ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","replace",destination.toString().c_str(),"metric",metstr,"via",gateway.toIpString().c_str(),(const char *)0);
- }
- } else {
- ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","replace",destination.toString().c_str(),"metric",metstr,"dev",device,(const char *)0);
- }
- ::_exit(-1);
- } else if (pid > 0) {
- int exitcode = -1;
- ::waitpid(pid,&exitcode,0);
- }
- }
-
- std::vector<RoutingTable::Entry> rtab(get(true,true));
- std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
- for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
- if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
- if ((device)&&(device[0])) {
- if (!strcmp(device,e->device)) {
- if (metric == e->metric)
- bestEntry = e;
- }
- }
- if (bestEntry == rtab.end())
- bestEntry = e;
- }
- }
- if (bestEntry != rtab.end())
- return *bestEntry;
-
- return RoutingTable::Entry();
-}
-
-} // namespace ZeroTier
diff --git a/attic/rtbl/LinuxRoutingTable.hpp b/attic/rtbl/LinuxRoutingTable.hpp
deleted file mode 100644
index 808ec7ea..00000000
--- a/attic/rtbl/LinuxRoutingTable.hpp
+++ /dev/null
@@ -1,49 +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_LINUXROUTINGTABLE_HPP
-#define ZT_LINUXROUTINGTABLE_HPP
-
-#include "../node/RoutingTable.hpp"
-
-namespace ZeroTier {
-
-/**
- * Routing table interface via /proc/net/route, /proc/net/ipv6_route, and /sbin/route command
- */
-class LinuxRoutingTable : public RoutingTable
-{
-public:
- LinuxRoutingTable();
- virtual ~LinuxRoutingTable();
- virtual std::vector<RoutingTable::Entry> get(bool includeLinkLocal = false,bool includeLoopback = false) const;
- virtual RoutingTable::Entry set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric);
-};
-
-} // namespace ZeroTier
-
-#endif
diff --git a/attic/rtbl/RoutingTable.cpp b/attic/rtbl/RoutingTable.cpp
deleted file mode 100644
index bae4bea9..00000000
--- a/attic/rtbl/RoutingTable.cpp
+++ /dev/null
@@ -1,77 +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 <stdio.h>
-#include <stdint.h>
-#include <string.h>
-#include <stdlib.h>
-
-#include "Constants.hpp"
-#include "RoutingTable.hpp"
-#include "Utils.hpp"
-
-namespace ZeroTier {
-
-std::string RoutingTable::Entry::toString() const
-{
- char tmp[1024];
- Utils::snprintf(tmp,sizeof(tmp),"%s %s %s %d",destination.toString().c_str(),((gateway) ? gateway.toIpString().c_str() : "<link>"),device,metric);
- return std::string(tmp);
-}
-
-bool RoutingTable::Entry::operator==(const Entry &re) const
-{
- return ((destination == re.destination)&&(gateway == re.gateway)&&(strcmp(device,re.device) == 0)&&(metric == re.metric));
-}
-
-bool RoutingTable::Entry::operator<(const Entry &re) const
-{
- if (destination < re.destination)
- return true;
- else if (destination == re.destination) {
- if (gateway < re.gateway)
- return true;
- else if (gateway == re.gateway) {
- int tmp = (int)::strcmp(device,re.device);
- if (tmp < 0)
- return true;
- else if (tmp == 0)
- return (metric < re.metric);
- }
- }
- return false;
-}
-
-RoutingTable::RoutingTable()
-{
-}
-
-RoutingTable::~RoutingTable()
-{
-}
-
-} // namespace ZeroTier
diff --git a/attic/rtbl/RoutingTable.hpp b/attic/rtbl/RoutingTable.hpp
deleted file mode 100644
index e1c98984..00000000
--- a/attic/rtbl/RoutingTable.hpp
+++ /dev/null
@@ -1,122 +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_ROUTINGTABLE_HPP
-#define ZT_ROUTINGTABLE_HPP
-
-#include <vector>
-#include <string>
-
-#include "InetAddress.hpp"
-#include "NonCopyable.hpp"
-
-namespace ZeroTier {
-
-/**
- * Base class for OS routing table interfaces
- */
-class RoutingTable : NonCopyable
-{
-public:
- class Entry
- {
- public:
- Entry() throw() { device[0] = (char)0; }
-
- /**
- * Destination IP and netmask bits (CIDR format)
- */
- InetAddress destination;
-
- /**
- * Gateway or null address if direct link-level route, netmask/port part of InetAddress not used
- */
- InetAddress gateway;
-
- /**
- * System device index or ID (not included in comparison operators, may not be set on all platforms)
- */
- int deviceIndex;
-
- /**
- * Metric or hop count -- higher = lower routing priority
- */
- int metric;
-
- /**
- * System device name
- */
- char device[128];
-
- /**
- * @return Human-readable representation of this route
- */
- std::string toString() const;
-
- /**
- * @return True if at least one required field is present (object is not null)
- */
- inline operator bool() const { return ((destination)||(gateway)||(device[0])); }
-
- bool operator==(const Entry &re) const;
- inline bool operator!=(const Entry &re) const { return (!(*this == re)); }
- bool operator<(const Entry &re) const;
- inline bool operator>(const Entry &re) const { return (re < *this); }
- inline bool operator<=(const Entry &re) const { return (!(re < *this)); }
- inline bool operator>=(const Entry &re) const { return (!(*this < re)); }
- };
-
- RoutingTable();
- virtual ~RoutingTable();
-
- /**
- * Get routing table
- *
- * @param includeLinkLocal If true, include link-local address routes (default: false)
- * @param includeLoopback Include loopback (default: false)
- * @return Sorted routing table entries
- */
- virtual std::vector<RoutingTable::Entry> get(bool includeLinkLocal = false,bool includeLoopback = false) const = 0;
-
- /**
- * Add or update a routing table entry
- *
- * If there is no change, the existing entry is returned. Use a value of -1
- * for metric to delete a route.
- *
- * @param destination Destination IP/netmask
- * @param gateway Gateway IP (netmask/port part unused) or NULL/zero for device-level route
- * @param device Device name (can be null for gateway routes)
- * @param metric Route metric or hop count (higher = lower priority) or negative to delete
- * @return Entry or null entry on failure (or delete)
- */
- virtual RoutingTable::Entry set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric) = 0;
-};
-
-} // namespace ZeroTier
-
-#endif
diff --git a/attic/rtbl/TestRoutingTable.cpp b/attic/rtbl/TestRoutingTable.cpp
deleted file mode 100644
index fd61b314..00000000
--- a/attic/rtbl/TestRoutingTable.cpp
+++ /dev/null
@@ -1,50 +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 "TestRoutingTable.hpp"
-
-namespace ZeroTier {
-
-TestRoutingTable::TestRoutingTable()
-{
-}
-
-TestRoutingTable::~TestRoutingTable()
-{
-}
-
-std::vector<RoutingTable::Entry> TestRoutingTable::get(bool includeLinkLocal,bool includeLoopback) const
-{
- return std::vector<RoutingTable::Entry>();
-}
-
-RoutingTable::Entry TestRoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric)
-{
- return RoutingTable::Entry();
-}
-
-} // namespace ZeroTier
diff --git a/attic/rtbl/TestRoutingTable.hpp b/attic/rtbl/TestRoutingTable.hpp
deleted file mode 100644
index 69bd3d9f..00000000
--- a/attic/rtbl/TestRoutingTable.hpp
+++ /dev/null
@@ -1,50 +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_TESTROUTINGTABLE_HPP
-#define ZT_TESTROUTINGTABLE_HPP
-
-#include "../node/RoutingTable.hpp"
-
-namespace ZeroTier {
-
-/**
- * Dummy routing table -- right now this just does nothing
- */
-class TestRoutingTable : public RoutingTable
-{
-public:
- TestRoutingTable();
- virtual ~TestRoutingTable();
-
- virtual std::vector<RoutingTable::Entry> get(bool includeLinkLocal = false,bool includeLoopback = false) const;
- virtual RoutingTable::Entry set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric);
-};
-
-} // namespace ZeroTier
-
-#endif
diff --git a/attic/rtbl/WindowsRoutingTable.cpp b/attic/rtbl/WindowsRoutingTable.cpp
deleted file mode 100644
index 00674620..00000000
--- a/attic/rtbl/WindowsRoutingTable.cpp
+++ /dev/null
@@ -1,178 +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 <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <WinSock2.h>
-#include <Windows.h>
-#include <netioapi.h>
-#include <IPHlpApi.h>
-
-#include <vector>
-
-#include "../node/Constants.hpp"
-#include "WindowsRoutingTable.hpp"
-
-namespace ZeroTier {
-
-static void _copyInetAddressToSockaddrInet(const InetAddress &a,SOCKADDR_INET &sinet)
-{
- memset(&sinet,0,sizeof(sinet));
- if (a.isV4()) {
- sinet.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)a.rawIpData());
- sinet.Ipv4.sin_family = AF_INET;
- sinet.Ipv4.sin_port = htons(a.port());
- } else if (a.isV6()) {
- memcpy(sinet.Ipv6.sin6_addr.u.Byte,a.rawIpData(),16);
- sinet.Ipv6.sin6_family = AF_INET6;
- sinet.Ipv6.sin6_port = htons(a.port());
- }
-}
-
-WindowsRoutingTable::WindowsRoutingTable()
-{
-}
-
-WindowsRoutingTable::~WindowsRoutingTable()
-{
-}
-
-std::vector<RoutingTable::Entry> WindowsRoutingTable::get(bool includeLinkLocal,bool includeLoopback) const
-{
- std::vector<RoutingTable::Entry> entries;
- PMIB_IPFORWARD_TABLE2 rtbl = NULL;
-
- if (GetIpForwardTable2(AF_UNSPEC,&rtbl) != NO_ERROR)
- return entries;
- if (!rtbl)
- return entries;
-
- for(ULONG r=0;r<rtbl->NumEntries;++r) {
- RoutingTable::Entry e;
- switch(rtbl->Table[r].DestinationPrefix.Prefix.si_family) {
- case AF_INET:
- e.destination.set(&(rtbl->Table[r].DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr),4,rtbl->Table[r].DestinationPrefix.PrefixLength);
- break;
- case AF_INET6:
- e.destination.set(rtbl->Table[r].DestinationPrefix.Prefix.Ipv6.sin6_addr.u.Byte,16,rtbl->Table[r].DestinationPrefix.PrefixLength);
- break;
- }
- switch(rtbl->Table[r].NextHop.si_family) {
- case AF_INET:
- e.gateway.set(&(rtbl->Table[r].NextHop.Ipv4.sin_addr.S_un.S_addr),4,0);
- break;
- case AF_INET6:
- e.gateway.set(rtbl->Table[r].NextHop.Ipv6.sin6_addr.u.Byte,16,0);
- break;
- }
- e.deviceIndex = (int)rtbl->Table[r].InterfaceIndex;
- e.metric = (int)rtbl->Table[r].Metric;
- ConvertInterfaceLuidToNameA(&(rtbl->Table[r].InterfaceLuid),e.device,sizeof(e.device));
- if ((e.destination)&&((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback()))))
- entries.push_back(e);
- }
-
- FreeMibTable(rtbl);
- std::sort(entries.begin(),entries.end());
- return entries;
-}
-
-RoutingTable::Entry WindowsRoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric)
-{
- NET_LUID luid;
- luid.Value = 0;
- if (ConvertInterfaceNameToLuidA(device,&luid) != NO_ERROR)
- return RoutingTable::Entry();
-
- bool needCreate = true;
- PMIB_IPFORWARD_TABLE2 rtbl = NULL;
- if (GetIpForwardTable2(AF_UNSPEC,&rtbl) != NO_ERROR)
- return RoutingTable::Entry();
- if (!rtbl)
- return RoutingTable::Entry();
- for(ULONG r=0;r<rtbl->NumEntries;++r) {
- if (rtbl->Table[r].InterfaceLuid.Value == luid.Value) {
- InetAddress rdest;
- switch(rtbl->Table[r].DestinationPrefix.Prefix.si_family) {
- case AF_INET:
- rdest.set(&(rtbl->Table[r].DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr),4,rtbl->Table[r].DestinationPrefix.PrefixLength);
- break;
- case AF_INET6:
- rdest.set(rtbl->Table[r].DestinationPrefix.Prefix.Ipv6.sin6_addr.u.Byte,16,rtbl->Table[r].DestinationPrefix.PrefixLength);
- break;
- }
- if (rdest == destination) {
- if (metric >= 0) {
- _copyInetAddressToSockaddrInet(gateway,rtbl->Table[r].NextHop);
- rtbl->Table[r].Metric = metric;
- SetIpForwardEntry2(&(rtbl->Table[r]));
- needCreate = false;
- } else {
- DeleteIpForwardEntry2(&(rtbl->Table[r]));
- FreeMibTable(rtbl);
- return RoutingTable::Entry();
- }
- }
- }
- }
- FreeMibTable(rtbl);
-
- if ((metric >= 0)&&(needCreate)) {
- MIB_IPFORWARD_ROW2 nr;
- InitializeIpForwardEntry(&nr);
- nr.InterfaceLuid.Value = luid.Value;
- _copyInetAddressToSockaddrInet(destination,nr.DestinationPrefix.Prefix);
- nr.DestinationPrefix.PrefixLength = destination.netmaskBits();
- _copyInetAddressToSockaddrInet(gateway,nr.NextHop);
- nr.Metric = metric;
- nr.Protocol = MIB_IPPROTO_NETMGMT;
- DWORD result = CreateIpForwardEntry2(&nr);
- if (result != NO_ERROR)
- return RoutingTable::Entry();
- }
-
- std::vector<RoutingTable::Entry> rtab(get(true,true));
- std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
- for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
- if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
- if ((device)&&(device[0])) {
- if (!strcmp(device,e->device)) {
- if (metric == e->metric)
- bestEntry = e;
- }
- }
- if (bestEntry == rtab.end())
- bestEntry = e;
- }
- }
- if (bestEntry != rtab.end())
- return *bestEntry;
- return RoutingTable::Entry();
-}
-
-} // namespace ZeroTier
diff --git a/attic/rtbl/WindowsRoutingTable.hpp b/attic/rtbl/WindowsRoutingTable.hpp
deleted file mode 100644
index 491c3424..00000000
--- a/attic/rtbl/WindowsRoutingTable.hpp
+++ /dev/null
@@ -1,49 +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_WINDOWSROUTINGTABLE_HPP
-#define ZT_WINDOWSROUTINGTABLE_HPP
-
-#include "../node/RoutingTable.hpp"
-
-namespace ZeroTier {
-
-/**
- * Interface to Microsoft Windows (Vista or newer) routing table
- */
-class WindowsRoutingTable : public RoutingTable
-{
-public:
- WindowsRoutingTable();
- virtual ~WindowsRoutingTable();
- virtual std::vector<RoutingTable::Entry> get(bool includeLinkLocal = false,bool includeLoopback = false) const;
- virtual RoutingTable::Entry set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric);
-};
-
-} // namespace ZeroTier
-
-#endif
diff --git a/cluster-geo/README.md b/cluster-geo/README.md
index 492ffc0d..23a097ad 100644
--- a/cluster-geo/README.md
+++ b/cluster-geo/README.md
@@ -7,6 +7,8 @@ If a cluster-mode instance detects a file in the ZeroTier home folder called *cl
IP,result code,latitude,longitude,x,y,z
+IPv6 IPs must be sent *without* compression / zero-removal.
+
The first field is the IP echoed back. The second field is 0 if the result is pending and may be ready in the future or 1 if the result is ready now. If the second field is 0 the remaining fields should be 0. Otherwise the remaining fields contain the IP's latitude, longitude, and X/Y/Z coordinates.
ZeroTier's cluster route optimization code only uses the X/Y/Z values. These are computed by this cluster-geo code as the spherical coordinates of the IP address using the Earth's center as the point of origin and using an approximation of the Earth as a sphere. This doesn't yield *exact* coordinates, but it's good enough for our purposes since the goal is to route clients to the geographically closest endpoint.
diff --git a/cluster-geo/cluster-geo/cluster-geo.js b/cluster-geo/cluster-geo/cluster-geo.js
index 1338b00b..77871fe3 100644
--- a/cluster-geo/cluster-geo/cluster-geo.js
+++ b/cluster-geo/cluster-geo/cluster-geo.js
@@ -25,7 +25,15 @@ var cache = require('levelup')(__dirname + '/cache.leveldb');
function lookup(ip,callback)
{
- cache.get(ip,function(err,cachedEntryJson) {
+ if (!ip)
+ return callback(null,null);
+
+ var ipKey = ip;
+ if ((ipKey.indexOf(':') === 4)&&(ipKey.length > 19))
+ ipKey = ipKey.substr(0,19); // we key in the cache using only the first 64 bits of IPv6 addresses
+
+ cache.get(ipKey,function(err,cachedEntryJson) {
+
if ((!err)&&(cachedEntryJson)) {
try {
let cachedEntry = JSON.parse(cachedEntryJson.toString());
@@ -40,30 +48,27 @@ function lookup(ip,callback)
} catch (e) {}
}
- cache.put(ip,JSON.stringify({
+ cache.put(ipKey,JSON.stringify({
ts: Date.now() - (CACHE_TTL - 30000), // set ts to expire in 30 seconds while the query is in progress
r: null
}),function(err) {
-
geo(ip,function(err,result) {
if (err) {
- //console.error(err);
return callback(err,null);
}
if (!result)
result = null;
- cache.put(ip,JSON.stringify({
+ cache.put(ipKey,JSON.stringify({
ts: Date.now(),
r: result
}),function(err) {
- if (err)
- console.error('Error saving to cache: '+err);
+ //if (err)
+ // console.error('Error saving to cache: '+err);
return callback(null,result);
});
});
-
});
});
diff --git a/cluster-geo/cluster-geo/package.json b/cluster-geo/cluster-geo/package.json
index 53fbc5f4..f7207a0d 100644
--- a/cluster-geo/cluster-geo/package.json
+++ b/cluster-geo/cluster-geo/package.json
@@ -10,7 +10,7 @@
"license": "GPL-3.0",
"dependencies": {
"geoip2ws": "^1.7.1",
- "leveldown": "^1.4.2",
+ "leveldown": "^1.4.4",
"levelup": "^1.3.0"
}
}
diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp
index 0e90163d..bef9cfc1 100644
--- a/controller/SqliteNetworkController.cpp
+++ b/controller/SqliteNetworkController.cpp
@@ -61,18 +61,23 @@
// Stored in database as schemaVersion key in Config.
// If not present, database is assumed to be empty and at the current schema version
// and this key/value is added automatically.
-#define ZT_NETCONF_SQLITE_SCHEMA_VERSION 1
-#define ZT_NETCONF_SQLITE_SCHEMA_VERSION_STR "1"
+#define ZT_NETCONF_SQLITE_SCHEMA_VERSION 2
+#define ZT_NETCONF_SQLITE_SCHEMA_VERSION_STR "2"
// API version reported via JSON control plane
#define ZT_NETCONF_CONTROLLER_API_VERSION 1
-// Drop requests for a given peer and network ID that occur more frequently
-// than this (ms).
+// Min duration between requests for an address/nwid combo to prevent floods
#define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
// Delay between backups in milliseconds
-#define ZT_NETCONF_BACKUP_PERIOD 120000
+#define ZT_NETCONF_BACKUP_PERIOD 300000
+
+// Number of NodeHistory entries to maintain per node and network (can be changed)
+#define ZT_NETCONF_NODE_HISTORY_LENGTH 64
+
+// Nodes are considered active if they've queried in less than this long
+#define ZT_NETCONF_NODE_ACTIVE_THRESHOLD ((ZT_NETWORK_AUTOCONF_DELAY * 2) + 5000)
namespace ZeroTier {
@@ -134,6 +139,9 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c
throw std::runtime_error("SqliteNetworkController cannot open database file");
sqlite3_busy_timeout(_db,10000);
+ sqlite3_exec(_db,"PRAGMA synchronous = OFF",0,0,0);
+ sqlite3_exec(_db,"PRAGMA journal_mode = MEMORY",0,0,0);
+
sqlite3_stmt *s = (sqlite3_stmt *)0;
if ((sqlite3_prepare_v2(_db,"SELECT v FROM Config WHERE k = 'schemaVersion';",-1,&s,(const char **)0) == SQLITE_OK)&&(s)) {
int schemaVersion = -1234;
@@ -146,8 +154,34 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c
if (schemaVersion == -1234) {
sqlite3_close(_db);
throw std::runtime_error("SqliteNetworkController schemaVersion not found in Config table (init failure?)");
+ } else if (schemaVersion == 1) {
+ // Create NodeHistory table to upgrade from version 1 to version 2
+ if (sqlite3_exec(_db,
+ "CREATE TABLE NodeHistory (\n"
+ " nodeId char(10) NOT NULL REFERENCES Node(id) ON DELETE CASCADE,\n"
+ " networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"
+ " networkVisitCounter INTEGER NOT NULL DEFAULT(0),\n"
+ " networkRequestAuthorized INTEGER NOT NULL DEFAULT(0),\n"
+ " requestTime INTEGER NOT NULL DEFAULT(0),\n"
+ " clientMajorVersion INTEGER NOT NULL DEFAULT(0),\n"
+ " clientMinorVersion INTEGER NOT NULL DEFAULT(0),\n"
+ " clientRevision INTEGER NOT NULL DEFAULT(0),\n"
+ " networkRequestMetaData VARCHAR(1024),\n"
+ " fromAddress VARCHAR(128)\n"
+ ");\n"
+ "\n"
+ "CREATE INDEX NodeHistory_nodeId ON NodeHistory (nodeId);\n"
+ "CREATE INDEX NodeHistory_networkId ON NodeHistory (networkId);\n"
+ "CREATE INDEX NodeHistory_requestTime ON NodeHistory (requestTime);\n"
+ "\n"
+ "UPDATE \"Config\" SET \"v\" = 2 WHERE \"k\" = 'schemaVersion';\n"
+ ,0,0,0) != SQLITE_OK) {
+ char err[1024];
+ Utils::snprintf(err,sizeof(err),"SqliteNetworkController cannot upgrade the database to version 2: %s",sqlite3_errmsg(_db));
+ sqlite3_close(_db);
+ throw std::runtime_error(err);
+ }
} else if (schemaVersion != ZT_NETCONF_SQLITE_SCHEMA_VERSION) {
- // Note -- this will eventually run auto-upgrades so this isn't how it'll work going forward
sqlite3_close(_db);
throw std::runtime_error("SqliteNetworkController database schema version mismatch");
}
@@ -177,6 +211,13 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c
||(sqlite3_prepare_v2(_db,"SELECT identity FROM Node WHERE id = ?",-1,&_sGetNodeIdentity,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"INSERT OR REPLACE INTO Node (id,identity) VALUES (?,?)",-1,&_sCreateOrReplaceNode,(const char **)0) != SQLITE_OK)
+ /* NodeHistory */
+ ||(sqlite3_prepare_v2(_db,"SELECT IFNULL(MAX(networkVisitCounter),0) FROM NodeHistory WHERE networkId = ? AND nodeId = ?",-1,&_sGetMaxNodeHistoryNetworkVisitCounter,(const char **)0) != SQLITE_OK)
+ ||(sqlite3_prepare_v2(_db,"INSERT INTO NodeHistory (nodeId,networkId,networkVisitCounter,networkRequestAuthorized,requestTime,clientMajorVersion,clientMinorVersion,clientRevision,networkRequestMetaData,fromAddress) VALUES (?,?,?,?,?,?,?,?,?,?)",-1,&_sAddNodeHistoryEntry,(const char **)0) != SQLITE_OK)
+ ||(sqlite3_prepare_v2(_db,"DELETE FROM NodeHistory WHERE networkId = ? AND nodeId = ? AND networkVisitCounter <= ?",-1,&_sDeleteOldNodeHistoryEntries,(const char **)0) != SQLITE_OK)
+ ||(sqlite3_prepare_v2(_db,"SELECT nodeId,requestTime,clientMajorVersion,clientMinorVersion,clientRevision,fromAddress,networkRequestAuthorized FROM NodeHistory WHERE networkId = ? AND requestTime IN (SELECT MAX(requestTime) FROM NodeHistory WHERE networkId = ? AND requestTime >= ? GROUP BY nodeId) ORDER BY nodeId ASC,requestTime DESC",-1,&_sGetActiveNodesOnNetwork,(const char **)0) != SQLITE_OK)
+ ||(sqlite3_prepare_v2(_db,"SELECT networkVisitCounter,networkRequestAuthorized,requestTime,clientMajorVersion,clientMinorVersion,clientRevision,networkRequestMetaData,fromAddress FROM NodeHistory WHERE networkId = ? AND nodeId = ? ORDER BY requestTime DESC",-1,&_sGetNodeHistory,(const char **)0) != SQLITE_OK)
+
/* Rule */
||(sqlite3_prepare_v2(_db,"SELECT etherType FROM Rule WHERE networkId = ? AND \"action\" = 'accept'",-1,&_sGetEtherTypesFromRuleTable,(const char **)0) != SQLITE_OK)
||(sqlite3_prepare_v2(_db,"INSERT INTO Rule (networkId,ruleNo,nodeId,sourcePort,destPort,vlanId,vlanPcP,etherType,macSource,macDest,ipSource,ipDest,ipTos,ipProtocol,ipSourcePort,ipDestPort,flags,invFlags,\"action\") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",-1,&_sCreateRule,(const char **)0) != SQLITE_OK)
@@ -224,9 +265,9 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c
||(sqlite3_prepare_v2(_db,"INSERT OR REPLACE INTO \"Config\" (\"k\",\"v\") VALUES (?,?)",-1,&_sSetConfig,(const char **)0) != SQLITE_OK)
) {
- //printf("%s\n",sqlite3_errmsg(_db));
+ std::string err(std::string("SqliteNetworkController unable to initialize one or more prepared statements: ") + sqlite3_errmsg(_db));
sqlite3_close(_db);
- throw std::runtime_error("SqliteNetworkController unable to initialize one or more prepared statements");
+ throw std::runtime_error(err);
}
/* Generate a 128-bit / 32-character "instance ID" if one isn't already
@@ -267,6 +308,11 @@ SqliteNetworkController::~SqliteNetworkController()
sqlite3_finalize(_sCreateMember);
sqlite3_finalize(_sGetNodeIdentity);
sqlite3_finalize(_sCreateOrReplaceNode);
+ sqlite3_finalize(_sGetMaxNodeHistoryNetworkVisitCounter);
+ sqlite3_finalize(_sAddNodeHistoryEntry);
+ sqlite3_finalize(_sDeleteOldNodeHistoryEntries);
+ sqlite3_finalize(_sGetActiveNodesOnNetwork);
+ sqlite3_finalize(_sGetNodeHistory);
sqlite3_finalize(_sGetEtherTypesFromRuleTable);
sqlite3_finalize(_sGetActiveBridges);
sqlite3_finalize(_sGetIpAssignmentsForNode);
@@ -555,9 +601,18 @@ unsigned int SqliteNetworkController::handleControlPlaneHttpPOST(
}
test->timestamp = OSUtils::now();
- _circuitTests[test->testId] = test;
+
+ _CircuitTestEntry &te = _circuitTests[test->testId];
+ te.test = test;
+ te.jsonResults = "";
+
_node->circuitTestBegin(test,&(SqliteNetworkController::_circuitTestCallback));
+ char json[1024];
+ Utils::snprintf(json,sizeof(json),"{\"testId\":\"%.16llx\"}",test->testId);
+ responseBody = json;
+ responseContentType = "application/json";
+
return 200;
} // else 404
@@ -1003,8 +1058,28 @@ unsigned int SqliteNetworkController::handleControlPlaneHttpDELETE(
void SqliteNetworkController::threadMain()
throw()
{
- uint64_t lastBackupTime = 0;
+ uint64_t lastBackupTime = OSUtils::now();
+ uint64_t lastCleanupTime = OSUtils::now();
+
while (_backupThreadRun) {
+ if ((OSUtils::now() - lastCleanupTime) >= 5000) {
+ const uint64_t now = OSUtils::now();
+ lastCleanupTime = now;
+
+ Mutex::Lock _l(_lock);
+
+ // Clean out really old circuit tests to prevent memory build-up
+ for(std::map< uint64_t,_CircuitTestEntry >::iterator ct(_circuitTests.begin());ct!=_circuitTests.end();) {
+ if (!ct->second.test) {
+ _circuitTests.erase(ct++);
+ } else if ((now - ct->second.test->timestamp) >= ZT_SQLITENETWORKCONTROLLER_CIRCUIT_TEST_TIMEOUT) {
+ _node->circuitTestEnd(ct->second.test);
+ ::free((void *)ct->second.test);
+ _circuitTests.erase(ct++);
+ } else ++ct;
+ }
+ }
+
if ((OSUtils::now() - lastBackupTime) >= ZT_NETCONF_BACKUP_PERIOD) {
lastBackupTime = OSUtils::now();
@@ -1049,6 +1124,7 @@ void SqliteNetworkController::threadMain()
OSUtils::rm(backupPath2);
::rename(backupPath,backupPath2);
}
+
Thread::sleep(250);
}
}
@@ -1171,44 +1247,36 @@ unsigned int SqliteNetworkController::_doCPGet(
(unsigned int)sqlite3_column_int(_sGetIpAssignmentsForNode2,1)
);
responseBody.append(firstIp ? "\"" : ",\"");
- firstIp = false;
responseBody.append(_jsonEscape(ip.toString()));
responseBody.push_back('"');
+ firstIp = false;
}
responseBody.append("],\n\t\"recentLog\": [");
- {
- std::map< std::pair<Address,uint64_t>,_LLEntry >::const_iterator lli(_lastLog.find(std::pair<Address,uint64_t>(Address(address),nwid)));
- if (lli != _lastLog.end()) {
- const _LLEntry &lastLogEntry = lli->second;
- uint64_t eptr = lastLogEntry.totalRequests;
- for(int k=0;k<ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;++k) {
- if (!eptr--)
- break;
- const unsigned long ptr = (unsigned long)eptr % ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;
-
- char tsbuf[64];
- Utils::snprintf(tsbuf,sizeof(tsbuf),"%llu",(unsigned long long)lastLogEntry.l[ptr].ts);
-
- responseBody.append((k == 0) ? "{" : ",{");
- responseBody.append("\"ts\":");
- responseBody.append(tsbuf);
- responseBody.append(lastLogEntry.l[ptr].authorized ? ",\"authorized\":false,\"version\":" : ",\"authorized\":true,\"version\":");
- if (lastLogEntry.l[ptr].version[0]) {
- responseBody.push_back('"');
- responseBody.append(_jsonEscape(lastLogEntry.l[ptr].version));
- responseBody.append("\",\"fromAddr\":");
- } else responseBody.append("null,\"fromAddr\":");
- if (lastLogEntry.l[ptr].fromAddr) {
- responseBody.push_back('"');
- responseBody.append(_jsonEscape(lastLogEntry.l[ptr].fromAddr.toString()));
- responseBody.append("\"}");
- } else responseBody.append("null}");
- }
- }
+ sqlite3_reset(_sGetNodeHistory);
+ sqlite3_bind_text(_sGetNodeHistory,1,nwids,16,SQLITE_STATIC);
+ sqlite3_bind_text(_sGetNodeHistory,2,addrs,10,SQLITE_STATIC);
+ bool firstHistory = true;
+ while (sqlite3_step(_sGetNodeHistory) == SQLITE_ROW) {
+ responseBody.append(firstHistory ? "{" : ",{");
+ responseBody.append("\"ts\":");
+ responseBody.append((const char *)sqlite3_column_text(_sGetNodeHistory,2));
+ responseBody.append((sqlite3_column_int(_sGetNodeHistory,1) == 0) ? ",\"authorized\":false,\"clientMajorVersion\":" : ",\"authorized\":true,\"clientMajorVersion\":");
+ responseBody.append((const char *)sqlite3_column_text(_sGetNodeHistory,3));
+ responseBody.append(",\"clientMinorVersion\":");
+ responseBody.append((const char *)sqlite3_column_text(_sGetNodeHistory,4));
+ responseBody.append(",\"clientRevision\":");
+ responseBody.append((const char *)sqlite3_column_text(_sGetNodeHistory,5));
+ responseBody.append(",\"fromAddr\":");
+ const char *fa = (const char *)sqlite3_column_text(_sGetNodeHistory,7);
+ if (fa) {
+ responseBody.push_back('"');
+ responseBody.append(_jsonEscape(fa));
+ responseBody.append("\"}");
+ } else responseBody.append("null}");
+ firstHistory = false;
}
-
responseBody.append("]\n}\n");
responseContentType = "application/json";
@@ -1220,7 +1288,7 @@ unsigned int SqliteNetworkController::_doCPGet(
sqlite3_reset(_sListNetworkMembers);
sqlite3_bind_text(_sListNetworkMembers,1,nwids,16,SQLITE_STATIC);
- responseBody.append("{");
+ responseBody.push_back('{');
bool firstMember = true;
while (sqlite3_step(_sListNetworkMembers) == SQLITE_ROW) {
responseBody.append(firstMember ? "\"" : ",\"");
@@ -1235,10 +1303,70 @@ unsigned int SqliteNetworkController::_doCPGet(
}
+ } else if ((path[2] == "active")&&(path.size() == 3)) {
+
+ sqlite3_reset(_sGetActiveNodesOnNetwork);
+ sqlite3_bind_text(_sGetActiveNodesOnNetwork,1,nwids,16,SQLITE_STATIC);
+ sqlite3_bind_text(_sGetActiveNodesOnNetwork,2,nwids,16,SQLITE_STATIC);
+ sqlite3_bind_int64(_sGetActiveNodesOnNetwork,3,(int64_t)(OSUtils::now() - ZT_NETCONF_NODE_ACTIVE_THRESHOLD));
+
+ responseBody.push_back('{');
+ bool firstMember = true;
+ uint64_t lastNodeId = 0;
+ while (sqlite3_step(_sGetActiveNodesOnNetwork) == SQLITE_ROW) {
+ const char *nodeId = (const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,0);
+ if (nodeId) {
+ const uint64_t nodeIdInt = Utils::hexStrToU64(nodeId);
+ if (nodeIdInt == lastNodeId) // technically that SQL query could (rarely) generate a duplicate for a given nodeId, in which case we want the first
+ continue;
+ lastNodeId = nodeIdInt;
+
+ responseBody.append(firstMember ? "\"" : ",\"");
+ firstMember = false;
+ responseBody.append(nodeId);
+ responseBody.append("\":{");
+ responseBody.append("\"ts\":");
+ responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,1));
+ responseBody.append((sqlite3_column_int(_sGetActiveNodesOnNetwork,6) > 0) ? ",\"authorized\":true" : ",\"authorized\":false");
+ responseBody.append(",\"clientMajorVersion\":");
+ responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,2));
+ responseBody.append(",\"clientMinorVersion\":");
+ responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,3));
+ responseBody.append(",\"clientRevision\":");
+ responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,4));
+ const char *fromAddr = (const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,5);
+ if ((fromAddr)&&(fromAddr[0])) {
+ responseBody.append(",\"fromAddr\":\"");
+ responseBody.append(_jsonEscape(fromAddr));
+ responseBody.append("\"}");
+ } else {
+ responseBody.append(",\"fromAddr\":null}");
+ }
+ }
+ }
+ responseBody.push_back('}');
+
+ responseContentType = "application/json";
+ return 200;
+
+ } else if ((path[2] == "test")&&(path.size() >= 4)) {
+
+ std::map< uint64_t,_CircuitTestEntry >::iterator cte(_circuitTests.find(Utils::hexStrToU64(path[3].c_str())));
+ if ((cte != _circuitTests.end())&&(cte->second.test)) {
+
+ responseBody = "[";
+ responseBody.append(cte->second.jsonResults);
+ responseBody.push_back(']');
+ responseContentType = "application/json";
+
+ return 200;
+
+ } // else 404
+
} // else 404
} else {
- // get network info
+
sqlite3_reset(_sGetNetworkById);
sqlite3_bind_text(_sGetNetworkById,1,nwids,16,SQLITE_STATIC);
if (sqlite3_step(_sGetNetworkById) == SQLITE_ROW) {
@@ -1541,12 +1669,15 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
}
- // Check rate limit circuit breaker to prevent flooding
const uint64_t now = OSUtils::now();
- _LLEntry &lastLogEntry = _lastLog[std::pair<Address,uint64_t>(identity.address(),nwid)];
- if ((now - lastLogEntry.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
- return NetworkController::NETCONF_QUERY_IGNORE;
- lastLogEntry.lastRequestTime = now;
+
+ // Check rate limit circuit breaker to prevent flooding
+ {
+ uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
+ if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
+ return NetworkController::NETCONF_QUERY_IGNORE;
+ lrt = now;
+ }
NetworkRecord network;
memset(&network,0,sizeof(network));
@@ -1632,18 +1763,47 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
sqlite3_step(_sIncrementMemberRevisionCounter);
}
- // Add log entry to in-memory circular log
+ // Update NodeHistory with new log entry and delete expired entries
{
- const unsigned long ptr = (unsigned long)lastLogEntry.totalRequests % ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;
- lastLogEntry.l[ptr].ts = now;
- lastLogEntry.l[ptr].fromAddr = fromAddr;
- if ((clientMajorVersion > 0)||(clientMinorVersion > 0)||(clientRevision > 0))
- Utils::snprintf(lastLogEntry.l[ptr].version,sizeof(lastLogEntry.l[ptr].version),"%u.%u.%u",clientMajorVersion,clientMinorVersion,clientRevision);
- else lastLogEntry.l[ptr].version[0] = (char)0;
- lastLogEntry.l[ptr].authorized = member.authorized;
- ++lastLogEntry.totalRequests;
- // TODO: push or save these somewhere
+ int64_t nextVC = 1;
+ sqlite3_reset(_sGetMaxNodeHistoryNetworkVisitCounter);
+ sqlite3_bind_text(_sGetMaxNodeHistoryNetworkVisitCounter,1,network.id,16,SQLITE_STATIC);
+ sqlite3_bind_text(_sGetMaxNodeHistoryNetworkVisitCounter,2,member.nodeId,10,SQLITE_STATIC);
+ if (sqlite3_step(_sGetMaxNodeHistoryNetworkVisitCounter) == SQLITE_ROW) {
+ nextVC = (int64_t)sqlite3_column_int64(_sGetMaxNodeHistoryNetworkVisitCounter,0) + 1;
+ }
+
+ std::string mdstr(metaData.toString());
+ if (mdstr.length() > 1024)
+ mdstr = mdstr.substr(0,1024);
+ std::string fastr;
+ if (fromAddr)
+ fastr = fromAddr.toString();
+
+ sqlite3_reset(_sAddNodeHistoryEntry);
+ sqlite3_bind_text(_sAddNodeHistoryEntry,1,member.nodeId,10,SQLITE_STATIC);
+ sqlite3_bind_text(_sAddNodeHistoryEntry,2,network.id,16,SQLITE_STATIC);
+ sqlite3_bind_int64(_sAddNodeHistoryEntry,3,nextVC);
+ sqlite3_bind_int(_sAddNodeHistoryEntry,4,(member.authorized ? 1 : 0));
+ sqlite3_bind_int64(_sAddNodeHistoryEntry,5,(long long)now);
+ sqlite3_bind_int(_sAddNodeHistoryEntry,6,(int)clientMajorVersion);
+ sqlite3_bind_int(_sAddNodeHistoryEntry,7,(int)clientMinorVersion);
+ sqlite3_bind_int(_sAddNodeHistoryEntry,8,(int)clientRevision);
+ sqlite3_bind_text(_sAddNodeHistoryEntry,9,mdstr.c_str(),-1,SQLITE_STATIC);
+ if (fastr.length() > 0)
+ sqlite3_bind_text(_sAddNodeHistoryEntry,10,fastr.c_str(),-1,SQLITE_STATIC);
+ else sqlite3_bind_null(_sAddNodeHistoryEntry,10);
+ sqlite3_step(_sAddNodeHistoryEntry);
+
+ nextVC -= ZT_NETCONF_NODE_HISTORY_LENGTH;
+ if (nextVC >= 0) {
+ sqlite3_reset(_sDeleteOldNodeHistoryEntries);
+ sqlite3_bind_text(_sDeleteOldNodeHistoryEntries,1,network.id,16,SQLITE_STATIC);
+ sqlite3_bind_text(_sDeleteOldNodeHistoryEntries,2,member.nodeId,10,SQLITE_STATIC);
+ sqlite3_bind_int64(_sDeleteOldNodeHistoryEntries,3,nextVC);
+ sqlite3_step(_sDeleteOldNodeHistoryEntries);
+ }
}
// Check member authorization
@@ -1701,6 +1861,7 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
netconf[ZT_NETWORKCONFIG_DICT_KEY_MULTICAST_LIMIT] = ml;
}
+ bool amActiveBridge = false;
{
std::string activeBridges;
sqlite3_reset(_sGetActiveBridges);
@@ -1711,6 +1872,8 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
if (activeBridges.length())
activeBridges.push_back(',');
activeBridges.append(ab);
+ if (!strcmp(member.nodeId,ab))
+ amActiveBridge = true;
}
if (activeBridges.length() > 1024) // sanity check -- you can't have too many active bridges at the moment
break;
@@ -1832,7 +1995,7 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
}
}
- if (!haveStaticIpAssignment) {
+ if ((!haveStaticIpAssignment)&&(!amActiveBridge)) {
// Attempt to auto-assign an IPv4 address from an available routed pool
sqlite3_reset(_sGetIpAssignmentPools);
sqlite3_bind_text(_sGetIpAssignmentPools,1,network.id,16,SQLITE_STATIC);
@@ -1846,7 +2009,7 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
uint32_t ipRangeStart = Utils::ntoh(*(reinterpret_cast<const uint32_t *>(ipRangeStartB + 12)));
uint32_t ipRangeEnd = Utils::ntoh(*(reinterpret_cast<const uint32_t *>(ipRangeEndB + 12)));
- if (ipRangeEnd < ipRangeStart)
+ if ((ipRangeEnd <= ipRangeStart)||(ipRangeStart == 0))
continue;
uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
@@ -1910,7 +2073,7 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
}
if (network.isPrivate) {
- CertificateOfMembership com(now,ZT_NETWORK_AUTOCONF_DELAY + (ZT_NETWORK_AUTOCONF_DELAY / 2),nwid,identity.address());
+ CertificateOfMembership com(now,ZT_NETWORK_COM_DEFAULT_REVISION_MAX_DELTA,nwid,identity.address());
if (com.sign(signingId)) // basically can't fail unless our identity is invalid
netconf[ZT_NETWORKCONFIG_DICT_KEY_CERTIFICATE_OF_MEMBERSHIP] = com.toString();
else {
@@ -1930,73 +2093,67 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c
void SqliteNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
{
- static Mutex circuitTestWriteLock;
-
- const uint64_t now = OSUtils::now();
+ char tmp[65535];
+ SqliteNetworkController *const self = reinterpret_cast<SqliteNetworkController *>(test->ptr);
- SqliteNetworkController *const c = reinterpret_cast<SqliteNetworkController *>(test->ptr);
- char tmp[128];
+ if (!test)
+ return;
+ if (!report)
+ return;
- std::string reportSavePath(c->_circuitTestPath);
- OSUtils::mkdir(reportSavePath);
- Utils::snprintf(tmp,sizeof(tmp),ZT_PATH_SEPARATOR_S"%.16llx",test->credentialNetworkId);
- reportSavePath.append(tmp);
- OSUtils::mkdir(reportSavePath);
- Utils::snprintf(tmp,sizeof(tmp),ZT_PATH_SEPARATOR_S"%.16llx_%.16llx",test->timestamp,test->testId);
- reportSavePath.append(tmp);
- OSUtils::mkdir(reportSavePath);
- Utils::snprintf(tmp,sizeof(tmp),ZT_PATH_SEPARATOR_S"%.16llx_%.10llx_%.10llx",now,report->upstream,report->current);
- reportSavePath.append(tmp);
+ Mutex::Lock _l(self->_lock);
+ std::map< uint64_t,_CircuitTestEntry >::iterator cte(self->_circuitTests.find(test->testId));
- {
- Mutex::Lock _l(circuitTestWriteLock);
- FILE *f = fopen(reportSavePath.c_str(),"a");
- if (!f)
- return;
- fseek(f,0,SEEK_END);
- fprintf(f,"%s{\n"
- "\t\"timestamp\": %llu,"ZT_EOL_S
- "\t\"testId\": \"%.16llx\","ZT_EOL_S
- "\t\"upstream\": \"%.10llx\","ZT_EOL_S
- "\t\"current\": \"%.10llx\","ZT_EOL_S
- "\t\"receivedTimestamp\": %llu,"ZT_EOL_S
- "\t\"remoteTimestamp\": %llu,"ZT_EOL_S
- "\t\"sourcePacketId\": \"%.16llx\","ZT_EOL_S
- "\t\"flags\": %llu,"ZT_EOL_S
- "\t\"sourcePacketHopCount\": %u,"ZT_EOL_S
- "\t\"errorCode\": %u,"ZT_EOL_S
- "\t\"vendor\": %d,"ZT_EOL_S
- "\t\"protocolVersion\": %u,"ZT_EOL_S
- "\t\"majorVersion\": %u,"ZT_EOL_S
- "\t\"minorVersion\": %u,"ZT_EOL_S
- "\t\"revision\": %u,"ZT_EOL_S
- "\t\"platform\": %d,"ZT_EOL_S
- "\t\"architecture\": %d,"ZT_EOL_S
- "\t\"receivedOnLocalAddress\": \"%s\","ZT_EOL_S
- "\t\"receivedFromRemoteAddress\": \"%s\""ZT_EOL_S
- "}",
- ((ftell(f) > 0) ? ",\n" : ""),
- (unsigned long long)report->timestamp,
- (unsigned long long)test->testId,
- (unsigned long long)report->upstream,
- (unsigned long long)report->current,
- (unsigned long long)now,
- (unsigned long long)report->remoteTimestamp,
- (unsigned long long)report->sourcePacketId,
- (unsigned long long)report->flags,
- report->sourcePacketHopCount,
- report->errorCode,
- (int)report->vendor,
- report->protocolVersion,
- report->majorVersion,
- report->minorVersion,
- report->revision,
- (int)report->platform,
- (int)report->architecture,
- reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
- reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
- fclose(f);
+ if (cte == self->_circuitTests.end()) { // sanity check: a circuit test we didn't launch?
+ self->_node->circuitTestEnd(test);
+ ::free((void *)test);
+ return;
}
+
+ Utils::snprintf(tmp,sizeof(tmp),
+ "%s{\n"
+ "\t\"timestamp\": %llu,"ZT_EOL_S
+ "\t\"testId\": \"%.16llx\","ZT_EOL_S
+ "\t\"upstream\": \"%.10llx\","ZT_EOL_S
+ "\t\"current\": \"%.10llx\","ZT_EOL_S
+ "\t\"receivedTimestamp\": %llu,"ZT_EOL_S
+ "\t\"remoteTimestamp\": %llu,"ZT_EOL_S
+ "\t\"sourcePacketId\": \"%.16llx\","ZT_EOL_S
+ "\t\"flags\": %llu,"ZT_EOL_S
+ "\t\"sourcePacketHopCount\": %u,"ZT_EOL_S
+ "\t\"errorCode\": %u,"ZT_EOL_S
+ "\t\"vendor\": %d,"ZT_EOL_S
+ "\t\"protocolVersion\": %u,"ZT_EOL_S
+ "\t\"majorVersion\": %u,"ZT_EOL_S
+ "\t\"minorVersion\": %u,"ZT_EOL_S
+ "\t\"revision\": %u,"ZT_EOL_S
+ "\t\"platform\": %d,"ZT_EOL_S
+ "\t\"architecture\": %d,"ZT_EOL_S
+ "\t\"receivedOnLocalAddress\": \"%s\","ZT_EOL_S
+ "\t\"receivedFromRemoteAddress\": \"%s\""ZT_EOL_S
+ "}",
+ ((cte->second.jsonResults.length() > 0) ? ",\n" : ""),
+ (unsigned long long)report->timestamp,
+ (unsigned long long)test->testId,
+ (unsigned long long)report->upstream,
+ (unsigned long long)report->current,
+ (unsigned long long)OSUtils::now(),
+ (unsigned long long)report->remoteTimestamp,
+ (unsigned long long)report->sourcePacketId,
+ (unsigned long long)report->flags,
+ report->sourcePacketHopCount,
+ report->errorCode,
+ (int)report->vendor,
+ report->protocolVersion,
+ report->majorVersion,
+ report->minorVersion,
+ report->revision,
+ (int)report->platform,
+ (int)report->architecture,
+ reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
+ reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
+
+ cte->second.jsonResults.append(tmp);
}
} // namespace ZeroTier
diff --git a/controller/SqliteNetworkController.hpp b/controller/SqliteNetworkController.hpp
index 0e2bb63e..11be9db4 100644
--- a/controller/SqliteNetworkController.hpp
+++ b/controller/SqliteNetworkController.hpp
@@ -44,8 +44,8 @@
// Number of in-memory last log entries to maintain per user
#define ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE 32
-// How long do circuit tests "live"? This is just to prevent buildup in memory.
-#define ZT_SQLITENETWORKCONTROLLER_CIRCUIT_TEST_TIMEOUT 300000
+// How long do circuit tests last before they're forgotten?
+#define ZT_SQLITENETWORKCONTROLLER_CIRCUIT_TEST_TIMEOUT 60000
namespace ZeroTier {
@@ -123,37 +123,16 @@ private:
std::string _circuitTestPath;
std::string _instanceId;
- // A circular buffer last log
- struct _LLEntry
+ // Circuit tests outstanding
+ struct _CircuitTestEntry
{
- _LLEntry()
- {
- for(long i=0;i<ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE;++i)
- this->l[i].ts = 0;
- this->lastRequestTime = 0;
- this->totalRequests = 0;
- }
-
- // Circular buffer of last log entries
- struct {
- uint64_t ts; // timestamp or 0 if circular buffer entry unused
- char version[64];
- InetAddress fromAddr;
- bool authorized;
- } l[ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE];
-
- // Time of last request whether successful or not
- uint64_t lastRequestTime;
-
- // Total requests by this address / network ID pair (also serves mod IN_MEMORY_LOG_SIZE as circular buffer ptr)
- uint64_t totalRequests;
+ ZT_CircuitTest *test;
+ std::string jsonResults;
};
+ std::map< uint64_t,_CircuitTestEntry > _circuitTests;
- // Last log entries by address and network ID pair
- std::map< std::pair<Address,uint64_t>,_LLEntry > _lastLog;
-
- // Circuit tests outstanding
- std::map< uint64_t,ZT_CircuitTest * > _circuitTests;
+ // Last request time by address, for rate limitation
+ std::map< std::pair<uint64_t,uint64_t>,uint64_t > _lastRequestTime;
sqlite3 *_db;
@@ -162,6 +141,11 @@ private:
sqlite3_stmt *_sCreateMember;
sqlite3_stmt *_sGetNodeIdentity;
sqlite3_stmt *_sCreateOrReplaceNode;
+ sqlite3_stmt *_sGetMaxNodeHistoryNetworkVisitCounter;
+ sqlite3_stmt *_sAddNodeHistoryEntry;
+ sqlite3_stmt *_sDeleteOldNodeHistoryEntries;
+ sqlite3_stmt *_sGetActiveNodesOnNetwork;
+ sqlite3_stmt *_sGetNodeHistory;
sqlite3_stmt *_sGetEtherTypesFromRuleTable;
sqlite3_stmt *_sGetActiveBridges;
sqlite3_stmt *_sGetIpAssignmentsForNode;
diff --git a/controller/schema.sql b/controller/schema.sql
index b6db7fa4..aff08827 100644
--- a/controller/schema.sql
+++ b/controller/schema.sql
@@ -34,6 +34,23 @@ CREATE TABLE Node (
identity varchar(4096) NOT NULL
);
+CREATE TABLE NodeHistory (
+ nodeId char(10) NOT NULL REFERENCES Node(id) ON DELETE CASCADE,
+ networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
+ networkVisitCounter INTEGER NOT NULL DEFAULT(0),
+ networkRequestAuthorized INTEGER NOT NULL DEFAULT(0),
+ requestTime INTEGER NOT NULL DEFAULT(0),
+ clientMajorVersion INTEGER NOT NULL DEFAULT(0),
+ clientMinorVersion INTEGER NOT NULL DEFAULT(0),
+ clientRevision INTEGER NOT NULL DEFAULT(0),
+ networkRequestMetaData VARCHAR(1024),
+ fromAddress VARCHAR(128)
+);
+
+CREATE INDEX NodeHistory_nodeId ON NodeHistory (nodeId);
+CREATE INDEX NodeHistory_networkId ON NodeHistory (networkId);
+CREATE INDEX NodeHistory_requestTime ON NodeHistory (requestTime);
+
CREATE TABLE Gateway (
networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,
ip blob(16) NOT NULL,
diff --git a/controller/schema.sql.c b/controller/schema.sql.c
index a5b9130b..4b524547 100644
--- a/controller/schema.sql.c
+++ b/controller/schema.sql.c
@@ -35,6 +35,23 @@
" identity varchar(4096) NOT NULL\n"\
");\n"\
"\n"\
+"CREATE TABLE NodeHistory (\n"\
+" nodeId char(10) NOT NULL REFERENCES Node(id) ON DELETE CASCADE,\n"\
+" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
+" networkVisitCounter INTEGER NOT NULL DEFAULT(0),\n"\
+" networkRequestAuthorized INTEGER NOT NULL DEFAULT(0),\n"\
+" requestTime INTEGER NOT NULL DEFAULT(0),\n"\
+" clientMajorVersion INTEGER NOT NULL DEFAULT(0),\n"\
+" clientMinorVersion INTEGER NOT NULL DEFAULT(0),\n"\
+" clientRevision INTEGER NOT NULL DEFAULT(0),\n"\
+" networkRequestMetaData VARCHAR(1024),\n"\
+" fromAddress VARCHAR(128)\n"\
+");\n"\
+"\n"\
+"CREATE INDEX NodeHistory_nodeId ON NodeHistory (nodeId);\n"\
+"CREATE INDEX NodeHistory_networkId ON NodeHistory (networkId);\n"\
+"CREATE INDEX NodeHistory_requestTime ON NodeHistory (requestTime);\n"\
+"\n"\
"CREATE TABLE Gateway (\n"\
" networkId char(16) NOT NULL REFERENCES Network(id) ON DELETE CASCADE,\n"\
" ip blob(16) NOT NULL,\n"\
diff --git a/examples/api/README.md b/examples/api/README.md
deleted file mode 100644
index 50b1b65e..00000000
--- a/examples/api/README.md
+++ /dev/null
@@ -1,26 +0,0 @@
-API Examples
-======
-
-This folder contains examples that can be posted with curl or another http query utility to a local instance.
-
-To test querying with curl:
-
- curl -H 'X-ZT1-Auth:AUTHTOKEN' http://127.0.0.1:9993/status
-
-To create a public network on a local controller (service must be built with "make ZT\_ENABLE\_NETWORK\_CONTROLLER=1"):
-
- curl -H 'X-ZT1-Auth:AUTHTOKEN' -X POST -d @public.json http://127.0.0.1:9993/controller/network/################
-
-Replace AUTHTOKEN with the contents of this instance's authtoken.secret file and ################ with a valid network ID. Its first 10 hex digits must be the ZeroTier address of the controller itself, while the last 6 hex digits can be anything. Also be sure to change the port if you have this instance listening somewhere other than 9993.
-
-After POSTing you can double check the network config with:
-
- curl -H 'X-ZT1-Auth:AUTHTOKEN' http://127.0.0.1:9993/controller/network/################
-
-Once this network is created (and if your controller is online, etc.) you can then join this network from any device anywhere in the world and it will receive a valid network configuration.
-
----
-
-**public.json**: A valid configuration for a public network that allows IPv4 and IPv6 traffic.
-
-**circuit-test-pingpong.json**: An example circuit test that can be posted to /controller/network/################/test to order a test -- you will have to edit this to insert the hops you want since the two hard coded device IDs are from our own test instances.
diff --git a/examples/api/circuit-test-pingpong.json b/examples/api/circuit-test-pingpong.json
deleted file mode 100644
index 8fcc5d94..00000000
--- a/examples/api/circuit-test-pingpong.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "hops": [
- [ "4cbc810d4c" ],
- [ "868cd1664f" ],
- [ "4cbc810d4c" ],
- [ "868cd1664f" ],
- [ "4cbc810d4c" ],
- [ "868cd1664f" ],
- [ "4cbc810d4c" ],
- [ "868cd1664f" ]
- ],
- "reportAtEveryHop": true
-}
diff --git a/examples/api/public.json b/examples/api/public.json
deleted file mode 100644
index 4317bd3e..00000000
--- a/examples/api/public.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "name": "public_test_network",
- "private": false,
- "enableBroadcast": true,
- "allowPassiveBridging": false,
- "v4AssignMode": "zt",
- "v6AssignMode": "rfc4193",
- "multicastLimit": 32,
- "relays": [],
- "gateways": [],
- "ipLocalRoutes": ["10.66.0.0/16"],
- "ipAssignmentPools": [{"ipRangeStart":"10.66.0.1","ipRangeEnd":"10.66.255.254"}],
- "rules": [
- {
- "ruleNo": 10,
- "etherType": 2048,
- "action": "accept"
- },{
- "ruleNo": 20,
- "etherType": 2054,
- "action": "accept"
- },{
- "ruleNo": 30,
- "etherType": 34525,
- "action": "accept"
- }]
-}
diff --git a/examples/docker/Dockerfile b/examples/docker/Dockerfile
deleted file mode 100644
index f1ce6bb5..00000000
--- a/examples/docker/Dockerfile
+++ /dev/null
@@ -1,19 +0,0 @@
-FROM centos:7
-
-MAINTAINER https://www.zerotier.com/
-
-RUN yum -y update && yum install -y sqlite net-tools && yum clean all
-
-EXPOSE 9993/udp
-
-RUN mkdir -p /var/lib/zerotier-one
-RUN mkdir -p /var/lib/zerotier-one/networks.d
-RUN ln -sf /var/lib/zerotier-one/zerotier-one /usr/local/bin/zerotier-cli
-RUN ln -sf /var/lib/zerotier-one/zerotier-one /usr/local/bin/zerotier-idtool
-
-ADD zerotier-one /var/lib/zerotier-one/
-
-ADD main.sh /
-RUN chmod a+x /main.sh
-
-CMD ["./main.sh"]
diff --git a/examples/docker/README.md b/examples/docker/README.md
deleted file mode 100644
index fbc93481..00000000
--- a/examples/docker/README.md
+++ /dev/null
@@ -1,8 +0,0 @@
-Simple Dockerfile Example
-======
-
-This is a simple Docker example using ZeroTier One in normal tun/tap mode. It uses a Dockerfile to build an image containing ZeroTier One and a main.sh that launches it with an identity supplied via the Docker environment via the ZEROTIER\_IDENTITY\_SECRET and ZEROTIER\_NETWORK variables. The Dockerfile assumes that the zerotier-one binary is in the build folder.
-
-This is not a very secure way to load an identity secret, but it's useful for testing since it allows you to repeatedly launch Docker containers with the same identity. For production we'd recommend using something like Hashicorp Vault, or modifying main.sh to leave identities unspecified and allow the container to generate a new identity at runtime. Then you could script approval of containers using the controller API, approving them as they launch, etc. (We are working on better ways of doing mass provisioning.)
-
-To use in normal tun/tap mode with Docker, containers must be run with the options "--device=/dev/net/tun --privileged". The main.sh script supplied here will complain and exit if these options are not present (no /dev/net/tun device).
diff --git a/examples/docker/main.sh b/examples/docker/main.sh
deleted file mode 100644
index 53fb6540..00000000
--- a/examples/docker/main.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/bin/bash
-
-export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin
-
-if [ ! -c "/dev/net/tun" ]; then
- echo 'FATAL: must be docker run with: --device=/dev/net/tun --cap-add=NET_ADMIN'
- exit 1
-fi
-
-if [ -z "$ZEROTIER_IDENTITY_SECRET" ]; then
- echo 'FATAL: ZEROTIER_IDENTITY_SECRET not set -- aborting!'
- exit 1
-fi
-
-if [ -z "$ZEROTIER_NETWORK" ]; then
- echo 'Warning: ZEROTIER_NETWORK not set, you will need to docker exec zerotier-cli to join a network.'
-else
- # The existence of a .conf will cause the service to "remember" this network
- touch /var/lib/zerotier-one/networks.d/$ZEROTIER_NETWORK.conf
-fi
-
-rm -f /var/lib/zerotier-one/identity.*
-echo "$ZEROTIER_IDENTITY_SECRET" >/var/lib/zerotier-one/identity.secret
-
-/var/lib/zerotier-one/zerotier-one
diff --git a/examples/docker/maketestenv.sh b/examples/docker/maketestenv.sh
deleted file mode 100755
index 275692e1..00000000
--- a/examples/docker/maketestenv.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/bin/bash
-
-if [ -z "$1" -o -z "$2" ]; then
- echo 'Usage: maketestenv.sh <output file e.g. test-01.env> <network ID>'
- exit 1
-fi
-
-newid=`../../zerotier-idtool generate`
-
-echo "ZEROTIER_IDENTITY_SECRET=$newid" >$1
-echo "ZEROTIER_NETWORK=$2" >>$1
diff --git a/ext/bin/win-ui-wrapper/ZeroTier One.exe b/ext/bin/win-ui-wrapper/ZeroTier One.exe
deleted file mode 100644
index 622b5b36..00000000
--- a/ext/bin/win-ui-wrapper/ZeroTier One.exe
+++ /dev/null
Binary files differ
diff --git a/ext/http-parser/http_parser.c b/ext/http-parser/http_parser.c
index aa6310f7..a113c7f5 100644
--- a/ext/http-parser/http_parser.c
+++ b/ext/http-parser/http_parser.c
@@ -400,6 +400,8 @@ enum http_host_state
, s_http_host
, s_http_host_v6
, s_http_host_v6_end
+ , s_http_host_v6_zone_start
+ , s_http_host_v6_zone
, s_http_host_port_start
, s_http_host_port
};
@@ -433,6 +435,12 @@ enum http_host_state
(IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_')
#endif
+/**
+ * Verify that a char is a valid visible (printable) US-ASCII
+ * character or %x80-FF
+ **/
+#define IS_HEADER_CHAR(ch) \
+ (ch == CR || ch == LF || ch == 9 || (ch > 31 && ch != 127))
#define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res)
@@ -637,6 +645,7 @@ size_t http_parser_execute (http_parser *parser,
const char *body_mark = 0;
const char *status_mark = 0;
enum state p_state = (enum state) parser->state;
+ const unsigned int lenient = parser->lenient_http_headers;
/* We're in an error state. Don't bother doing anything. */
if (HTTP_PARSER_ERRNO(parser) != HPE_OK) {
@@ -957,21 +966,23 @@ reexecute:
parser->method = (enum http_method) 0;
parser->index = 1;
switch (ch) {
+ case 'A': parser->method = HTTP_ACL; break;
+ case 'B': parser->method = HTTP_BIND; break;
case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break;
case 'D': parser->method = HTTP_DELETE; break;
case 'G': parser->method = HTTP_GET; break;
case 'H': parser->method = HTTP_HEAD; break;
- case 'L': parser->method = HTTP_LOCK; break;
+ case 'L': parser->method = HTTP_LOCK; /* or LINK */ break;
case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break;
case 'N': parser->method = HTTP_NOTIFY; break;
case 'O': parser->method = HTTP_OPTIONS; break;
case 'P': parser->method = HTTP_POST;
/* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */
break;
- case 'R': parser->method = HTTP_REPORT; break;
+ case 'R': parser->method = HTTP_REPORT; /* or REBIND */ break;
case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH */ break;
case 'T': parser->method = HTTP_TRACE; break;
- case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE */ break;
+ case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE, UNBIND, UNLINK */ break;
default:
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
@@ -1027,16 +1038,32 @@ reexecute:
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
}
- } else if (parser->index == 1 && parser->method == HTTP_POST) {
- if (ch == 'R') {
- parser->method = HTTP_PROPFIND; /* or HTTP_PROPPATCH */
- } else if (ch == 'U') {
- parser->method = HTTP_PUT; /* or HTTP_PURGE */
- } else if (ch == 'A') {
- parser->method = HTTP_PATCH;
- } else {
- SET_ERRNO(HPE_INVALID_METHOD);
- goto error;
+ } else if (parser->method == HTTP_REPORT) {
+ if (parser->index == 2 && ch == 'B') {
+ parser->method = HTTP_REBIND;
+ } else {
+ SET_ERRNO(HPE_INVALID_METHOD);
+ goto error;
+ }
+ } else if (parser->index == 1) {
+ if (parser->method == HTTP_POST) {
+ if (ch == 'R') {
+ parser->method = HTTP_PROPFIND; /* or HTTP_PROPPATCH */
+ } else if (ch == 'U') {
+ parser->method = HTTP_PUT; /* or HTTP_PURGE */
+ } else if (ch == 'A') {
+ parser->method = HTTP_PATCH;
+ } else {
+ SET_ERRNO(HPE_INVALID_METHOD);
+ goto error;
+ }
+ } else if (parser->method == HTTP_LOCK) {
+ if (ch == 'I') {
+ parser->method = HTTP_LINK;
+ } else {
+ SET_ERRNO(HPE_INVALID_METHOD);
+ goto error;
+ }
}
} else if (parser->index == 2) {
if (parser->method == HTTP_PUT) {
@@ -1049,6 +1076,8 @@ reexecute:
} else if (parser->method == HTTP_UNLOCK) {
if (ch == 'S') {
parser->method = HTTP_UNSUBSCRIBE;
+ } else if(ch == 'B') {
+ parser->method = HTTP_UNBIND;
} else {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
@@ -1059,6 +1088,8 @@ reexecute:
}
} else if (parser->index == 4 && parser->method == HTTP_PROPFIND && ch == 'P') {
parser->method = HTTP_PROPPATCH;
+ } else if (parser->index == 3 && parser->method == HTTP_UNLOCK && ch == 'I') {
+ parser->method = HTTP_UNLINK;
} else {
SET_ERRNO(HPE_INVALID_METHOD);
goto error;
@@ -1384,7 +1415,12 @@ reexecute:
|| c != CONTENT_LENGTH[parser->index]) {
parser->header_state = h_general;
} else if (parser->index == sizeof(CONTENT_LENGTH)-2) {
+ if (parser->flags & F_CONTENTLENGTH) {
+ SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH);
+ goto error;
+ }
parser->header_state = h_content_length;
+ parser->flags |= F_CONTENTLENGTH;
}
break;
@@ -1536,6 +1572,11 @@ reexecute:
REEXECUTE();
}
+ if (!lenient && !IS_HEADER_CHAR(ch)) {
+ SET_ERRNO(HPE_INVALID_HEADER_TOKEN);
+ goto error;
+ }
+
c = LOWER(ch);
switch (h_state) {
@@ -1703,7 +1744,10 @@ reexecute:
case s_header_almost_done:
{
- STRICT_CHECK(ch != LF);
+ if (UNLIKELY(ch != LF)) {
+ SET_ERRNO(HPE_LF_EXPECTED);
+ goto error;
+ }
UPDATE_STATE(s_header_value_lws);
break;
@@ -1782,9 +1826,17 @@ reexecute:
if (parser->flags & F_TRAILING) {
/* End of a chunked request */
- UPDATE_STATE(NEW_MESSAGE());
- CALLBACK_NOTIFY(message_complete);
- break;
+ UPDATE_STATE(s_message_done);
+ CALLBACK_NOTIFY_NOADVANCE(chunk_complete);
+ REEXECUTE();
+ }
+
+ /* Cannot use chunked encoding and a content-length header together
+ per the HTTP specification. */
+ if ((parser->flags & F_CHUNKED) &&
+ (parser->flags & F_CONTENTLENGTH)) {
+ SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH);
+ goto error;
}
UPDATE_STATE(s_headers_done);
@@ -1828,12 +1880,16 @@ reexecute:
case s_headers_done:
{
+ int hasBody;
STRICT_CHECK(ch != LF);
parser->nread = 0;
- /* Exit, the rest of the connect is in a different protocol. */
- if (parser->upgrade) {
+ hasBody = parser->flags & F_CHUNKED ||
+ (parser->content_length > 0 && parser->content_length != ULLONG_MAX);
+ if (parser->upgrade && (parser->method == HTTP_CONNECT ||
+ (parser->flags & F_SKIPBODY) || !hasBody)) {
+ /* Exit, the rest of the message is in a different protocol. */
UPDATE_STATE(NEW_MESSAGE());
CALLBACK_NOTIFY(message_complete);
RETURN((p - data) + 1);
@@ -1854,8 +1910,7 @@ reexecute:
/* Content-Length header given and non-zero */
UPDATE_STATE(s_body_identity);
} else {
- if (parser->type == HTTP_REQUEST ||
- !http_message_needs_eof(parser)) {
+ if (!http_message_needs_eof(parser)) {
/* Assume content-length 0 - read the next */
UPDATE_STATE(NEW_MESSAGE());
CALLBACK_NOTIFY(message_complete);
@@ -1915,6 +1970,10 @@ reexecute:
case s_message_done:
UPDATE_STATE(NEW_MESSAGE());
CALLBACK_NOTIFY(message_complete);
+ if (parser->upgrade) {
+ /* Exit, the rest of the message is in a different protocol. */
+ RETURN((p - data) + 1);
+ }
break;
case s_chunk_size_start:
@@ -1994,6 +2053,7 @@ reexecute:
} else {
UPDATE_STATE(s_chunk_data);
}
+ CALLBACK_NOTIFY(chunk_header);
break;
}
@@ -2033,6 +2093,7 @@ reexecute:
STRICT_CHECK(ch != LF);
parser->nread = 0;
UPDATE_STATE(s_chunk_size_start);
+ CALLBACK_NOTIFY(chunk_complete);
break;
default:
@@ -2144,13 +2205,13 @@ http_parser_settings_init(http_parser_settings *settings)
const char *
http_errno_name(enum http_errno err) {
- assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0])));
+ assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab));
return http_strerror_tab[err].name;
}
const char *
http_errno_description(enum http_errno err) {
- assert(err < (sizeof(http_strerror_tab)/sizeof(http_strerror_tab[0])));
+ assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab));
return http_strerror_tab[err].description;
}
@@ -2203,6 +2264,23 @@ http_parse_host_char(enum http_host_state s, const char ch) {
return s_http_host_v6;
}
+ if (s == s_http_host_v6 && ch == '%') {
+ return s_http_host_v6_zone_start;
+ }
+ break;
+
+ case s_http_host_v6_zone:
+ if (ch == ']') {
+ return s_http_host_v6_end;
+ }
+
+ /* FALLTHROUGH */
+ case s_http_host_v6_zone_start:
+ /* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */
+ if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' ||
+ ch == '~') {
+ return s_http_host_v6_zone;
+ }
break;
case s_http_host_port:
@@ -2221,6 +2299,7 @@ http_parse_host_char(enum http_host_state s, const char ch) {
static int
http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
+ //assert(u->field_set & (1 << UF_HOST));
enum http_host_state s;
const char *p;
@@ -2252,6 +2331,11 @@ http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
u->field_data[UF_HOST].len++;
break;
+ case s_http_host_v6_zone_start:
+ case s_http_host_v6_zone:
+ u->field_data[UF_HOST].len++;
+ break;
+
case s_http_host_port:
if (s != s_http_host_port) {
u->field_data[UF_PORT].off = p - buf;
@@ -2281,6 +2365,8 @@ http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
case s_http_host_start:
case s_http_host_v6_start:
case s_http_host_v6:
+ case s_http_host_v6_zone_start:
+ case s_http_host_v6_zone:
case s_http_host_port_start:
case s_http_userinfo:
case s_http_userinfo_start:
@@ -2292,6 +2378,11 @@ http_parse_host(const char * buf, struct http_parser_url *u, int found_at) {
return 0;
}
+void
+http_parser_url_init(struct http_parser_url *u) {
+ memset(u, 0, sizeof(*u));
+}
+
int
http_parser_parse_url(const char *buf, size_t buflen, int is_connect,
struct http_parser_url *u)
@@ -2365,7 +2456,12 @@ http_parser_parse_url(const char *buf, size_t buflen, int is_connect,
/* host must be present if there is a schema */
/* parsing http:///toto will fail */
- if ((u->field_set & ((1 << UF_SCHEMA) | (1 << UF_HOST))) != 0) {
+ if ((u->field_set & (1 << UF_SCHEMA)) &&
+ (u->field_set & (1 << UF_HOST)) == 0) {
+ return 1;
+ }
+
+ if (u->field_set & (1 << UF_HOST)) {
if (http_parse_host(buf, u, found_at) != 0) {
return 1;
}
diff --git a/ext/http-parser/http_parser.h b/ext/http-parser/http_parser.h
index 99c533ae..e33c0620 100644
--- a/ext/http-parser/http_parser.h
+++ b/ext/http-parser/http_parser.h
@@ -26,11 +26,12 @@ extern "C" {
/* Also update SONAME in the Makefile whenever you change these. */
#define HTTP_PARSER_VERSION_MAJOR 2
-#define HTTP_PARSER_VERSION_MINOR 4
-#define HTTP_PARSER_VERSION_PATCH 2
+#define HTTP_PARSER_VERSION_MINOR 6
+#define HTTP_PARSER_VERSION_PATCH 1
#include <sys/types.h>
-#if defined(_WIN32) && !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER<1600)
+#if defined(_WIN32) && !defined(__MINGW32__) && \
+ (!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
#include <BaseTsd.h>
#include <stddef.h>
typedef __int8 int8_t;
@@ -95,7 +96,7 @@ typedef int (*http_cb) (http_parser*);
XX(5, CONNECT, CONNECT) \
XX(6, OPTIONS, OPTIONS) \
XX(7, TRACE, TRACE) \
- /* webdav */ \
+ /* WebDAV */ \
XX(8, COPY, COPY) \
XX(9, LOCK, LOCK) \
XX(10, MKCOL, MKCOL) \
@@ -104,21 +105,28 @@ typedef int (*http_cb) (http_parser*);
XX(13, PROPPATCH, PROPPATCH) \
XX(14, SEARCH, SEARCH) \
XX(15, UNLOCK, UNLOCK) \
+ XX(16, BIND, BIND) \
+ XX(17, REBIND, REBIND) \
+ XX(18, UNBIND, UNBIND) \
+ XX(19, ACL, ACL) \
/* subversion */ \
- XX(16, REPORT, REPORT) \
- XX(17, MKACTIVITY, MKACTIVITY) \
- XX(18, CHECKOUT, CHECKOUT) \
- XX(19, MERGE, MERGE) \
+ XX(20, REPORT, REPORT) \
+ XX(21, MKACTIVITY, MKACTIVITY) \
+ XX(22, CHECKOUT, CHECKOUT) \
+ XX(23, MERGE, MERGE) \
/* upnp */ \
- XX(20, MSEARCH, M-SEARCH) \
- XX(21, NOTIFY, NOTIFY) \
- XX(22, SUBSCRIBE, SUBSCRIBE) \
- XX(23, UNSUBSCRIBE, UNSUBSCRIBE) \
+ XX(24, MSEARCH, M-SEARCH) \
+ XX(25, NOTIFY, NOTIFY) \
+ XX(26, SUBSCRIBE, SUBSCRIBE) \
+ XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \
/* RFC-5789 */ \
- XX(24, PATCH, PATCH) \
- XX(25, PURGE, PURGE) \
+ XX(28, PATCH, PATCH) \
+ XX(29, PURGE, PURGE) \
/* CalDAV */ \
- XX(26, MKCALENDAR, MKCALENDAR) \
+ XX(30, MKCALENDAR, MKCALENDAR) \
+ /* RFC-2068, section 19.6.1.2 */ \
+ XX(31, LINK, LINK) \
+ XX(32, UNLINK, UNLINK) \
enum http_method
{
@@ -140,11 +148,12 @@ enum flags
, F_TRAILING = 1 << 4
, F_UPGRADE = 1 << 5
, F_SKIPBODY = 1 << 6
+ , F_CONTENTLENGTH = 1 << 7
};
/* Map for errno-related constants
- *
+ *
* The provided argument should be a macro that takes 2 arguments.
*/
#define HTTP_ERRNO_MAP(XX) \
@@ -160,6 +169,8 @@ enum flags
XX(CB_body, "the on_body callback failed") \
XX(CB_message_complete, "the on_message_complete callback failed") \
XX(CB_status, "the on_status callback failed") \
+ XX(CB_chunk_header, "the on_chunk_header callback failed") \
+ XX(CB_chunk_complete, "the on_chunk_complete callback failed") \
\
/* Parsing-related errors */ \
XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \
@@ -180,6 +191,8 @@ enum flags
XX(INVALID_HEADER_TOKEN, "invalid character in header") \
XX(INVALID_CONTENT_LENGTH, \
"invalid character in content-length header") \
+ XX(UNEXPECTED_CONTENT_LENGTH, \
+ "unexpected content-length header") \
XX(INVALID_CHUNK_SIZE, \
"invalid character in chunk size header") \
XX(INVALID_CONSTANT, "invalid constant string") \
@@ -204,10 +217,11 @@ enum http_errno {
struct http_parser {
/** PRIVATE **/
unsigned int type : 2; /* enum http_parser_type */
- unsigned int flags : 7; /* F_* values from 'flags' enum; semi-public */
+ unsigned int flags : 8; /* F_* values from 'flags' enum; semi-public */
unsigned int state : 7; /* enum state from http_parser.c */
- unsigned int header_state : 8; /* enum header_state from http_parser.c */
- unsigned int index : 8; /* index into current matcher */
+ unsigned int header_state : 7; /* enum header_state from http_parser.c */
+ unsigned int index : 7; /* index into current matcher */
+ unsigned int lenient_http_headers : 1;
uint32_t nread; /* # bytes read in various scenarios */
uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */
@@ -240,6 +254,11 @@ struct http_parser_settings {
http_cb on_headers_complete;
http_data_cb on_body;
http_cb on_message_complete;
+ /* When on_chunk_header is called, the current chunk length is stored
+ * in parser->content_length.
+ */
+ http_cb on_chunk_header;
+ http_cb on_chunk_complete;
};
@@ -318,6 +337,9 @@ const char *http_errno_name(enum http_errno err);
/* Return a string description of the given error */
const char *http_errno_description(enum http_errno err);
+/* Initialize all http_parser_url members to 0 */
+void http_parser_url_init(struct http_parser_url *u);
+
/* Parse a URL; return nonzero on failure */
int http_parser_parse_url(const char *buf, size_t buflen,
int is_connect,
diff --git a/ext/installfiles/linux/DEBIAN/control.in b/ext/installfiles/linux/DEBIAN/control.in
index dab6587f..d1b5a8c1 100644
--- a/ext/installfiles/linux/DEBIAN/control.in
+++ b/ext/installfiles/linux/DEBIAN/control.in
@@ -7,5 +7,6 @@ Installed-Size: 1024
Homepage: https://github.com/zerotier/ZeroTierOne
Description: ZeroTier One network virtualization service
ZeroTier One is a fast, secure, and easy to use peer to peer network
- virtualization engine. Visit https://www.zerotier.com/ for more
- information.
+ virtualization engine that provides global-scale software defined
+ networking to any device or application. Visit https://www.zerotier.com/
+ for more information.
diff --git a/ext/installfiles/linux/RPM/README.md b/ext/installfiles/linux/RPM/README.md
new file mode 100644
index 00000000..21ad0a1b
--- /dev/null
+++ b/ext/installfiles/linux/RPM/README.md
@@ -0,0 +1,24 @@
+This folder contains two spec files which enable building of various RPM packages for ZeroTier.
+
+#zerotier-one.spec.in
+This file contains the information to build an RPM from the bash based binary installer of ZeroTier. The resulting RPM cannot be recompiled to different architectures.
+
+#zerotier.spec
+This spec file is a “standard” RPM spec file. It fits to the common rpmbuild process, SRPM and differnt architectures are supported too. The spec file can be used to build two packages: the standard zerotier and the zerotier-controller. It supports some of the build options exposed in the original Linux makefile:
+
+> `rpmbuild -ba zerotier.spec` #builds the standard zerotier package, this is what you need in most of the cases
+
+> `rpmbuild -ba zerotier.spec --with controller` #builds the zerotier-controller package
+
+> `rpmbuild -ba zerotier.spec --with debug` #builds the zerotier package with debug enable<>d
+
+> `rpmbuild -ba zerotier.spec --with miniupnpc` #builds the zerotier package with miniupnpc enabled
+
+> `rpmbuild -ba zerotier.spec --with cluster` #builds the zerotier package with cluster enabled
+
+
+####Build environment preparation
+As zerotier is not distributed in tar.gz format at the moment, the %prep section of the spec file takes care about the prepartion of an rpmbuild compatible tar.gz.
+
+
+
diff --git a/ext/installfiles/linux/RPM/zerotier-one.spec.in b/ext/installfiles/linux/RPM/zerotier-one.spec.in
index a5445ba5..1ec3d42a 100644
--- a/ext/installfiles/linux/RPM/zerotier-one.spec.in
+++ b/ext/installfiles/linux/RPM/zerotier-one.spec.in
@@ -21,11 +21,11 @@ mkdir -p /var/lib/zerotier-one/updates.d
%post
chmod 0755 /var/lib/zerotier-one/updates.d/__INSTALLER__
-/var/lib/zerotier-one/updates.d/__INSTALLER__
+/var/lib/zerotier-one/updates.d/__INSTALLER__ >>/dev/null 2>&1
%preun
if [ "$1" -lt 1 ]; then
- /var/lib/zerotier-one/uninstall.sh
+ /var/lib/zerotier-one/uninstall.sh >>/dev/null 2>&1
fi
%clean
diff --git a/ext/installfiles/linux/RPM/zerotier.spec b/ext/installfiles/linux/RPM/zerotier.spec
new file mode 100755
index 00000000..41230f0e
--- /dev/null
+++ b/ext/installfiles/linux/RPM/zerotier.spec
@@ -0,0 +1,194 @@
+# add --with controller option to build controller (builds zerotier-controller package)
+%bcond_with controller
+# add --with miniupnpc option to enable the miniupnpc option during build
+%bcond_with miniupnpc
+# add --with cluster option to enable the cluster option during build
+%bcond_with cluster
+# add --with debug option to enable the debug option during build
+%bcond_with debug
+%if %{with controller}
+Name:zerotier-controller
+Conflicts:zerotier
+%else
+Name:zerotier
+Conflicts:zerotier-controller
+%endif
+Version: 1.1.4
+Release: 1
+Summary: Network Virtualization Everywhere https://www.zerotier.com/
+Group: network
+License: GPLv3
+BuildRoot: %{_tmppath}/%{name}-root
+Provides: zerotier-one
+Source0: http:///download/%{name}-%{version}.tar.gz
+BuildRequires: gcc-c++
+BuildRequires: make
+BuildRequires: gcc
+%if %{with server}
+BuildRequires: sqlite-devel
+BuildRequires: wget
+BuildRequires: unzip
+Requires: sqlite
+%endif
+%description
+ZeroTier One creates virtual Ethernet networks that work anywhere and everywhere.
+Visit https://www.zerotier.com/ for more information.
+
+%prep
+cd `mktemp -d`
+wget -O master.zip https://github.com/zerotier/ZeroTierOne/archive/master.zip
+unzip master.zip
+mv ZeroTierOne-master zerotier-1.1.4
+ln -s zerotier-1.1.4 zerotier-controller-1.1.4
+tar zcvf zerotier-1.1.4.tar.gz zerotier-1.1.4 zerotier-controller-1.1.4
+ln -s zerotier-1.1.4.tar.gz zerotier-controller-1.1.4.tar.gz
+mv zero*.tar.gz ~/rpmbuild/SOURCES
+cd -
+%setup -q
+
+%build
+%if %{with miniupnpc}
+ZT_USE_MINIUPNPC=1; export ZT_USE_MINIUPNPC;
+%endif
+
+%if %{with controller}
+ZT_ENABLE_NETWORK_CONTROLLER=1; export ZT_ENABLE_NETWORK_CONTROLLER;
+%endif
+
+%if %{with cluster}
+export ZT_ENABLE_CLUSTER=1
+%endif
+
+%if %{with debug}
+export ZT_DEBUG=1
+%endif
+
+make
+
+%install
+
+
+rm -rf $RPM_BUILD_ROOT
+rm -f $RPM_BUILD_ROOT%{_prefix}/bin/zerotier-idtool $RPM_BUILD_ROOT%{_prefix}/bin/zerotier-idtool
+echo 'Install...'
+mkdir -p $RPM_BUILD_ROOT%{_vardir}/lib/zerotier-one/initfiles/{init.d,systemd}
+install -m 0755 -D zerotier-one -t $RPM_BUILD_ROOT%{_vardir}/lib/zerotier-one/
+install -m 0755 -D ext/installfiles/linux/init.d/* -t $RPM_BUILD_ROOT%{_vardir}/lib/zerotier-one/initfiles/init.d/
+install -m 0755 -D ext/installfiles/linux/systemd/* -t $RPM_BUILD_ROOT%{_vardir}/lib/zerotier-one/initfiles/systemd/
+
+
+
+%posttrans
+echo -n 'Getting version of new install... '
+newVersion=`/var/lib/zerotier-one/zerotier-one -v`
+echo $newVersion
+
+echo 'Creating symlinks...'
+
+rm -f /usr/bin/zerotier-cli /usr/bin/zerotier-idtool
+ln -sf /var/lib/zerotier-one/zerotier-one /usr/bin/zerotier-cli
+ln -sf /var/lib/zerotier-one/zerotier-one /usr/bin/zerotier-idtool
+echo 'Installing zerotier-one service...'
+
+SYSTEMDUNITDIR=
+if [ -e /bin/systemctl -o -e /usr/bin/systemctl -o -e /usr/local/bin/systemctl -o -e /sbin/systemctl -o -e /usr/sbin/systemctl ]; then
+ # Second check: test if systemd appears to actually be running. Apparently Ubuntu
+ # thought it was a good idea to ship with systemd installed but not used. Issue #133
+ if [ -d /var/run/systemd/system -o -d /run/systemd/system ]; then
+ if [ -e /usr/bin/pkg-config ]; then
+ SYSTEMDUNITDIR=`/usr/bin/pkg-config systemd --variable=systemdsystemunitdir`
+ fi
+ if [ -z "$SYSTEMDUNITDIR" -o ! -d "$SYSTEMDUNITDIR" ]; then
+ if [ -d /usr/lib/systemd/system ]; then
+ SYSTEMDUNITDIR=/usr/lib/systemd/system
+ fi
+ if [ -d /etc/systemd/system ]; then
+ SYSTEMDUNITDIR=/etc/systemd/system
+ fi
+ fi
+ fi
+fi
+
+if [ -n "$SYSTEMDUNITDIR" -a -d "$SYSTEMDUNITDIR" ]; then
+ # SYSTEMD
+
+ # If this was updated or upgraded from an init.d based system, clean up the old
+ # init.d stuff before installing directly via systemd.
+ if [ -f /etc/init.d/zerotier-one ]; then
+ if [ -e /sbin/chkconfig -o -e /usr/sbin/chkconfig -o -e /bin/chkconfig -o -e /usr/bin/chkconfig ]; then
+ chkconfig zerotier-one off
+ fi
+ rm -f /etc/init.d/zerotier-one
+ fi
+
+ cp -f /var/lib/zerotier-one/initfiles/systemd/zerotier-one.service "$SYSTEMDUNITDIR/zerotier-one.service"
+ chown 0 "$SYSTEMDUNITDIR/zerotier-one.service"
+ chgrp 0 "$SYSTEMDUNITDIR/zerotier-one.service"
+ chmod 0755 "$SYSTEMDUNITDIR/zerotier-one.service"
+
+ systemctl enable zerotier-one.service
+
+ echo
+ echo 'Done! Installed and service configured to start at system boot.'
+ echo
+ echo "To start now or restart the service if it's already running:"
+ echo ' sudo systemctl restart zerotier-one.service'
+else
+ # SYSV INIT -- also covers upstart which supports SysVinit backward compatibility
+
+ cp -f /var/lib/zerotier-one/initfiles/init.d/zerotier-one /etc/init.d/zerotier-one
+ chmod 0755 /etc/init.d/zerotier-one
+
+ if [ -f /sbin/chkconfig -o -f /usr/sbin/chkconfig -o -f /usr/bin/chkconfig -o -f /bin/chkconfig ]; then
+ chkconfig zerotier-one on
+ else
+ # Yes Virginia, some systems lack chkconfig.
+ if [ -d /etc/rc0.d ]; then
+ rm -f /etc/rc0.d/???zerotier-one
+ ln -sf /etc/init.d/zerotier-one /etc/rc0.d/K89zerotier-one
+ fi
+ if [ -d /etc/rc1.d ]; then
+ rm -f /etc/rc1.d/???zerotier-one
+ ln -sf /etc/init.d/zerotier-one /etc/rc1.d/K89zerotier-one
+ fi
+ if [ -d /etc/rc2.d ]; then
+ rm -f /etc/rc2.d/???zerotier-one
+ ln -sf /etc/init.d/zerotier-one /etc/rc2.d/S11zerotier-one
+ fi
+ if [ -d /etc/rc3.d ]; then
+ rm -f /etc/rc3.d/???zerotier-one
+ ln -sf /etc/init.d/zerotier-one /etc/rc3.d/S11zerotier-one
+ fi
+ if [ -d /etc/rc4.d ]; then
+ rm -f /etc/rc4.d/???zerotier-one
+ ln -sf /etc/init.d/zerotier-one /etc/rc4.d/S11zerotier-one
+ fi
+ if [ -d /etc/rc5.d ]; then
+ rm -f /etc/rc5.d/???zerotier-one
+ ln -sf /etc/init.d/zerotier-one /etc/rc5.d/S11zerotier-one
+ fi
+ if [ -d /etc/rc6.d ]; then
+ rm -f /etc/rc6.d/???zerotier-one
+ ln -sf /etc/init.d/zerotier-one /etc/rc6.d/K89zerotier-one
+ fi
+ fi
+ echo
+ echo 'Done! Installed and service configured to start at system boot.'
+ echo
+ echo "To start now or restart the service if it's already running:"
+ echo ' sudo service zerotier-one restart'
+fi
+%preun
+/sbin/chkconfig --del zerotier-one
+rm -f /usr/bin/zerotier-cli /usr/bin/zerotier-idtool
+
+%clean
+rm -rf $RPM_BUILD_ROOT
+%files
+%{_vardir}/lib/zerotier-one/zerotier-one
+%{_vardir}/lib/zerotier-one/initfiles/systemd/zerotier-one.service
+%{_vardir}/lib/zerotier-one/initfiles/init.d/zerotier-one
+
+%changelog
+* Fri Feb 26 2016 Kristof Imre Szabo <kristof.szabo@lxsystems.de> 1.1.4-1
+- initial package
diff --git a/ext/installfiles/linux/buildinstaller.sh b/ext/installfiles/linux/buildinstaller.sh
index 1f6f8935..21f2f73e 100755
--- a/ext/installfiles/linux/buildinstaller.sh
+++ b/ext/installfiles/linux/buildinstaller.sh
@@ -91,14 +91,14 @@ case "$system" in
rm -f "${debfolder}/postinst" "${debfolder}/prerm"
echo '#!/bin/bash' >${debfolder}/postinst
- echo "/var/lib/zerotier-one/updates.d/${targ}" >>${debfolder}/postinst
+ echo "/var/lib/zerotier-one/updates.d/${targ} >>/dev/null 2>&1" >>${debfolder}/postinst
echo "/bin/rm -f /var/lib/zerotier-one/updates.d/*" >>${debfolder}/postinst
chmod a+x ${debfolder}/postinst
echo '#!/bin/bash' >${debfolder}/prerm
echo 'export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin' >>${debfolder}/prerm
echo 'if [ "$1" != "upgrade" ]; then' >>${debfolder}/prerm
- echo ' /var/lib/zerotier-one/uninstall.sh' >>${debfolder}/prerm
+ echo ' /var/lib/zerotier-one/uninstall.sh >>/dev/null 2>&1' >>${debfolder}/prerm
echo 'fi' >>${debfolder}/prerm
chmod a+x ${debfolder}/prerm
diff --git a/ext/installfiles/linux/install.tmpl.sh b/ext/installfiles/linux/install.tmpl.sh
index 24425cbb..2d18d24c 100644
--- a/ext/installfiles/linux/install.tmpl.sh
+++ b/ext/installfiles/linux/install.tmpl.sh
@@ -115,7 +115,7 @@ if [ -n "$SYSTEMDUNITDIR" -a -d "$SYSTEMDUNITDIR" ]; then
cp -f /tmp/systemd_zerotier-one.service "$SYSTEMDUNITDIR/zerotier-one.service"
chown 0 "$SYSTEMDUNITDIR/zerotier-one.service"
chgrp 0 "$SYSTEMDUNITDIR/zerotier-one.service"
- chmod 0755 "$SYSTEMDUNITDIR/zerotier-one.service"
+ chmod 0644 "$SYSTEMDUNITDIR/zerotier-one.service"
rm -f /tmp/systemd_zerotier-one.service /tmp/init.d_zerotier-one
systemctl enable zerotier-one.service
diff --git a/ext/installfiles/linux/uninstall.sh b/ext/installfiles/linux/uninstall.sh
index bfc7ee6b..d9495a18 100755
--- a/ext/installfiles/linux/uninstall.sh
+++ b/ext/installfiles/linux/uninstall.sh
@@ -59,7 +59,7 @@ fi
echo "Erasing binary and support files..."
if [ -d /var/lib/zerotier-one ]; then
cd /var/lib/zerotier-one
- rm -rf zerotier-one *.persist identity.public *.log *.pid *.sh updates.d networks.d iddb.d root-topology
+ rm -rf zerotier-one *.persist identity.public *.log *.pid *.sh updates.d networks.d iddb.d root-topology ui
fi
echo "Erasing anything installed into system bin directories..."
diff --git a/ext/installfiles/windows/ZeroTier One.aip b/ext/installfiles/windows/ZeroTier One.aip
index 43d3d8c9..d8a99c3d 100644
--- a/ext/installfiles/windows/ZeroTier One.aip
+++ b/ext/installfiles/windows/ZeroTier One.aip
@@ -26,10 +26,10 @@
<ROW Property="CTRLS" Value="2"/>
<ROW Property="MSIFASTINSTALL" MultiBuildValue="DefaultBuild:2"/>
<ROW Property="Manufacturer" Value="ZeroTier, Inc."/>
- <ROW Property="ProductCode" Value="1033:{21557450-C8FD-49C9-AB47-BCAB4DA31EED} " Type="16"/>
+ <ROW Property="ProductCode" Value="1033:{A6D97FB1-02FA-4042-A0EE-A080D53CDBBF} " Type="16"/>
<ROW Property="ProductLanguage" Value="1033"/>
<ROW Property="ProductName" Value="ZeroTier One"/>
- <ROW Property="ProductVersion" Value="1.1.2" Type="32"/>
+ <ROW Property="ProductVersion" Value="1.1.5" Type="32"/>
<ROW Property="REBOOT" MultiBuildValue="DefaultBuild:ReallySuppress"/>
<ROW Property="RUNAPPLICATION" Value="1" Type="4"/>
<ROW Property="SecureCustomProperties" Value="OLDPRODUCTS;AI_NEWERPRODUCTFOUND"/>
@@ -59,7 +59,7 @@
<ROW Directory="x86_Dir" Directory_Parent="tapwindows_Dir" DefaultDir="x86"/>
</COMPONENT>
<COMPONENT cid="caphyon.advinst.msicomp.MsiCompsComponent">
- <ROW Component="AI_CustomARPName" ComponentId="{0F49E5E5-7D43-4204-A667-51FDF0BA9549}" Directory_="APPDIR" Attributes="4" KeyPath="DisplayName" Options="1"/>
+ <ROW Component="AI_CustomARPName" ComponentId="{738BDE1C-E12F-4DFB-B279-9038EECEFF45}" 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="Newtonsoft.Json.dll" ComponentId="{0B2F229D-5425-42FB-9E28-F6D25AB2B4B5}" Directory_="APPDIR" Attributes="0" KeyPath="Newtonsoft.Json.dll"/>
<ROW Component="ProductInformation" ComponentId="{DB078D04-EA8E-4A7C-9001-89BAD932F9D9}" Directory_="APPDIR" Attributes="4" KeyPath="Version"/>
@@ -338,7 +338,7 @@
<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 cid="caphyon.advinst.msicomp.XmlElementComponent">
- <ROW XmlElement="swidbuild" ParentElement="swidnumeric" Name="swid:build" Condition="1" Order="2" Flags="14" Text="2"/>
+ <ROW XmlElement="swidbuild" ParentElement="swidnumeric" Name="swid:build" Condition="1" Order="2" Flags="14" Text="5"/>
<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="swidminor" ParentElement="swidnumeric" Name="swid:minor" Condition="1" Order="1" Flags="14" Text="1"/>
diff --git a/ext/lz4/lz4.c b/ext/lz4/lz4.c
index 881d1af0..08cf6b5c 100644
--- a/ext/lz4/lz4.c
+++ b/ext/lz4/lz4.c
@@ -34,7 +34,7 @@
/**************************************
- Tuning parameters
+* Tuning parameters
**************************************/
/*
* HEAPMODE :
@@ -44,51 +44,16 @@
#define HEAPMODE 0
/*
- * CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS :
- * By default, the source code expects the compiler to correctly optimize
- * 4-bytes and 8-bytes read on architectures able to handle it efficiently.
- * This is not always the case. In some circumstances (ARM notably),
- * the compiler will issue cautious code even when target is able to correctly handle unaligned memory accesses.
- *
- * You can force the compiler to use unaligned memory access by uncommenting the line below.
- * One of the below scenarios will happen :
- * 1 - Your target CPU correctly handle unaligned access, and was not well optimized by compiler (good case).
- * You will witness large performance improvements (+50% and up).
- * Keep the line uncommented and send a word to upstream (https://groups.google.com/forum/#!forum/lz4c)
- * The goal is to automatically detect such situations by adding your target CPU within an exception list.
- * 2 - Your target CPU correctly handle unaligned access, and was already already optimized by compiler
- * No change will be experienced.
- * 3 - Your target CPU inefficiently handle unaligned access.
- * You will experience a performance loss. Comment back the line.
- * 4 - Your target CPU does not handle unaligned access.
- * Program will crash.
- * If uncommenting results in better performance (case 1)
- * please report your configuration to upstream (https://groups.google.com/forum/#!forum/lz4c)
- * This way, an automatic detection macro can be added to match your case within later versions of the library.
+ * ACCELERATION_DEFAULT :
+ * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0
*/
-/* #define CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS 1 */
+#define ACCELERATION_DEFAULT 1
/**************************************
- CPU Feature Detection
+* CPU Feature Detection
**************************************/
/*
- * Automated efficient unaligned memory access detection
- * Based on known hardware architectures
- * This list will be updated thanks to feedbacks
- */
-#if defined(CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS) \
- || defined(__ARM_FEATURE_UNALIGNED) \
- || defined(__i386__) || defined(__x86_64__) \
- || defined(_M_IX86) || defined(_M_X64) \
- || defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_8__) \
- || (defined(_M_ARM) && (_M_ARM >= 7))
-# define LZ4_UNALIGNED_ACCESS 1
-#else
-# define LZ4_UNALIGNED_ACCESS 0
-#endif
-
-/*
* LZ4_FORCE_SW_BITCOUNT
* Define this parameter if your target system or compiler does not support hardware bit count
*/
@@ -98,14 +63,14 @@
/**************************************
-* Compiler Options
+* Includes
**************************************/
-#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
-/* "restrict" is a known keyword */
-#else
-# define restrict /* Disable restrict */
-#endif
+#include "lz4.h"
+
+/**************************************
+* Compiler Options
+**************************************/
#ifdef _MSC_VER /* Visual Studio */
# define FORCE_INLINE static __forceinline
# include <intrin.h>
@@ -113,7 +78,7 @@
# pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */
#else
# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
-# ifdef __GNUC__
+# if defined(__GNUC__) || defined(__clang__)
# define FORCE_INLINE static inline __attribute__((always_inline))
# else
# define FORCE_INLINE static inline
@@ -123,9 +88,8 @@
# endif /* __STDC_VERSION__ */
#endif /* _MSC_VER */
-#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
-
-#if (GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__)
+/* LZ4_GCC_VERSION is defined into lz4.h */
+#if (LZ4_GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__)
# define expect(expr,value) (__builtin_expect ((expr),(value)) )
#else
# define expect(expr,value) (expr)
@@ -136,7 +100,7 @@
/**************************************
- Memory routines
+* Memory routines
**************************************/
#include <stdlib.h> /* malloc, calloc, free */
#define ALLOCATOR(n,s) calloc(n,s)
@@ -146,13 +110,7 @@
/**************************************
- Includes
-**************************************/
-#include "lz4.h"
-
-
-/**************************************
- Basic Types
+* Basic Types
**************************************/
#if defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
# include <stdint.h>
@@ -171,7 +129,7 @@
/**************************************
- Reading and writing into memory
+* Reading and writing into memory
**************************************/
#define STEPSIZE sizeof(size_t)
@@ -184,10 +142,19 @@ static unsigned LZ4_isLittleEndian(void)
}
+static U16 LZ4_read16(const void* memPtr)
+{
+ U16 val16;
+ memcpy(&val16, memPtr, 2);
+ return val16;
+}
+
static U16 LZ4_readLE16(const void* memPtr)
{
- if ((LZ4_UNALIGNED_ACCESS) && (LZ4_isLittleEndian()))
- return *(U16*)memPtr;
+ if (LZ4_isLittleEndian())
+ {
+ return LZ4_read16(memPtr);
+ }
else
{
const BYTE* p = (const BYTE*)memPtr;
@@ -197,10 +164,9 @@ static U16 LZ4_readLE16(const void* memPtr)
static void LZ4_writeLE16(void* memPtr, U16 value)
{
- if ((LZ4_UNALIGNED_ACCESS) && (LZ4_isLittleEndian()))
+ if (LZ4_isLittleEndian())
{
- *(U16*)memPtr = value;
- return;
+ memcpy(memPtr, &value, 2);
}
else
{
@@ -210,41 +176,18 @@ static void LZ4_writeLE16(void* memPtr, U16 value)
}
}
-
-static U16 LZ4_read16(const void* memPtr)
-{
- if (LZ4_UNALIGNED_ACCESS)
- return *(U16*)memPtr;
- else
- {
- U16 val16;
- memcpy(&val16, memPtr, 2);
- return val16;
- }
-}
-
static U32 LZ4_read32(const void* memPtr)
{
- if (LZ4_UNALIGNED_ACCESS)
- return *(U32*)memPtr;
- else
- {
- U32 val32;
- memcpy(&val32, memPtr, 4);
- return val32;
- }
+ U32 val32;
+ memcpy(&val32, memPtr, 4);
+ return val32;
}
static U64 LZ4_read64(const void* memPtr)
{
- if (LZ4_UNALIGNED_ACCESS)
- return *(U64*)memPtr;
- else
- {
- U64 val64;
- memcpy(&val64, memPtr, 8);
- return val64;
- }
+ U64 val64;
+ memcpy(&val64, memPtr, 8);
+ return val64;
}
static size_t LZ4_read_ARCH(const void* p)
@@ -256,31 +199,9 @@ static size_t LZ4_read_ARCH(const void* p)
}
-static void LZ4_copy4(void* dstPtr, const void* srcPtr)
-{
- if (LZ4_UNALIGNED_ACCESS)
- {
- *(U32*)dstPtr = *(U32*)srcPtr;
- return;
- }
- memcpy(dstPtr, srcPtr, 4);
-}
+static void LZ4_copy4(void* dstPtr, const void* srcPtr) { memcpy(dstPtr, srcPtr, 4); }
-static void LZ4_copy8(void* dstPtr, const void* srcPtr)
-{
-#if GCC_VERSION!=409 /* disabled on GCC 4.9, as it generates invalid opcode (crash) */
- if (LZ4_UNALIGNED_ACCESS)
- {
- if (LZ4_64bits())
- *(U64*)dstPtr = *(U64*)srcPtr;
- else
- ((U32*)dstPtr)[0] = ((U32*)srcPtr)[0],
- ((U32*)dstPtr)[1] = ((U32*)srcPtr)[1];
- return;
- }
-#endif
- memcpy(dstPtr, srcPtr, 8);
-}
+static void LZ4_copy8(void* dstPtr, const void* srcPtr) { memcpy(dstPtr, srcPtr, 8); }
/* customized version of memcpy, which may overwrite up to 7 bytes beyond dstEnd */
static void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
@@ -293,7 +214,7 @@ static void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
/**************************************
- Common Constants
+* Common Constants
**************************************/
#define MINMATCH 4
@@ -334,7 +255,7 @@ static unsigned LZ4_NbCommonBytes (register size_t val)
unsigned long r = 0;
_BitScanForward64( &r, (U64)val );
return (int)(r>>3);
-# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
+# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT)
return (__builtin_ctzll((U64)val) >> 3);
# else
static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };
@@ -347,7 +268,7 @@ static unsigned LZ4_NbCommonBytes (register size_t val)
unsigned long r;
_BitScanForward( &r, (U32)val );
return (int)(r>>3);
-# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
+# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT)
return (__builtin_ctz((U32)val) >> 3);
# else
static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };
@@ -363,8 +284,8 @@ static unsigned LZ4_NbCommonBytes (register size_t val)
unsigned long r = 0;
_BitScanReverse64( &r, val );
return (unsigned)(r>>3);
-# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
- return (__builtin_clzll(val) >> 3);
+# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ return (__builtin_clzll((U64)val) >> 3);
# else
unsigned r;
if (!(val>>32)) { r=4; } else { r=0; val>>=32; }
@@ -379,8 +300,8 @@ static unsigned LZ4_NbCommonBytes (register size_t val)
unsigned long r = 0;
_BitScanReverse( &r, (unsigned long)val );
return (unsigned)(r>>3);
-# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)
- return (__builtin_clz(val) >> 3);
+# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ return (__builtin_clz((U32)val) >> 3);
# else
unsigned r;
if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
@@ -423,13 +344,6 @@ static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression ru
/**************************************
-* Local Utils
-**************************************/
-int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
-int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
-
-
-/**************************************
* Local Structures and types
**************************************/
typedef struct {
@@ -437,7 +351,7 @@ typedef struct {
U32 currentOffset;
U32 initCheck;
const BYTE* dictionary;
- const BYTE* bufferStart;
+ BYTE* bufferStart; /* obsolete, used for slideInputBuffer */
U32 dictSize;
} LZ4_stream_t_internal;
@@ -451,6 +365,14 @@ typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
typedef enum { full = 0, partial = 1 } earlyEnd_directive;
+/**************************************
+* Local Utils
+**************************************/
+int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
+int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
+int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
+
+
/********************************
* Compression functions
@@ -464,7 +386,22 @@ static U32 LZ4_hashSequence(U32 sequence, tableType_t const tableType)
return (((sequence) * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
}
-static U32 LZ4_hashPosition(const BYTE* p, tableType_t tableType) { return LZ4_hashSequence(LZ4_read32(p), tableType); }
+static const U64 prime5bytes = 889523592379ULL;
+static U32 LZ4_hashSequence64(size_t sequence, tableType_t const tableType)
+{
+ const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
+ const U32 hashMask = (1<<hashLog) - 1;
+ return ((sequence * prime5bytes) >> (40 - hashLog)) & hashMask;
+}
+
+static U32 LZ4_hashSequenceT(size_t sequence, tableType_t const tableType)
+{
+ if (LZ4_64bits())
+ return LZ4_hashSequence64(sequence, tableType);
+ return LZ4_hashSequence((U32)sequence, tableType);
+}
+
+static U32 LZ4_hashPosition(const void* p, tableType_t tableType) { return LZ4_hashSequenceT(LZ4_read_ARCH(p), tableType); }
static void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase)
{
@@ -495,16 +432,17 @@ static const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t t
return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
}
-static int LZ4_compress_generic(
- void* ctx,
- const char* source,
- char* dest,
- int inputSize,
- int maxOutputSize,
- limitedOutput_directive outputLimited,
- tableType_t const tableType,
- dict_directive dict,
- dictIssue_directive dictIssue)
+FORCE_INLINE int LZ4_compress_generic(
+ void* const ctx,
+ const char* const source,
+ char* const dest,
+ const int inputSize,
+ const int maxOutputSize,
+ const limitedOutput_directive outputLimited,
+ const tableType_t tableType,
+ const dict_directive dict,
+ const dictIssue_directive dictIssue,
+ const U32 acceleration)
{
LZ4_stream_t_internal* const dictPtr = (LZ4_stream_t_internal*)ctx;
@@ -527,7 +465,7 @@ static int LZ4_compress_generic(
size_t refDelta=0;
/* Init conditions */
- if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */
+ if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */
switch(dict)
{
case noDict:
@@ -558,15 +496,15 @@ static int LZ4_compress_generic(
BYTE* token;
{
const BYTE* forwardIp = ip;
- unsigned step=1;
- unsigned searchMatchNb = (1U << LZ4_skipTrigger);
+ unsigned step = 1;
+ unsigned searchMatchNb = acceleration << LZ4_skipTrigger;
/* Find a match */
do {
U32 h = forwardH;
ip = forwardIp;
forwardIp += step;
- step = searchMatchNb++ >> LZ4_skipTrigger;
+ step = (searchMatchNb++ >> LZ4_skipTrigger);
if (unlikely(forwardIp > mflimit)) goto _last_literals;
@@ -693,13 +631,22 @@ _next_match:
_last_literals:
/* Encode Last Literals */
{
- int lastRun = (int)(iend - anchor);
- if ((outputLimited) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize))
+ const size_t lastRun = (size_t)(iend - anchor);
+ if ((outputLimited) && ((op - (BYTE*)dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize))
return 0; /* Check output limit */
- if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun >= 255 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }
- else *op++ = (BYTE)(lastRun<<ML_BITS);
- memcpy(op, anchor, iend - anchor);
- op += iend-anchor;
+ if (lastRun >= RUN_MASK)
+ {
+ size_t accumulator = lastRun - RUN_MASK;
+ *op++ = RUN_MASK << ML_BITS;
+ for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
+ *op++ = (BYTE) accumulator;
+ }
+ else
+ {
+ *op++ = (BYTE)(lastRun<<ML_BITS);
+ }
+ memcpy(op, anchor, lastRun);
+ op += lastRun;
}
/* End */
@@ -707,39 +654,271 @@ _last_literals:
}
-int LZ4_compress(const char* source, char* dest, int inputSize)
+int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
+{
+ LZ4_resetStream((LZ4_stream_t*)state);
+ if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
+
+ if (maxOutputSize >= LZ4_compressBound(inputSize))
+ {
+ if (inputSize < LZ4_64Klimit)
+ return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
+ else
+ return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue, acceleration);
+ }
+ else
+ {
+ if (inputSize < LZ4_64Klimit)
+ return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
+ else
+ return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue, acceleration);
+ }
+}
+
+
+int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
{
#if (HEAPMODE)
- void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8); /* Aligned on 8-bytes boundaries */
+ void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
#else
- U64 ctx[LZ4_STREAMSIZE_U64] = {0}; /* Ensure data is aligned on 8-bytes boundaries */
+ LZ4_stream_t ctx;
+ void* ctxPtr = &ctx;
#endif
- int result;
- if (inputSize < LZ4_64Klimit)
- result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue);
- else
- result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
+ int result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
#if (HEAPMODE)
- FREEMEM(ctx);
+ FREEMEM(ctxPtr);
#endif
return result;
}
-int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
+
+int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize)
+{
+ return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1);
+}
+
+
+/* hidden debug function */
+/* strangely enough, gcc generates faster code when this function is uncommented, even if unused */
+int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
+{
+ LZ4_stream_t ctx;
+
+ LZ4_resetStream(&ctx);
+
+ if (inputSize < LZ4_64Klimit)
+ return LZ4_compress_generic(&ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
+ else
+ return LZ4_compress_generic(&ctx, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue, acceleration);
+}
+
+
+/********************************
+* destSize variant
+********************************/
+
+static int LZ4_compress_destSize_generic(
+ void* const ctx,
+ const char* const src,
+ char* const dst,
+ int* const srcSizePtr,
+ const int targetDstSize,
+ const tableType_t tableType)
+{
+ const BYTE* ip = (const BYTE*) src;
+ const BYTE* base = (const BYTE*) src;
+ const BYTE* lowLimit = (const BYTE*) src;
+ const BYTE* anchor = ip;
+ const BYTE* const iend = ip + *srcSizePtr;
+ const BYTE* const mflimit = iend - MFLIMIT;
+ const BYTE* const matchlimit = iend - LASTLITERALS;
+
+ BYTE* op = (BYTE*) dst;
+ BYTE* const oend = op + targetDstSize;
+ BYTE* const oMaxLit = op + targetDstSize - 2 /* offset */ - 8 /* because 8+MINMATCH==MFLIMIT */ - 1 /* token */;
+ BYTE* const oMaxMatch = op + targetDstSize - (LASTLITERALS + 1 /* token */);
+ BYTE* const oMaxSeq = oMaxLit - 1 /* token */;
+
+ U32 forwardH;
+
+
+ /* Init conditions */
+ if (targetDstSize < 1) return 0; /* Impossible to store anything */
+ if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */
+ if ((tableType == byU16) && (*srcSizePtr>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */
+ if (*srcSizePtr<LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */
+
+ /* First Byte */
+ *srcSizePtr = 0;
+ LZ4_putPosition(ip, ctx, tableType, base);
+ ip++; forwardH = LZ4_hashPosition(ip, tableType);
+
+ /* Main Loop */
+ for ( ; ; )
+ {
+ const BYTE* match;
+ BYTE* token;
+ {
+ const BYTE* forwardIp = ip;
+ unsigned step = 1;
+ unsigned searchMatchNb = 1 << LZ4_skipTrigger;
+
+ /* Find a match */
+ do {
+ U32 h = forwardH;
+ ip = forwardIp;
+ forwardIp += step;
+ step = (searchMatchNb++ >> LZ4_skipTrigger);
+
+ if (unlikely(forwardIp > mflimit))
+ goto _last_literals;
+
+ match = LZ4_getPositionOnHash(h, ctx, tableType, base);
+ forwardH = LZ4_hashPosition(forwardIp, tableType);
+ LZ4_putPositionOnHash(ip, h, ctx, tableType, base);
+
+ } while ( ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip))
+ || (LZ4_read32(match) != LZ4_read32(ip)) );
+ }
+
+ /* Catch up */
+ while ((ip>anchor) && (match > lowLimit) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; }
+
+ {
+ /* Encode Literal length */
+ unsigned litLength = (unsigned)(ip - anchor);
+ token = op++;
+ if (op + ((litLength+240)/255) + litLength > oMaxLit)
+ {
+ /* Not enough space for a last match */
+ op--;
+ goto _last_literals;
+ }
+ if (litLength>=RUN_MASK)
+ {
+ unsigned len = litLength - RUN_MASK;
+ *token=(RUN_MASK<<ML_BITS);
+ for(; len >= 255 ; len-=255) *op++ = 255;
+ *op++ = (BYTE)len;
+ }
+ else *token = (BYTE)(litLength<<ML_BITS);
+
+ /* Copy Literals */
+ LZ4_wildCopy(op, anchor, op+litLength);
+ op += litLength;
+ }
+
+_next_match:
+ /* Encode Offset */
+ LZ4_writeLE16(op, (U16)(ip-match)); op+=2;
+
+ /* Encode MatchLength */
+ {
+ size_t matchLength;
+
+ matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
+
+ if (op + ((matchLength+240)/255) > oMaxMatch)
+ {
+ /* Match description too long : reduce it */
+ matchLength = (15-1) + (oMaxMatch-op) * 255;
+ }
+ //printf("offset %5i, matchLength%5i \n", (int)(ip-match), matchLength + MINMATCH);
+ ip += MINMATCH + matchLength;
+
+ if (matchLength>=ML_MASK)
+ {
+ *token += ML_MASK;
+ matchLength -= ML_MASK;
+ while (matchLength >= 255) { matchLength-=255; *op++ = 255; }
+ *op++ = (BYTE)matchLength;
+ }
+ else *token += (BYTE)(matchLength);
+ }
+
+ anchor = ip;
+
+ /* Test end of block */
+ if (ip > mflimit) break;
+ if (op > oMaxSeq) break;
+
+ /* Fill table */
+ LZ4_putPosition(ip-2, ctx, tableType, base);
+
+ /* Test next position */
+ match = LZ4_getPosition(ip, ctx, tableType, base);
+ LZ4_putPosition(ip, ctx, tableType, base);
+ if ( (match+MAX_DISTANCE>=ip)
+ && (LZ4_read32(match)==LZ4_read32(ip)) )
+ { token=op++; *token=0; goto _next_match; }
+
+ /* Prepare next loop */
+ forwardH = LZ4_hashPosition(++ip, tableType);
+ }
+
+_last_literals:
+ /* Encode Last Literals */
+ {
+ size_t lastRunSize = (size_t)(iend - anchor);
+ if (op + 1 /* token */ + ((lastRunSize+240)/255) /* litLength */ + lastRunSize /* literals */ > oend)
+ {
+ /* adapt lastRunSize to fill 'dst' */
+ lastRunSize = (oend-op) - 1;
+ lastRunSize -= (lastRunSize+240)/255;
+ }
+ ip = anchor + lastRunSize;
+
+ if (lastRunSize >= RUN_MASK)
+ {
+ size_t accumulator = lastRunSize - RUN_MASK;
+ *op++ = RUN_MASK << ML_BITS;
+ for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
+ *op++ = (BYTE) accumulator;
+ }
+ else
+ {
+ *op++ = (BYTE)(lastRunSize<<ML_BITS);
+ }
+ memcpy(op, anchor, lastRunSize);
+ op += lastRunSize;
+ }
+
+ /* End */
+ *srcSizePtr = (int) (((const char*)ip)-src);
+ return (int) (((char*)op)-dst);
+}
+
+
+static int LZ4_compress_destSize_extState (void* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize)
+{
+ LZ4_resetStream((LZ4_stream_t*)state);
+
+ if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) /* compression success is guaranteed */
+ {
+ return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
+ }
+ else
+ {
+ if (*srcSizePtr < LZ4_64Klimit)
+ return LZ4_compress_destSize_generic(state, src, dst, srcSizePtr, targetDstSize, byU16);
+ else
+ return LZ4_compress_destSize_generic(state, src, dst, srcSizePtr, targetDstSize, LZ4_64bits() ? byU32 : byPtr);
+ }
+}
+
+
+int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize)
{
#if (HEAPMODE)
- void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8); /* Aligned on 8-bytes boundaries */
+ void* ctx = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
#else
- U64 ctx[LZ4_STREAMSIZE_U64] = {0}; /* Ensure data is aligned on 8-bytes boundaries */
+ LZ4_stream_t ctxBody;
+ void* ctx = &ctxBody;
#endif
- int result;
- if (inputSize < LZ4_64Klimit)
- result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue);
- else
- result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
+ int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
#if (HEAPMODE)
FREEMEM(ctx);
@@ -748,19 +927,10 @@ int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, in
}
-/*****************************************
-* Experimental : Streaming functions
-*****************************************/
-/*
- * LZ4_initStream
- * Use this function once, to init a newly allocated LZ4_stream_t structure
- * Return : 1 if OK, 0 if error
- */
-void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
-{
- MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
-}
+/********************************
+* Streaming functions
+********************************/
LZ4_stream_t* LZ4_createStream(void)
{
@@ -770,6 +940,11 @@ LZ4_stream_t* LZ4_createStream(void)
return lz4s;
}
+void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
+{
+ MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
+}
+
int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
{
FREEMEM(LZ4_stream);
@@ -777,6 +952,7 @@ int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
}
+#define HASH_UNIT sizeof(size_t)
int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
{
LZ4_stream_t_internal* dict = (LZ4_stream_t_internal*) LZ4_dict;
@@ -784,24 +960,26 @@ int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
const BYTE* const dictEnd = p + dictSize;
const BYTE* base;
- if (dict->initCheck) LZ4_resetStream(LZ4_dict); /* Uninitialized structure detected */
+ if ((dict->initCheck) || (dict->currentOffset > 1 GB)) /* Uninitialized structure, or reuse overflow */
+ LZ4_resetStream(LZ4_dict);
- if (dictSize < MINMATCH)
+ if (dictSize < (int)HASH_UNIT)
{
dict->dictionary = NULL;
dict->dictSize = 0;
return 0;
}
- if (p <= dictEnd - 64 KB) p = dictEnd - 64 KB;
+ if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;
+ dict->currentOffset += 64 KB;
base = p - dict->currentOffset;
dict->dictionary = p;
dict->dictSize = (U32)(dictEnd - p);
dict->currentOffset += dict->dictSize;
- while (p <= dictEnd-MINMATCH)
+ while (p <= dictEnd-HASH_UNIT)
{
- LZ4_putPosition(p, dict, byU32, base);
+ LZ4_putPosition(p, dict->hashTable, byU32, base);
p+=3;
}
@@ -830,8 +1008,7 @@ static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src)
}
-FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* source, char* dest, int inputSize,
- int maxOutputSize, limitedOutput_directive limit)
+int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
{
LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_stream;
const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize;
@@ -840,6 +1017,7 @@ FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* so
if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */
if ((streamPtr->dictSize>0) && (smallest>dictEnd)) smallest = dictEnd;
LZ4_renormDictT(streamPtr, smallest);
+ if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
/* Check overlapping input/dictionary space */
{
@@ -858,9 +1036,9 @@ FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* so
{
int result;
if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
- result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, withPrefix64k, dictSmall);
+ result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, dictSmall, acceleration);
else
- result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, withPrefix64k, noDictIssue);
+ result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, noDictIssue, acceleration);
streamPtr->dictSize += (U32)inputSize;
streamPtr->currentOffset += (U32)inputSize;
return result;
@@ -870,9 +1048,9 @@ FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* so
{
int result;
if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
- result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, usingExtDict, dictSmall);
+ result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, dictSmall, acceleration);
else
- result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, usingExtDict, noDictIssue);
+ result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, noDictIssue, acceleration);
streamPtr->dictionary = (const BYTE*)source;
streamPtr->dictSize = (U32)inputSize;
streamPtr->currentOffset += (U32)inputSize;
@@ -880,18 +1058,8 @@ FORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* so
}
}
-int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)
-{
- return LZ4_compress_continue_generic(LZ4_stream, source, dest, inputSize, 0, notLimited);
-}
-
-int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize)
-{
- return LZ4_compress_continue_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput);
-}
-
-/* Hidden debug function, to force separate dictionary mode */
+/* Hidden debug function, to force external dictionary mode */
int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int inputSize)
{
LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_dict;
@@ -902,7 +1070,7 @@ int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char*
if (smallest > (const BYTE*) source) smallest = (const BYTE*) source;
LZ4_renormDictT((LZ4_stream_t_internal*)LZ4_dict, smallest);
- result = LZ4_compress_generic(LZ4_dict, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue);
+ result = LZ4_compress_generic(LZ4_dict, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);
streamPtr->dictionary = (const BYTE*)source;
streamPtr->dictSize = (U32)inputSize;
@@ -955,7 +1123,7 @@ FORCE_INLINE int LZ4_decompress_generic(
)
{
/* Local Variables */
- const BYTE* restrict ip = (const BYTE*) source;
+ const BYTE* ip = (const BYTE*) source;
const BYTE* const iend = ip + inputSize;
BYTE* op = (BYTE*) dest;
@@ -1051,8 +1219,7 @@ FORCE_INLINE int LZ4_decompress_generic(
{
/* match can be copied as a single segment from external dictionary */
match = dictEnd - (lowPrefix-match);
- memcpy(op, match, length);
- op += length;
+ memmove(op, match, length); op += length;
}
else
{
@@ -1110,11 +1277,11 @@ FORCE_INLINE int LZ4_decompress_generic(
if (endOnInput)
return (int) (((char*)op)-dest); /* Nb of output bytes decoded */
else
- return (int) (((char*)ip)-source); /* Nb of input bytes read */
+ return (int) (((const char*)ip)-source); /* Nb of input bytes read */
/* Overflow error detected */
_output_error:
- return (int) (-(((char*)ip)-source))-1;
+ return (int) (-(((const char*)ip)-source))-1;
}
@@ -1138,9 +1305,9 @@ int LZ4_decompress_fast(const char* source, char* dest, int originalSize)
typedef struct
{
- BYTE* externalDict;
+ const BYTE* externalDict;
size_t extDictSize;
- BYTE* prefixEnd;
+ const BYTE* prefixEnd;
size_t prefixSize;
} LZ4_streamDecode_t_internal;
@@ -1172,7 +1339,7 @@ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dicti
{
LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;
lz4sd->prefixSize = (size_t) dictSize;
- lz4sd->prefixEnd = (BYTE*) dictionary + dictSize;
+ lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;
lz4sd->externalDict = NULL;
lz4sd->extDictSize = 0;
return 1;
@@ -1261,7 +1428,7 @@ FORCE_INLINE int LZ4_decompress_usingDict_generic(const char* source, char* dest
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, withPrefix64k, (BYTE*)dest-64 KB, NULL, 0);
return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest-dictSize, NULL, 0);
}
- return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (BYTE*)dictStart, dictSize);
+ return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize);
}
int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
@@ -1277,13 +1444,21 @@ int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSi
/* debug function */
int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
{
- return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (BYTE*)dictStart, dictSize);
+ return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize);
}
/***************************************************
* Obsolete Functions
***************************************************/
+/* obsolete compression functions */
+int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) { return LZ4_compress_default(source, dest, inputSize, maxOutputSize); }
+int LZ4_compress(const char* source, char* dest, int inputSize) { return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize)); }
+int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); }
+int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); }
+int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, maxDstSize, 1); }
+int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) { return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); }
+
/*
These function names are deprecated and should no longer be used.
They are only provided here for compatibility with older user programs.
@@ -1298,23 +1473,23 @@ int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize,
int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; }
-static void LZ4_init(LZ4_stream_t_internal* lz4ds, const BYTE* base)
+static void LZ4_init(LZ4_stream_t_internal* lz4ds, BYTE* base)
{
MEM_INIT(lz4ds, 0, LZ4_STREAMSIZE);
lz4ds->bufferStart = base;
}
-int LZ4_resetStreamState(void* state, const char* inputBuffer)
+int LZ4_resetStreamState(void* state, char* inputBuffer)
{
if ((((size_t)state) & 3) != 0) return 1; /* Error : pointer is not aligned on 4-bytes boundary */
- LZ4_init((LZ4_stream_t_internal*)state, (const BYTE*)inputBuffer);
+ LZ4_init((LZ4_stream_t_internal*)state, (BYTE*)inputBuffer);
return 0;
}
-void* LZ4_create (const char* inputBuffer)
+void* LZ4_create (char* inputBuffer)
{
void* lz4ds = ALLOCATOR(8, LZ4_STREAMSIZE_U64);
- LZ4_init ((LZ4_stream_t_internal*)lz4ds, (const BYTE*)inputBuffer);
+ LZ4_init ((LZ4_stream_t_internal*)lz4ds, (BYTE*)inputBuffer);
return lz4ds;
}
@@ -1325,32 +1500,6 @@ char* LZ4_slideInputBuffer (void* LZ4_Data)
return (char*)(ctx->bufferStart + dictSize);
}
-/* Obsolete compresson functions using User-allocated state */
-
-int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
-
-int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize)
-{
- if (((size_t)(state)&3) != 0) return 0; /* Error : state is not aligned on 4-bytes boundary */
- MEM_INIT(state, 0, LZ4_STREAMSIZE);
-
- if (inputSize < LZ4_64Klimit)
- return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue);
- else
- return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
-}
-
-int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize)
-{
- if (((size_t)(state)&3) != 0) return 0; /* Error : state is not aligned on 4-bytes boundary */
- MEM_INIT(state, 0, LZ4_STREAMSIZE);
-
- if (inputSize < LZ4_64Klimit)
- return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue);
- else
- return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);
-}
-
/* Obsolete streaming decompression functions */
int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)
diff --git a/ext/lz4/lz4.h b/ext/lz4/lz4.h
index de43fc0a..3e740022 100644
--- a/ext/lz4/lz4.h
+++ b/ext/lz4/lz4.h
@@ -39,17 +39,17 @@ extern "C" {
#endif
/*
- * lz4.h provides block compression functions, for optimal performance.
+ * lz4.h provides block compression functions, and gives full buffer control to programmer.
* If you need to generate inter-operable compressed data (respecting LZ4 frame specification),
- * please use lz4frame.h instead.
+ * and can let the library handle its own memory, please use lz4frame.h instead.
*/
/**************************************
* Version
**************************************/
#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */
-#define LZ4_VERSION_MINOR 6 /* for new (non-breaking) interface capabilities */
-#define LZ4_VERSION_RELEASE 0 /* for tweaks, bug-fixes, or development */
+#define LZ4_VERSION_MINOR 7 /* for new (non-breaking) interface capabilities */
+#define LZ4_VERSION_RELEASE 1 /* for tweaks, bug-fixes, or development */
#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
int LZ4_versionNumber (void);
@@ -70,28 +70,32 @@ int LZ4_versionNumber (void);
* Simple Functions
**************************************/
-int LZ4_compress (const char* source, char* dest, int sourceSize);
+int LZ4_compress_default(const char* source, char* dest, int sourceSize, int maxDestSize);
int LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize);
/*
-LZ4_compress() :
- Compresses 'sourceSize' bytes from 'source' into 'dest'.
- Destination buffer must be already allocated,
- and must be sized to handle worst cases situations (input data not compressible)
- Worst case size evaluation is provided by function LZ4_compressBound()
- inputSize : Max supported value is LZ4_MAX_INPUT_SIZE
- return : the number of bytes written in buffer dest
- or 0 if the compression fails
+LZ4_compress_default() :
+ Compresses 'sourceSize' bytes from buffer 'source'
+ into already allocated 'dest' buffer of size 'maxDestSize'.
+ Compression is guaranteed to succeed if 'maxDestSize' >= LZ4_compressBound(sourceSize).
+ It also runs faster, so it's a recommended setting.
+ If the function cannot compress 'source' into a more limited 'dest' budget,
+ compression stops *immediately*, and the function result is zero.
+ As a consequence, 'dest' content is not valid.
+ This function never writes outside 'dest' buffer, nor read outside 'source' buffer.
+ sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE
+ maxDestSize : full or partial size of buffer 'dest' (which must be already allocated)
+ return : the number of bytes written into buffer 'dest' (necessarily <= maxOutputSize)
+ or 0 if compression fails
LZ4_decompress_safe() :
- compressedSize : is obviously the source size
- maxDecompressedSize : is the size of the destination buffer, which must be already allocated.
- return : the number of bytes decompressed into the destination buffer (necessarily <= maxDecompressedSize)
- If the destination buffer is not large enough, decoding will stop and output an error code (<0).
+ compressedSize : is the precise full size of the compressed block.
+ maxDecompressedSize : is the size of destination buffer, which must be already allocated.
+ return : the number of bytes decompressed into destination buffer (necessarily <= maxDecompressedSize)
+ If destination buffer is not large enough, decoding will stop and output an error code (<0).
If the source stream is detected malformed, the function will stop decoding and return a negative result.
- This function is protected against buffer overflow exploits,
- and never writes outside of output buffer, nor reads outside of input buffer.
- It is also protected against malicious data packets.
+ This function is protected against buffer overflow exploits, including malicious data packets.
+ It never writes outside output buffer, nor reads outside input buffer.
*/
@@ -99,45 +103,54 @@ LZ4_decompress_safe() :
* Advanced Functions
**************************************/
#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
-#define LZ4_COMPRESSBOUND(isize) ((unsigned int)(isize) > (unsigned int)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
+#define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
/*
LZ4_compressBound() :
Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible)
- This function is primarily useful for memory allocation purposes (output buffer size).
+ This function is primarily useful for memory allocation purposes (destination buffer size).
Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).
-
- isize : is the input size. Max supported value is LZ4_MAX_INPUT_SIZE
- return : maximum output size in a "worst case" scenario
- or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE)
+ Note that LZ4_compress_default() compress faster when dest buffer size is >= LZ4_compressBound(srcSize)
+ inputSize : max supported value is LZ4_MAX_INPUT_SIZE
+ return : maximum output size in a "worst case" scenario
+ or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE)
*/
-int LZ4_compressBound(int isize);
-
+int LZ4_compressBound(int inputSize);
/*
-LZ4_compress_limitedOutput() :
- Compress 'sourceSize' bytes from 'source' into an output buffer 'dest' of maximum size 'maxOutputSize'.
- If it cannot achieve it, compression will stop, and result of the function will be zero.
- This saves time and memory on detecting non-compressible (or barely compressible) data.
- This function never writes outside of provided output buffer.
-
- sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE
- maxOutputSize : is the size of the destination buffer (which must be already allocated)
- return : the number of bytes written in buffer 'dest'
- or 0 if compression fails
+LZ4_compress_fast() :
+ Same as LZ4_compress_default(), but allows to select an "acceleration" factor.
+ The larger the acceleration value, the faster the algorithm, but also the lesser the compression.
+ It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed.
+ An acceleration value of "1" is the same as regular LZ4_compress_default()
+ Values <= 0 will be replaced by ACCELERATION_DEFAULT (see lz4.c), which is 1.
*/
-int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize);
+int LZ4_compress_fast (const char* source, char* dest, int sourceSize, int maxDestSize, int acceleration);
/*
-LZ4_compress_withState() :
- Same compression functions, but using an externally allocated memory space to store compression state.
+LZ4_compress_fast_extState() :
+ Same compression function, just using an externally allocated memory space to store compression state.
Use LZ4_sizeofState() to know how much memory must be allocated,
- and then, provide it as 'void* state' to compression functions.
+ and allocate it on 8-bytes boundaries (using malloc() typically).
+ Then, provide it as 'void* state' to compression function.
*/
int LZ4_sizeofState(void);
-int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize);
-int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
+int LZ4_compress_fast_extState (void* state, const char* source, char* dest, int inputSize, int maxDestSize, int acceleration);
+
+
+/*
+LZ4_compress_destSize() :
+ Reverse the logic, by compressing as much data as possible from 'source' buffer
+ into already allocated buffer 'dest' of size 'targetDestSize'.
+ This function either compresses the entire 'source' content into 'dest' if it's large enough,
+ or fill 'dest' buffer completely with as much data as possible from 'source'.
+ *sourceSizePtr : will be modified to indicate how many bytes where read from 'source' to fill 'dest'.
+ New value is necessarily <= old value.
+ return : Nb bytes written into 'dest' (necessarily <= targetDestSize)
+ or 0 if compression fails
+*/
+int LZ4_compress_destSize (const char* source, char* dest, int* sourceSizePtr, int targetDestSize);
/*
@@ -153,7 +166,6 @@ LZ4_decompress_fast() :
*/
int LZ4_decompress_fast (const char* source, char* dest, int originalSize);
-
/*
LZ4_decompress_safe_partial() :
This function decompress a compressed block of size 'compressedSize' at position 'source'
@@ -172,7 +184,6 @@ int LZ4_decompress_safe_partial (const char* source, char* dest, int compressedS
/***********************************************
* Streaming Compression Functions
***********************************************/
-
#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)
#define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(long long))
/*
@@ -188,7 +199,7 @@ typedef struct { long long table[LZ4_STREAMSIZE_U64]; } LZ4_stream_t;
* LZ4_resetStream
* Use this function to init an allocated LZ4_stream_t structure
*/
-void LZ4_resetStream (LZ4_stream_t* LZ4_streamPtr);
+void LZ4_resetStream (LZ4_stream_t* streamPtr);
/*
* LZ4_createStream will allocate and initialize an LZ4_stream_t structure
@@ -197,7 +208,7 @@ void LZ4_resetStream (LZ4_stream_t* LZ4_streamPtr);
* They are more future proof, in case of a change of LZ4_stream_t size.
*/
LZ4_stream_t* LZ4_createStream(void);
-int LZ4_freeStream (LZ4_stream_t* LZ4_streamPtr);
+int LZ4_freeStream (LZ4_stream_t* streamPtr);
/*
* LZ4_loadDict
@@ -206,32 +217,27 @@ int LZ4_freeStream (LZ4_stream_t* LZ4_streamPtr);
* Loading a size of 0 is allowed.
* Return : dictionary size, in bytes (necessarily <= 64 KB)
*/
-int LZ4_loadDict (LZ4_stream_t* LZ4_streamPtr, const char* dictionary, int dictSize);
+int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
/*
- * LZ4_compress_continue
- * Compress data block 'source', using blocks compressed before as dictionary to improve compression ratio
- * Previous data blocks are assumed to still be present at their previous location.
- * dest buffer must be already allocated, and sized to at least LZ4_compressBound(inputSize)
+ * LZ4_compress_fast_continue
+ * Compress buffer content 'src', using data from previously compressed blocks as dictionary to improve compression ratio.
+ * Important : Previous data blocks are assumed to still be present and unmodified !
+ * 'dst' buffer must be already allocated.
+ * If maxDstSize >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster.
+ * If not, and if compressed data cannot fit into 'dst' buffer size, compression stops, and function returns a zero.
*/
-int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);
-
-/*
- * LZ4_compress_limitedOutput_continue
- * Same as before, but also specify a maximum target compressed size (maxOutputSize)
- * If objective cannot be met, compression exits, and returns a zero.
- */
-int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
+int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int maxDstSize, int acceleration);
/*
* LZ4_saveDict
* If previously compressed data block is not guaranteed to remain available at its memory location
* save it into a safer place (char* safeBuffer)
* Note : you don't need to call LZ4_loadDict() afterwards,
- * dictionary is immediately usable, you can therefore call again LZ4_compress_continue()
+ * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue()
* Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error
*/
-int LZ4_saveDict (LZ4_stream_t* LZ4_streamPtr, char* safeBuffer, int dictSize);
+int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int dictSize);
/************************************************
@@ -266,8 +272,18 @@ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dicti
*_continue() :
These decoding functions allow decompression of multiple blocks in "streaming" mode.
Previously decoded blocks *must* remain available at the memory position where they were decoded (up to 64 KB)
- If this condition is not possible, save the relevant part of decoded data into a safe buffer,
- and indicate where is its new address using LZ4_setStreamDecode()
+ In the case of a ring buffers, decoding buffer must be either :
+ - Exactly same size as encoding buffer, with same update rule (block boundaries at same positions)
+ In which case, the decoding & encoding ring buffer can have any size, including very small ones ( < 64 KB).
+ - Larger than encoding buffer, by a minimum of maxBlockSize more bytes.
+ maxBlockSize is implementation dependent. It's the maximum size you intend to compress into a single block.
+ In which case, encoding and decoding buffers do not need to be synchronized,
+ and encoding ring buffer can have any size, including small ones ( < 64 KB).
+ - _At least_ 64 KB + 8 bytes + maxBlockSize.
+ In which case, encoding and decoding buffers do not need to be synchronized,
+ and encoding ring buffer can have any size, including larger than decoding buffer.
+ Whenever these conditions are not possible, save the last 64KB of decoded data into a safe buffer,
+ and indicate where it is saved using LZ4_setStreamDecode()
*/
int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize);
int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize);
@@ -277,8 +293,8 @@ int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const ch
Advanced decoding functions :
*_usingDict() :
These decoding functions work the same as
- a combination of LZ4_setDictDecode() followed by LZ4_decompress_x_continue()
- They are stand-alone and don't use nor update an LZ4_streamDecode_t structure.
+ a combination of LZ4_setStreamDecode() followed by LZ4_decompress_x_continue()
+ They are stand-alone. They don't need nor update an LZ4_streamDecode_t structure.
*/
int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize);
int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize);
@@ -288,27 +304,55 @@ int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalS
/**************************************
* Obsolete Functions
**************************************/
-/*
-Obsolete decompression functions
-These function names are deprecated and should no longer be used.
-They are only provided here for compatibility with older user programs.
-- LZ4_uncompress is the same as LZ4_decompress_fast
-- LZ4_uncompress_unknownOutputSize is the same as LZ4_decompress_safe
-These function prototypes are now disabled; uncomment them if you really need them.
-It is highly recommended to stop using these functions and migrate to newer ones */
+/* Deprecate Warnings */
+/* Should these warnings messages be a problem,
+ it is generally possible to disable them,
+ with -Wno-deprecated-declarations for gcc
+ or _CRT_SECURE_NO_WARNINGS in Visual for example.
+ You can also define LZ4_DEPRECATE_WARNING_DEFBLOCK. */
+#ifndef LZ4_DEPRECATE_WARNING_DEFBLOCK
+# define LZ4_DEPRECATE_WARNING_DEFBLOCK
+# define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+# if (LZ4_GCC_VERSION >= 405) || defined(__clang__)
+# define LZ4_DEPRECATED(message) __attribute__((deprecated(message)))
+# elif (LZ4_GCC_VERSION >= 301)
+# define LZ4_DEPRECATED(message) __attribute__((deprecated))
+# elif defined(_MSC_VER)
+# define LZ4_DEPRECATED(message) __declspec(deprecated(message))
+# else
+# pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler")
+# define LZ4_DEPRECATED(message)
+# endif
+#endif /* LZ4_DEPRECATE_WARNING_DEFBLOCK */
+
+/* Obsolete compression functions */
+/* These functions are planned to start generate warnings by r131 approximately */
+int LZ4_compress (const char* source, char* dest, int sourceSize);
+int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize);
+int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize);
+int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
+int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);
+int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
+
+/* Obsolete decompression functions */
+/* These function names are completely deprecated and must no longer be used.
+ They are only provided here for compatibility with older programs.
+ - LZ4_uncompress is the same as LZ4_decompress_fast
+ - LZ4_uncompress_unknownOutputSize is the same as LZ4_decompress_safe
+ These function prototypes are now disabled; uncomment them only if you really need them.
+ It is highly recommended to stop using these prototypes and migrate to maintained ones */
/* int LZ4_uncompress (const char* source, char* dest, int outputSize); */
/* int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); */
-
/* Obsolete streaming functions; use new streaming interface whenever possible */
-void* LZ4_create (const char* inputBuffer);
-int LZ4_sizeofStreamState(void);
-int LZ4_resetStreamState(void* state, const char* inputBuffer);
-char* LZ4_slideInputBuffer (void* state);
+LZ4_DEPRECATED("use LZ4_createStream() instead") void* LZ4_create (char* inputBuffer);
+LZ4_DEPRECATED("use LZ4_createStream() instead") int LZ4_sizeofStreamState(void);
+LZ4_DEPRECATED("use LZ4_resetStream() instead") int LZ4_resetStreamState(void* state, char* inputBuffer);
+LZ4_DEPRECATED("use LZ4_saveDict() instead") char* LZ4_slideInputBuffer (void* state);
/* Obsolete streaming decoding functions */
-int LZ4_decompress_safe_withPrefix64k (const char* source, char* dest, int compressedSize, int maxOutputSize);
-int LZ4_decompress_fast_withPrefix64k (const char* source, char* dest, int originalSize);
+LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize);
+LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize);
#if defined (__cplusplus)
diff --git a/include/ZeroTierOne.h b/include/ZeroTierOne.h
index 8a74eafa..076e31fc 100644
--- a/include/ZeroTierOne.h
+++ b/include/ZeroTierOne.h
@@ -112,12 +112,12 @@ extern "C" {
* This is more or less the max that can be fit in a given packet (with
* fragmentation) and only one address per hop.
*/
-#define ZT_CIRCUIT_TEST_MAX_HOPS 512
+#define ZT_CIRCUIT_TEST_MAX_HOPS 256
/**
* Maximum number of addresses per hop in a circuit test
*/
-#define ZT_CIRCUIT_TEST_MAX_HOP_BREADTH 256
+#define ZT_CIRCUIT_TEST_MAX_HOP_BREADTH 8
/**
* Maximum number of cluster members (and max member ID plus one)
diff --git a/java/jni/com_zerotierone_sdk_Node.cpp b/java/jni/com_zerotierone_sdk_Node.cpp
index 2c1b6807..dbabf803 100644
--- a/java/jni/com_zerotierone_sdk_Node.cpp
+++ b/java/jni/com_zerotierone_sdk_Node.cpp
@@ -90,6 +90,7 @@ namespace {
ZT_Node *node,
void *userData,
uint64_t nwid,
+ void **,
enum ZT_VirtualNetworkConfigOperation operation,
const ZT_VirtualNetworkConfig *config)
{
@@ -137,6 +138,7 @@ namespace {
void VirtualNetworkFrameFunctionCallback(ZT_Node *node,
void *userData,
uint64_t nwid,
+ void**,
uint64_t sourceMac,
uint64_t destMac,
unsigned int etherType,
@@ -609,6 +611,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_node_1init(
&WirePacketSendFunction,
&VirtualNetworkFrameFunctionCallback,
&VirtualNetworkConfigFunctionCallback,
+ NULL,
&EventCallback);
if(rc != ZT_RESULT_OK)
@@ -995,7 +998,7 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_join(
uint64_t nwid = (uint64_t)in_nwid;
- ZT_ResultCode rc = ZT_Node_join(node, nwid);
+ ZT_ResultCode rc = ZT_Node_join(node, nwid, NULL);
return createResultObject(env, rc);
}
@@ -1018,8 +1021,8 @@ JNIEXPORT jobject JNICALL Java_com_zerotier_sdk_Node_leave(
uint64_t nwid = (uint64_t)in_nwid;
- ZT_ResultCode rc = ZT_Node_leave(node, nwid);
-
+ ZT_ResultCode rc = ZT_Node_leave(node, nwid, NULL);
+
return createResultObject(env, rc);
}
diff --git a/make-linux.mk b/make-linux.mk
index 4011db95..0b59b5b0 100644
--- a/make-linux.mk
+++ b/make-linux.mk
@@ -18,6 +18,7 @@
#
GENERATED_FILES :=
+DOC_DIR = doc
# Automagically pick clang or gcc, with preference for clang
# This is only done if we have not overridden these with an environment or CLI variable
@@ -117,9 +118,7 @@ installer: one FORCE
./ext/installfiles/linux/buildinstaller.sh
clean: FORCE
- $(RM) -r ${GENERATED_FILES}
- rm -rf *.so *.o netcon/*.a node/*.o controller/*.o osdep/*.o service/*.o ext/http-parser/*.o ext/lz4/*.o ext/json-parser/*.o $(OBJS) zerotier-one zerotier-idtool zerotier-cli zerotier-selftest zerotier-netcon-service build-* ZeroTierOneInstaller-* *.deb *.rpm .depend netcon/.depend
- # Remove files from all the funny places we put them for tests
+ rm -rf ${GENERATED_FILES} *.so *.o netcon/*.a node/*.o controller/*.o osdep/*.o service/*.o ext/http-parser/*.o ext/lz4/*.o ext/json-parser/*.o ext/miniupnpc/*.o ext/libnatpmp/*.o $(OBJS) zerotier-one zerotier-idtool zerotier-cli zerotier-selftest zerotier-netcon-service build-* ZeroTierOneInstaller-* *.deb *.rpm .depend netcon/.depend
find netcon -type f \( -name '*.o' -o -name '*.so' -o -name '*.1.0' -o -name 'zerotier-one' -o -name 'zerotier-cli' -o -name 'zerotier-netcon-service' \) -delete
find netcon/docker-test -name "zerotier-intercept" -type f -delete
@@ -128,11 +127,10 @@ debug: FORCE
make ZT_DEBUG=1 selftest
official: FORCE
+ make ZT_OFFICIAL_RELEASE=1 clean
make -j 4 ZT_OFFICIAL_RELEASE=1 one
make ZT_OFFICIAL_RELEASE=1 installer
-FORCE:
-
-DOC_DIR = doc
-
include ${DOC_DIR}/module.mk
+
+FORCE:
diff --git a/make-mac.mk b/make-mac.mk
index ffaf822d..5987aed5 100644
--- a/make-mac.mk
+++ b/make-mac.mk
@@ -79,6 +79,18 @@ one: $(OBJS) service/OneService.o one.o
$(CODESIGN) -f -s $(CODESIGN_APP_CERT) zerotier-one
$(CODESIGN) -vvv zerotier-one
+netcon: $(OBJS)
+ rm -f *.o
+ # Need to selectively rebuild one.cpp and OneService.cpp with ZT_SERVICE_NETCON and ZT_ONE_NO_ROOT_CHECK defined, and also NetconEthernetTap
+ $(CXX) $(CXXFLAGS) $(LDFLAGS) -DZT_SERVICE_NETCON -DZT_ONE_NO_ROOT_CHECK -Iext/lwip/src/include -Iext/lwip/src/include/ipv4 -Iext/lwip/src/include/ipv6 -o zerotier-netcon-service $(OBJS) service/OneService.cpp netcon/NetconEthernetTap.cpp one.cpp -x c netcon/RPC.c $(LDLIBS) -ldl
+ # Build netcon/liblwip.so which must be placed in ZT home for zerotier-netcon-service to work
+ cd netcon ; make -f make-liblwip.mk
+ # Use gcc not clang to build standalone intercept library since gcc is typically used for libc and we want to ensure maximal ABI compatibility
+ cd netcon ; gcc -O2 -Wall -std=c99 -fPIC -fno-common -dynamiclib -flat_namespace -DVERBOSE -D_GNU_SOURCE -DNETCON_INTERCEPT -I. -nostdlib -shared -o libzerotierintercept.so Intercept.c RPC.c -ldl
+ cp netcon/libzerotierintercept.so libzerotierintercept.so
+ ln -sf zerotier-netcon-service zerotier-cli
+ ln -sf zerotier-netcon-service zerotier-idtool
+
selftest: $(OBJS) selftest.o
$(CXX) $(CXXFLAGS) -o zerotier-selftest selftest.o $(OBJS) $(LIBS)
$(STRIP) zerotier-selftest
@@ -92,12 +104,12 @@ mac-dist-pkg: FORCE
# For internal use only
official: FORCE
- make clean
+ make ZT_OFFICIAL_RELEASE=1 clean
make -j 4 ZT_OFFICIAL_RELEASE=1
make ZT_OFFICIAL_RELEASE=1 mac-dist-pkg
clean:
- rm -rf *.dSYM build-* *.pkg *.dmg *.o node/*.o controller/*.o service/*.o osdep/*.o ext/http-parser/*.o ext/lz4/*.o ext/json-parser/*.o $(OBJS) zerotier-one zerotier-idtool zerotier-selftest zerotier-cli ZeroTierOneInstaller-* mkworld
+ rm -rf netcon/*.so *.dSYM build-* *.pkg *.dmg *.o node/*.o controller/*.o service/*.o osdep/*.o ext/http-parser/*.o ext/lz4/*.o ext/json-parser/*.o $(OBJS) zerotier-one zerotier-idtool zerotier-selftest zerotier-cli ZeroTierOneInstaller-* mkworld
# For those building from source -- installs signed binary tap driver in system ZT home
install-mac-tap: FORCE
diff --git a/netcon/Intercept.c b/netcon/Intercept.c
index 9c4feedf..48276c96 100644
--- a/netcon/Intercept.c
+++ b/netcon/Intercept.c
@@ -38,20 +38,25 @@
#include <sys/time.h>
#include <pwd.h>
#include <errno.h>
-#include <linux/errno.h>
#include <stdarg.h>
#include <netdb.h>
#include <string.h>
-#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <sys/resource.h>
-#include <linux/net.h> /* for NPROTO */
-#define SOCK_MAX (SOCK_PACKET + 1)
+#if defined(__linux__)
+ #include <linux/errno.h>
+ #include <sys/syscall.h>
+ #include <linux/net.h> /* for NPROTO */
+#endif
+
+#if defined(__linux__)
+ #define SOCK_MAX (SOCK_PACKET + 1)
+#endif
#define SOCK_TYPE_MASK 0xf
#include "Intercept.h"
@@ -92,6 +97,11 @@ static int connected_to_service(int sockfd)
static int set_up_intercept()
{
if (!realconnect) {
+
+#if defined(__linux__)
+ realaccept4 = dlsym(RTLD_NEXT, "accept4");
+ realsyscall = dlsym(RTLD_NEXT, "syscall");
+#endif
realconnect = dlsym(RTLD_NEXT, "connect");
realbind = dlsym(RTLD_NEXT, "bind");
realaccept = dlsym(RTLD_NEXT, "accept");
@@ -100,9 +110,7 @@ static int set_up_intercept()
realbind = dlsym(RTLD_NEXT, "bind");
realsetsockopt = dlsym(RTLD_NEXT, "setsockopt");
realgetsockopt = dlsym(RTLD_NEXT, "getsockopt");
- realaccept4 = dlsym(RTLD_NEXT, "accept4");
realclose = dlsym(RTLD_NEXT, "close");
- realsyscall = dlsym(RTLD_NEXT, "syscall");
realgetsockname = dlsym(RTLD_NEXT, "getsockname");
}
if (!netpath) {
@@ -127,10 +135,12 @@ int setsockopt(SETSOCKOPT_SIG)
return realsetsockopt(socket, level, option_name, option_value, option_len);
dwr(MSG_DEBUG,"setsockopt(%d)\n", socket);
+#if defined(__linux__)
if(level == SOL_IPV6 && option_name == IPV6_V6ONLY)
return 0;
if(level == SOL_IP && (option_name == IP_TTL || option_name == IP_TOS))
return 0;
+#endif
if(level == IPPROTO_TCP || (level == SOL_SOCKET && option_name == SO_KEEPALIVE))
return 0;
if(realsetsockopt(socket, level, option_name, option_value, option_len) < 0)
@@ -169,13 +179,16 @@ int socket(SOCKET_SIG)
dwr(MSG_DEBUG,"socket():\n");
/* Check that type makes sense */
+#if defined(__linux__)
int flags = socket_type & ~SOCK_TYPE_MASK;
if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
errno = EINVAL;
return -1;
}
+#endif
socket_type &= SOCK_TYPE_MASK;
/* Check protocol is in range */
+#if defined(__linux__)
if (socket_family < 0 || socket_family >= NPROTO){
errno = EAFNOSUPPORT;
return -1;
@@ -184,9 +197,12 @@ int socket(SOCKET_SIG)
errno = EINVAL;
return -1;
}
+#endif
/* TODO: detect ENFILE condition */
if(socket_family == AF_LOCAL
+#if defined(__linux__)
|| socket_family == AF_NETLINK
+#endif
|| socket_family == AF_UNIX) {
int err = realsocket(socket_family, socket_type, protocol);
dwr(MSG_DEBUG,"realsocket() = %d\n", err);
@@ -244,24 +260,30 @@ int connect(CONNECT_SIG)
errno = ENOTSOCK;
return -1;
}
+#if defined(__linux__)
/* Check family */
if (connaddr->sin_family < 0 || connaddr->sin_family >= NPROTO){
errno = EAFNOSUPPORT;
return -1;
}
+#endif
/* make sure we don't touch any standard outputs */
if(__fd == STDIN_FILENO || __fd == STDOUT_FILENO || __fd == STDERR_FILENO)
return(realconnect(__fd, __addr, __len));
if(__addr != NULL && (connaddr->sin_family == AF_LOCAL
+#if defined(__linux__)
|| connaddr->sin_family == PF_NETLINK
|| connaddr->sin_family == AF_NETLINK
+#endif
|| connaddr->sin_family == AF_UNIX)) {
return realconnect(__fd, __addr, __len);
}
/* Assemble and send RPC */
struct connect_st rpc_st;
+#if defined(__linux__)
rpc_st.__tid = syscall(SYS_gettid);
+#endif
rpc_st.__fd = __fd;
memcpy(&rpc_st.__addr, __addr, sizeof(struct sockaddr_storage));
memcpy(&rpc_st.__len, &__len, sizeof(socklen_t));
@@ -300,7 +322,9 @@ int bind(BIND_SIG)
connaddr = (struct sockaddr_in *)addr;
if(connaddr->sin_family == AF_LOCAL
+#if defined(__linux__)
|| connaddr->sin_family == AF_NETLINK
+#endif
|| connaddr->sin_family == AF_UNIX) {
int err = realbind(sockfd, addr, addrlen);
dwr(MSG_DEBUG,"realbind, err = %d\n", err);
@@ -317,7 +341,9 @@ int bind(BIND_SIG)
/* Assemble and send RPC */
struct bind_st rpc_st;
rpc_st.sockfd = sockfd;
+#if defined(__linux__)
rpc_st.__tid = syscall(SYS_gettid);
+#endif
memcpy(&rpc_st.addr, addr, sizeof(struct sockaddr_storage));
memcpy(&rpc_st.addrlen, &addrlen, sizeof(socklen_t));
return rpc_send_command(netpath, RPC_BIND, sockfd, &rpc_st, sizeof(struct bind_st));
@@ -328,6 +354,7 @@ int bind(BIND_SIG)
------------------------------------------------------------------------------*/
/* int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags */
+#if defined(__linux__)
int accept4(ACCEPT4_SIG)
{
dwr(MSG_DEBUG,"accept4(%d):\n", sockfd);
@@ -337,6 +364,7 @@ int accept4(ACCEPT4_SIG)
fcntl(sockfd, F_SETFL, O_NONBLOCK);
return accept(sockfd, addr, addrlen);
}
+#endif
/*------------------------------------------------------------------------------
----------------------------------- accept() -----------------------------------
@@ -442,7 +470,9 @@ int listen(LISTEN_SIG)
struct listen_st rpc_st;
rpc_st.sockfd = sockfd;
rpc_st.backlog = backlog;
+#if defined(__linux__)
rpc_st.__tid = syscall(SYS_gettid);
+#endif
return rpc_send_command(netpath, RPC_LISTEN, sockfd, &rpc_st, sizeof(struct listen_st));
}
@@ -502,6 +532,7 @@ int getsockname(GETSOCKNAME_SIG)
------------------------------------ syscall() ---------------------------------
------------------------------------------------------------------------------*/
+#if defined(__linux__)
long syscall(SYSCALL_SIG)
{
va_list ap;
@@ -542,3 +573,4 @@ long syscall(SYSCALL_SIG)
#endif
return realsyscall(number,a,b,c,d,e,f);
}
+#endif \ No newline at end of file
diff --git a/netcon/Intercept.h b/netcon/Intercept.h
index b399993b..9593468f 100644
--- a/netcon/Intercept.h
+++ b/netcon/Intercept.h
@@ -25,12 +25,17 @@
* LLC. Start here: http://www.zerotier.com/
*/
-
#ifndef _INTERCEPT_H
#define _INTERCEPT_H 1
#include <sys/socket.h>
+
+#if defined(__linux__)
+ #define ACCEPT4_SIG int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags
+ #define SYSCALL_SIG long number, ...
+#endif
+
#define CLOSE_SIG int fd
#define READ_SIG int __fd, void *__buf, size_t __nbytes
#define BIND_SIG int sockfd, const struct sockaddr *addr, socklen_t addrlen
@@ -38,7 +43,6 @@
#define WRITE_SIG int __fd, const void *__buf, size_t __n
#define LISTEN_SIG int sockfd, int backlog
#define SOCKET_SIG int socket_family, int socket_type, int protocol
-#define ACCEPT4_SIG int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags
#define ACCEPT_SIG int sockfd, struct sockaddr *addr, socklen_t *addrlen
#define SHUTDOWN_SIG int socket, int how
#define CONNECT_SOCKARG struct sockaddr *
@@ -47,12 +51,17 @@
#define DAEMON_SIG int nochdir, int noclose
#define SETSOCKOPT_SIG int socket, int level, int option_name, const void *option_value, socklen_t option_len
#define GETSOCKOPT_SIG int sockfd, int level, int optname, void *optval, socklen_t *optlen
-#define SYSCALL_SIG long number, ...
#define CLONE_SIG int (*fn)(void *), void *child_stack, int flags, void *arg, ...
#define GETSOCKNAME_SIG int sockfd, struct sockaddr *addr, socklen_t *addrlen
#define DUP2_SIG int oldfd, int newfd
#define DUP3_SIG int oldfd, int newfd, int flags
+
+#if defined(__linux__)
+ int accept4(ACCEPT4_SIG);
+ long syscall(SYSCALL_SIG);
+#endif
+
void my_init(void);
int connect(CONNECT_SIG);
int bind(BIND_SIG);
@@ -61,14 +70,17 @@ int listen(LISTEN_SIG);
int socket(SOCKET_SIG);
int setsockopt(SETSOCKOPT_SIG);
int getsockopt(GETSOCKOPT_SIG);
-int accept4(ACCEPT4_SIG);
-long syscall(SYSCALL_SIG);
int close(CLOSE_SIG);
int clone(CLONE_SIG);
int dup2(DUP2_SIG);
int dup3(DUP3_SIG);
int getsockname(GETSOCKNAME_SIG);
+#if defined(__linux__)
+ static int (*realaccept4)(ACCEPT4_SIG) = 0;
+ static long (*realsyscall)(SYSCALL_SIG) = 0;
+#endif
+
static int (*realconnect)(CONNECT_SIG) = 0;
static int (*realbind)(BIND_SIG) = 0;
static int (*realaccept)(ACCEPT_SIG) = 0;
@@ -76,8 +88,6 @@ static int (*reallisten)(LISTEN_SIG) = 0;
static int (*realsocket)(SOCKET_SIG) = 0;
static int (*realsetsockopt)(SETSOCKOPT_SIG) = 0;
static int (*realgetsockopt)(GETSOCKOPT_SIG) = 0;
-static int (*realaccept4)(ACCEPT4_SIG) = 0;
-static long (*realsyscall)(SYSCALL_SIG) = 0;
static int (*realclose)(CLOSE_SIG) = 0;
static int (*realgetsockname)(GETSOCKNAME_SIG) = 0;
diff --git a/netcon/LWIPStack.hpp b/netcon/LWIPStack.hpp
index fedbdd5f..2ad1a843 100644
--- a/netcon/LWIPStack.hpp
+++ b/netcon/LWIPStack.hpp
@@ -132,7 +132,13 @@ public:
LWIPStack(const char* path) :
_libref(NULL)
{
+
+#if defined(__linux__)
_libref = dlmopen(LM_ID_NEWLM, path, RTLD_NOW);
+#elif defined(__APPLE__)
+ _libref = dlopen(path, RTLD_NOW);
+#endif
+
if(_libref == NULL)
printf("dlerror(): %s\n", dlerror());
diff --git a/netcon/README.md b/netcon/README.md
index 413efc2b..12d48c1d 100644
--- a/netcon/README.md
+++ b/netcon/README.md
@@ -70,6 +70,22 @@ The intercept library does nothing unless the *ZT\_NC\_NETWORK* environment vari
Unlike *zerotier-one*, *zerotier-netcon-service* does not need to be run with root privileges and will not modify the host's network configuration in any way. It can be run alongside *zerotier-one* on the same host with no ill effect, though this can be confusing since you'll have to remember the difference between "real" host interfaces (tun/tap) and network containerized endpoints. The latter are completely unknown to the kernel and will not show up in *ifconfig*.
+# Linking into an application on Mac OSX
+
+Example:
+
+ gcc myapp.c -o myapp libzerotierintercept.so
+ export ZT_NC_NETWORK=/tmp/netcon-test-home/nc_8056c2e21c000001
+
+Start service
+
+ ./zerotier-netcon-service -d -p8000 /tmp/netcon-test-home
+
+Run application
+
+ ./myapp
+
+
# Starting the Network Containers Service
You don't need Docker or any other container engine to try Network Containers. A simple test can be performed in user space (no root) in your own home directory.
@@ -154,9 +170,11 @@ Results will be written to the *netcon/docker-test/_results/* directory which is
To run unit tests:
-1) Set up your own network at [https://my.zerotier.com/](https://my.zerotier.com/). For our example we'll just use the Earth network (8056c2e21c000001). Use its network id as follows:
+1) Disable SELinux. This is so the containers can use a shared volume to exchange MD5 sums and address information.
+
+2) Set up your own network at [https://my.zerotier.com/](https://my.zerotier.com/). For our example we'll just use the Earth network (8056c2e21c000001). Use its network id as follows:
-2) Generate two pairs of identity keys. Each public/private pair will be used by the *netcon* and *monitor* containers:
+3) Generate two pairs of identity keys. Each public/private pair will be used by the *netcon* and *monitor* containers:
mkdir -p /tmp/netcon_first
cp -f ./netcon/liblwip.so /tmp/netcon_first
@@ -176,7 +194,7 @@ To run unit tests:
./zerotier-cli -D/tmp/netcon_second join 8056c2e21c000001
kill `cat /tmp/netcon_second/zerotier-one.pid`
-3) Copy the identity files to your *docker-test* directory. Names will be altered during copy step so the dockerfiles know which identities to use for each image/container:
+4) Copy the identity files to your *docker-test* directory. Names will be altered during copy step so the dockerfiles know which identities to use for each image/container:
cp /tmp/netcon_first/identity.public ./netcon/docker-test/netcon_identity.public
cp /tmp/netcon_first/identity.secret ./netcon/docker-test/netcon_identity.secret
@@ -185,7 +203,7 @@ To run unit tests:
cp /tmp/netcon_second/identity.secret ./netcon/docker-test/monitor_identity.secret
-4) Place a blank network config file in the *netcon/docker-test* directory (e.g. "8056c2e21c000001.conf")
+5) Place a blank network config file in the *netcon/docker-test* directory (e.g. "8056c2e21c000001.conf")
- This will be used to inform test-specific scripts what network to use for testing
After you've created your network and placed its blank config file in *netcon/docker-test* run the following to perform unit tests for httpd:
diff --git a/netcon/RPC.c b/netcon/RPC.c
index a6965892..7d5c11e0 100644
--- a/netcon/RPC.c
+++ b/netcon/RPC.c
@@ -3,7 +3,10 @@
#include <sys/un.h>
#include <pthread.h>
#include <errno.h>
+
+#if defined(__linux__)
#include <sys/syscall.h>
+#endif
#include <fcntl.h>
#include <dlfcn.h>
@@ -70,12 +73,12 @@ int get_retval(int rpc_sock)
int load_symbols_rpc()
{
- #ifdef NETCON_INTERCEPT
+#ifdef NETCON_INTERCEPT
realsocket = dlsym(RTLD_NEXT, "socket");
realconnect = dlsym(RTLD_NEXT, "connect");
if(!realconnect || !realsocket)
return -1;
- #endif
+#endif
return 1;
}
@@ -131,19 +134,22 @@ int rpc_send_command(char *path, int cmd, int forfd, void *data, int len)
memcpy(&cmdbuf[CANARY_IDX], &canary_num, CANARY_SZ);
memcpy(&cmdbuf[STRUCT_IDX], data, len);
-#ifdef VERBOSE
+#if defined(VERBOSE)
+ rpc_count++;
memset(metabuf, 0, BUF_SZ);
+#if defined(__linux__)
pid_t pid = syscall(SYS_getpid);
pid_t tid = syscall(SYS_gettid);
- rpc_count++;
+#endif
char timestring[20];
time_t timestamp;
timestamp = time(NULL);
strftime(timestring, sizeof(timestring), "%H:%M:%S", localtime(&timestamp));
memcpy(metabuf, RPC_PHRASE, RPC_PHRASE_SZ); // Write signal phrase
-
+#if defined(__linux__)
memcpy(&metabuf[IDX_PID], &pid, sizeof(pid_t) ); /* pid */
memcpy(&metabuf[IDX_TID], &tid, sizeof(pid_t) ); /* tid */
+#endif
memcpy(&metabuf[IDX_COUNT], &rpc_count, sizeof(rpc_count) ); /* rpc_count */
memcpy(&metabuf[IDX_TIME], &timestring, 20 ); /* timestamp */
#endif
diff --git a/netcon/docker-test/build_tests.sh b/netcon/docker-test/build_tests.sh
index f360124b..65009f18 100755
--- a/netcon/docker-test/build_tests.sh
+++ b/netcon/docker-test/build_tests.sh
@@ -18,7 +18,7 @@ find . -mindepth 2 -maxdepth 2 -type d | while read testdir; do
continue
fi
- echo "*** Building: '$testdir'..."
+ echo "\n\n\n*** Building: '$testdir'..."
rm _results/*.tmp
# Stage scripts
diff --git a/netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/monitor_dockerfile b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_dockerfile
index d2d2a0cb..d2d2a0cb 100644
--- a/netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/monitor_dockerfile
+++ b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_dockerfile
diff --git a/netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/monitor_entrypoint.sh b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_entrypoint.sh
index c8fca5a3..c8fca5a3 100644
--- a/netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/monitor_entrypoint.sh
+++ b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_entrypoint.sh
diff --git a/netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/netcon_dockerfile b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/netcon_dockerfile
index 90739f10..66a39d88 100644
--- a/netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/netcon_dockerfile
+++ b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/netcon_dockerfile
@@ -4,7 +4,7 @@ MAINTAINER https://www.zerotier.com/
# Install apps
RUN yum -y update
-RUN yum -y install httpd-2.4.17-3.fc23.x86_64
+RUN yum -y install darkhttpd-1.11
RUN yum clean all
EXPOSE 9993/udp 80/udp
diff --git a/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/netcon_entrypoint.sh b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/netcon_entrypoint.sh
new file mode 100644
index 00000000..978696a8
--- /dev/null
+++ b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/netcon_entrypoint.sh
@@ -0,0 +1,46 @@
+#!/bin/bash
+
+export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
+
+
+# --- Test Parameters ---
+test_namefile=$(ls *.name)
+test_name="${test_namefile%.*}" # test network id
+nwconf=$(ls *.conf) # blank test network config file
+nwid="${nwconf%.*}" # test network id
+file_path=/opt/results/ # test result output file path (fs shared between host and containers)
+file_base="$test_name".txt # test result output file
+tmp_ext=.tmp # temporary filetype used for sharing test data between containers
+address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
+bigfile_name=bigfile
+bigfile_size=10M # size of file we want to use for the test
+tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
+
+# --- Network Config ---
+echo '*** ZeroTier Network Containers Test: ' "$test_name"
+chown -R daemon /var/lib/zerotier-one
+chgrp -R daemon /var/lib/zerotier-one
+su daemon -s /bin/bash -c '/zerotier-netcon-service -d -U -p9993 >>/tmp/zerotier-netcon-service.out 2>&1'
+virtip4=""
+while [ -z "$virtip4" ]; do
+ sleep 0.2
+ virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
+ dev=`/zerotier-cli listnetworks | grep -F "" | cut -d ' ' -f 8 | cut -d "_" -f 2 | sed "s/^<dev>//" | tr '\n' '\0'`
+done
+echo '--- Up and running at' $virtip4 ' on network: ' $nwid
+echo '*** Writing address to ' "$address_file"
+echo $virtip4 > "$address_file"
+
+# --- Test section ---
+# Generate large random file for transfer test, share md5sum for monitor container to check
+echo '*** Generating ' "$bigfile_size" ' file'
+dd if=/dev/urandom of="$bigfile_name" bs="$bigfile_size" count=1
+md5sum < "$bigfile_name" > "$tx_md5sumfile"
+echo '*** Wrote MD5 sum to ' "$tx_md5sumfile"
+
+echo '*** Starting application...'
+sleep 0.5
+
+export ZT_NC_NETWORK=/var/lib/zerotier-one/nc_"$dev"
+export LD_PRELOAD=./libzerotierintercept.so
+darkhttpd /
diff --git a/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/monitor_dockerfile b/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/monitor_dockerfile
new file mode 100644
index 00000000..d2d2a0cb
--- /dev/null
+++ b/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/monitor_dockerfile
@@ -0,0 +1,24 @@
+# ZT Network Containers Test Monitor
+FROM fedora:23
+MAINTAINER https://www.zerotier.com/
+
+EXPOSE 9993/udp
+
+# Add ZT files
+RUN mkdir -p /var/lib/zerotier-one/networks.d
+ADD monitor_identity.public /var/lib/zerotier-one/identity.public
+ADD monitor_identity.secret /var/lib/zerotier-one/identity.secret
+ADD *.conf /var/lib/zerotier-one/networks.d/
+ADD *.conf /
+ADD *.name /
+
+# Install LWIP library used by service
+ADD liblwip.so /var/lib/zerotier-one/liblwip.so
+
+ADD zerotier-one /
+ADD zerotier-cli /
+
+# Start ZeroTier-One
+ADD monitor_entrypoint.sh /monitor_entrypoint.sh
+RUN chmod -v +x /monitor_entrypoint.sh
+CMD ["./monitor_entrypoint.sh"]
diff --git a/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/monitor_entrypoint.sh b/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/monitor_entrypoint.sh
new file mode 100644
index 00000000..c8fca5a3
--- /dev/null
+++ b/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/monitor_entrypoint.sh
@@ -0,0 +1,80 @@
+#!/bin/bash
+
+export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
+
+
+# --- Test Parameters ---
+test_namefile=$(ls *.name)
+test_name="${test_namefile%.*}" # test network id
+nwconf=$(ls *.conf) # blank test network config file
+nwid="${nwconf%.*}" # test network id
+netcon_wait_time=35 # wait for test container to come online
+app_timeout_time=25 # app-specific timeout
+file_path=/opt/results/ # test result output file path (fs shared between host and containers)
+file_base="$test_name".txt # test result output file
+fail=FAIL. # appended to result file in event of failure
+ok=OK. # appended to result file in event of success
+tmp_ext=.tmp # temporary filetype used for sharing test data between containers
+address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
+bigfile_name=bigfile # large, random test transfer file
+rx_md5sumfile="$file_path"rx_"$bigfile_name"_md5sum"$tmp_ext"
+tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
+
+
+# --- Network Config ---
+echo '*** ZeroTier Network Containers Test Monitor'
+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'
+virtip4=""
+while [ -z "$virtip4" ]; do
+ sleep 0.2
+ virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
+done
+echo '*** Starting Test...'
+echo '*** Up and running at' $virtip4 ' on network: ' $nwid
+echo '*** Sleeping for (' "$netcon_wait_time" 's ) while we wait for the Network Container to come online...'
+sleep "$netcon_wait_time"s
+ncvirtip=$(<$address_file)
+
+
+# --- Test section ---
+echo '*** Curling from intercepted server at' $ncvirtip
+rm -rf "$file_path"*."$file_base"
+touch "$bigfile_name"
+
+# Perform test
+# curl --connect-timeout "$app_timeout_time" -v -o "$file_path$file_base" http://"$ncvirtip"/index.html
+# Large transfer test
+curl --connect-timeout "$app_timeout_time" -v -o "$bigfile_name" http://"$ncvirtip"/"$bigfile_name"
+
+# Check md5
+md5sum < "$bigfile_name" > "$rx_md5sumfile"
+rx_md5sum=$(<$rx_md5sumfile)
+tx_md5sum=$(<$tx_md5sumfile)
+
+echo '*** Comparing md5: ' "$rx_md5sum" ' and ' "$tx_md5sum"
+
+if [ "$rx_md5sum" != "$tx_md5sum" ];
+then
+ echo 'MD5 FAIL'
+ touch "$file_path$fail$test_name.txt"
+ printf 'Test: md5 sum did not match!\n' >> "$file_path$fail$test_name.txt"
+else
+ echo 'MD5 OK'
+ touch "$file_path$ok$test_name.txt"
+ printf 'Test: md5 sum ok!\n' >> "$file_path$ok$test_name.txt"
+ cat "$rx_md5sumfile" >> "$file_path$ok$test_name.txt"
+ cat "$tx_md5sumfile" >> "$file_path$ok$test_name.txt"
+fi
+
+
+
+
+
+
+
+
+
+
+
diff --git a/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/netcon_dockerfile b/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/netcon_dockerfile
new file mode 100644
index 00000000..3053a832
--- /dev/null
+++ b/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/netcon_dockerfile
@@ -0,0 +1,38 @@
+# ZT Network Containers Test
+FROM fedora:23
+MAINTAINER https://www.zerotier.com/
+
+# Install apps
+RUN yum -y update
+RUN yum -y install httpd-2.4.18-1.fc23.x86_64
+RUN yum clean all
+
+EXPOSE 9993/udp 80/udp
+
+# Add ZT files
+RUN mkdir -p /var/lib/zerotier-one/networks.d
+ADD netcon_identity.public /var/lib/zerotier-one/identity.public
+ADD netcon_identity.secret /var/lib/zerotier-one/identity.secret
+ADD *.conf /var/lib/zerotier-one/networks.d/
+ADD *.conf /
+ADD *.name /
+
+# Install LWIP library used by service
+ADD liblwip.so /var/lib/zerotier-one/liblwip.so
+
+# Install syscall intercept library
+ADD zerotier-intercept /
+ADD libzerotierintercept.so /
+RUN cp libzerotierintercept.so lib/libzerotierintercept.so
+RUN ln -sf /lib/libzerotierintercept.so /lib/libzerotierintercept
+RUN /usr/bin/install -c zerotier-intercept /usr/bin
+
+ADD zerotier-cli /
+ADD zerotier-netcon-service /
+
+# Install test scripts
+ADD netcon_entrypoint.sh /netcon_entrypoint.sh
+RUN chmod -v +x /netcon_entrypoint.sh
+
+# Start ZeroTier-One
+CMD ["./netcon_entrypoint.sh"]
diff --git a/netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/netcon_entrypoint.sh b/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/netcon_entrypoint.sh
index d2ab248a..d2ab248a 100644
--- a/netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/netcon_entrypoint.sh
+++ b/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/netcon_entrypoint.sh
diff --git a/netcon/docker-test/python/python/monitor_dockerfile b/netcon/docker-test/python/python/monitor_dockerfile
new file mode 100644
index 00000000..d2d2a0cb
--- /dev/null
+++ b/netcon/docker-test/python/python/monitor_dockerfile
@@ -0,0 +1,24 @@
+# ZT Network Containers Test Monitor
+FROM fedora:23
+MAINTAINER https://www.zerotier.com/
+
+EXPOSE 9993/udp
+
+# Add ZT files
+RUN mkdir -p /var/lib/zerotier-one/networks.d
+ADD monitor_identity.public /var/lib/zerotier-one/identity.public
+ADD monitor_identity.secret /var/lib/zerotier-one/identity.secret
+ADD *.conf /var/lib/zerotier-one/networks.d/
+ADD *.conf /
+ADD *.name /
+
+# Install LWIP library used by service
+ADD liblwip.so /var/lib/zerotier-one/liblwip.so
+
+ADD zerotier-one /
+ADD zerotier-cli /
+
+# Start ZeroTier-One
+ADD monitor_entrypoint.sh /monitor_entrypoint.sh
+RUN chmod -v +x /monitor_entrypoint.sh
+CMD ["./monitor_entrypoint.sh"]
diff --git a/netcon/docker-test/python/python/monitor_entrypoint.sh b/netcon/docker-test/python/python/monitor_entrypoint.sh
new file mode 100644
index 00000000..c8fca5a3
--- /dev/null
+++ b/netcon/docker-test/python/python/monitor_entrypoint.sh
@@ -0,0 +1,80 @@
+#!/bin/bash
+
+export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
+
+
+# --- Test Parameters ---
+test_namefile=$(ls *.name)
+test_name="${test_namefile%.*}" # test network id
+nwconf=$(ls *.conf) # blank test network config file
+nwid="${nwconf%.*}" # test network id
+netcon_wait_time=35 # wait for test container to come online
+app_timeout_time=25 # app-specific timeout
+file_path=/opt/results/ # test result output file path (fs shared between host and containers)
+file_base="$test_name".txt # test result output file
+fail=FAIL. # appended to result file in event of failure
+ok=OK. # appended to result file in event of success
+tmp_ext=.tmp # temporary filetype used for sharing test data between containers
+address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
+bigfile_name=bigfile # large, random test transfer file
+rx_md5sumfile="$file_path"rx_"$bigfile_name"_md5sum"$tmp_ext"
+tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
+
+
+# --- Network Config ---
+echo '*** ZeroTier Network Containers Test Monitor'
+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'
+virtip4=""
+while [ -z "$virtip4" ]; do
+ sleep 0.2
+ virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
+done
+echo '*** Starting Test...'
+echo '*** Up and running at' $virtip4 ' on network: ' $nwid
+echo '*** Sleeping for (' "$netcon_wait_time" 's ) while we wait for the Network Container to come online...'
+sleep "$netcon_wait_time"s
+ncvirtip=$(<$address_file)
+
+
+# --- Test section ---
+echo '*** Curling from intercepted server at' $ncvirtip
+rm -rf "$file_path"*."$file_base"
+touch "$bigfile_name"
+
+# Perform test
+# curl --connect-timeout "$app_timeout_time" -v -o "$file_path$file_base" http://"$ncvirtip"/index.html
+# Large transfer test
+curl --connect-timeout "$app_timeout_time" -v -o "$bigfile_name" http://"$ncvirtip"/"$bigfile_name"
+
+# Check md5
+md5sum < "$bigfile_name" > "$rx_md5sumfile"
+rx_md5sum=$(<$rx_md5sumfile)
+tx_md5sum=$(<$tx_md5sumfile)
+
+echo '*** Comparing md5: ' "$rx_md5sum" ' and ' "$tx_md5sum"
+
+if [ "$rx_md5sum" != "$tx_md5sum" ];
+then
+ echo 'MD5 FAIL'
+ touch "$file_path$fail$test_name.txt"
+ printf 'Test: md5 sum did not match!\n' >> "$file_path$fail$test_name.txt"
+else
+ echo 'MD5 OK'
+ touch "$file_path$ok$test_name.txt"
+ printf 'Test: md5 sum ok!\n' >> "$file_path$ok$test_name.txt"
+ cat "$rx_md5sumfile" >> "$file_path$ok$test_name.txt"
+ cat "$tx_md5sumfile" >> "$file_path$ok$test_name.txt"
+fi
+
+
+
+
+
+
+
+
+
+
+
diff --git a/netcon/docker-test/python/python/netcon_dockerfile b/netcon/docker-test/python/python/netcon_dockerfile
new file mode 100644
index 00000000..6646f670
--- /dev/null
+++ b/netcon/docker-test/python/python/netcon_dockerfile
@@ -0,0 +1,38 @@
+# ZT Network Containers Test
+FROM fedora:23
+MAINTAINER https://www.zerotier.com/
+
+# Install apps
+RUN yum -y update
+RUN yum -y install python
+RUN yum clean all
+
+EXPOSE 9993/udp 80/udp
+
+# Add ZT files
+RUN mkdir -p /var/lib/zerotier-one/networks.d
+ADD netcon_identity.public /var/lib/zerotier-one/identity.public
+ADD netcon_identity.secret /var/lib/zerotier-one/identity.secret
+ADD *.conf /var/lib/zerotier-one/networks.d/
+ADD *.conf /
+ADD *.name /
+
+# Install LWIP library used by service
+ADD liblwip.so /var/lib/zerotier-one/liblwip.so
+
+# Install syscall intercept library
+ADD zerotier-intercept /
+ADD libzerotierintercept.so /
+RUN cp libzerotierintercept.so lib/libzerotierintercept.so
+RUN ln -sf /lib/libzerotierintercept.so /lib/libzerotierintercept
+RUN /usr/bin/install -c zerotier-intercept /usr/bin
+
+ADD zerotier-cli /
+ADD zerotier-netcon-service /
+
+# Install test scripts
+ADD netcon_entrypoint.sh /netcon_entrypoint.sh
+RUN chmod -v +x /netcon_entrypoint.sh
+
+# Start ZeroTier-One
+CMD ["./netcon_entrypoint.sh"]
diff --git a/netcon/docker-test/python/python/netcon_entrypoint.sh b/netcon/docker-test/python/python/netcon_entrypoint.sh
new file mode 100644
index 00000000..5e1a19b8
--- /dev/null
+++ b/netcon/docker-test/python/python/netcon_entrypoint.sh
@@ -0,0 +1,46 @@
+#!/bin/bash
+
+export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
+
+
+# --- Test Parameters ---
+test_namefile=$(ls *.name)
+test_name="${test_namefile%.*}" # test network id
+nwconf=$(ls *.conf) # blank test network config file
+nwid="${nwconf%.*}" # test network id
+file_path=/opt/results/ # test result output file path (fs shared between host and containers)
+file_base="$test_name".txt # test result output file
+tmp_ext=.tmp # temporary filetype used for sharing test data between containers
+address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
+bigfile_name=bigfile
+bigfile_size=10M # size of file we want to use for the test
+tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
+
+# --- Network Config ---
+echo '*** ZeroTier Network Containers Test: ' "$test_name"
+chown -R daemon /var/lib/zerotier-one
+chgrp -R daemon /var/lib/zerotier-one
+su daemon -s /bin/bash -c '/zerotier-netcon-service -d -U -p9993 >>/tmp/zerotier-netcon-service.out 2>&1'
+virtip4=""
+while [ -z "$virtip4" ]; do
+ sleep 0.2
+ virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
+ dev=`/zerotier-cli listnetworks | grep -F "" | cut -d ' ' -f 8 | cut -d "_" -f 2 | sed "s/^<dev>//" | tr '\n' '\0'`
+done
+echo '--- Up and running at' $virtip4 ' on network: ' $nwid
+echo '*** Writing address to ' "$address_file"
+echo $virtip4 > "$address_file"
+
+# --- Test section ---
+# Generate large random file for transfer test, share md5sum for monitor container to check
+echo '*** Generating ' "$bigfile_size" ' file'
+dd if=/dev/urandom of="$bigfile_name" bs="$bigfile_size" count=1
+md5sum < "$bigfile_name" > "$tx_md5sumfile"
+echo '*** Wrote MD5 sum to ' "$tx_md5sumfile"
+
+echo '*** Starting application...'
+sleep 0.5
+
+export ZT_NC_NETWORK=/var/lib/zerotier-one/nc_"$dev"
+export LD_PRELOAD=./libzerotierintercept.so
+python -m SimpleHTTPServer 80
diff --git a/netcon/docker-test/python/python3/monitor_dockerfile b/netcon/docker-test/python/python3/monitor_dockerfile
new file mode 100644
index 00000000..d2d2a0cb
--- /dev/null
+++ b/netcon/docker-test/python/python3/monitor_dockerfile
@@ -0,0 +1,24 @@
+# ZT Network Containers Test Monitor
+FROM fedora:23
+MAINTAINER https://www.zerotier.com/
+
+EXPOSE 9993/udp
+
+# Add ZT files
+RUN mkdir -p /var/lib/zerotier-one/networks.d
+ADD monitor_identity.public /var/lib/zerotier-one/identity.public
+ADD monitor_identity.secret /var/lib/zerotier-one/identity.secret
+ADD *.conf /var/lib/zerotier-one/networks.d/
+ADD *.conf /
+ADD *.name /
+
+# Install LWIP library used by service
+ADD liblwip.so /var/lib/zerotier-one/liblwip.so
+
+ADD zerotier-one /
+ADD zerotier-cli /
+
+# Start ZeroTier-One
+ADD monitor_entrypoint.sh /monitor_entrypoint.sh
+RUN chmod -v +x /monitor_entrypoint.sh
+CMD ["./monitor_entrypoint.sh"]
diff --git a/netcon/docker-test/python/python3/monitor_entrypoint.sh b/netcon/docker-test/python/python3/monitor_entrypoint.sh
new file mode 100644
index 00000000..c8fca5a3
--- /dev/null
+++ b/netcon/docker-test/python/python3/monitor_entrypoint.sh
@@ -0,0 +1,80 @@
+#!/bin/bash
+
+export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
+
+
+# --- Test Parameters ---
+test_namefile=$(ls *.name)
+test_name="${test_namefile%.*}" # test network id
+nwconf=$(ls *.conf) # blank test network config file
+nwid="${nwconf%.*}" # test network id
+netcon_wait_time=35 # wait for test container to come online
+app_timeout_time=25 # app-specific timeout
+file_path=/opt/results/ # test result output file path (fs shared between host and containers)
+file_base="$test_name".txt # test result output file
+fail=FAIL. # appended to result file in event of failure
+ok=OK. # appended to result file in event of success
+tmp_ext=.tmp # temporary filetype used for sharing test data between containers
+address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
+bigfile_name=bigfile # large, random test transfer file
+rx_md5sumfile="$file_path"rx_"$bigfile_name"_md5sum"$tmp_ext"
+tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
+
+
+# --- Network Config ---
+echo '*** ZeroTier Network Containers Test Monitor'
+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'
+virtip4=""
+while [ -z "$virtip4" ]; do
+ sleep 0.2
+ virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
+done
+echo '*** Starting Test...'
+echo '*** Up and running at' $virtip4 ' on network: ' $nwid
+echo '*** Sleeping for (' "$netcon_wait_time" 's ) while we wait for the Network Container to come online...'
+sleep "$netcon_wait_time"s
+ncvirtip=$(<$address_file)
+
+
+# --- Test section ---
+echo '*** Curling from intercepted server at' $ncvirtip
+rm -rf "$file_path"*."$file_base"
+touch "$bigfile_name"
+
+# Perform test
+# curl --connect-timeout "$app_timeout_time" -v -o "$file_path$file_base" http://"$ncvirtip"/index.html
+# Large transfer test
+curl --connect-timeout "$app_timeout_time" -v -o "$bigfile_name" http://"$ncvirtip"/"$bigfile_name"
+
+# Check md5
+md5sum < "$bigfile_name" > "$rx_md5sumfile"
+rx_md5sum=$(<$rx_md5sumfile)
+tx_md5sum=$(<$tx_md5sumfile)
+
+echo '*** Comparing md5: ' "$rx_md5sum" ' and ' "$tx_md5sum"
+
+if [ "$rx_md5sum" != "$tx_md5sum" ];
+then
+ echo 'MD5 FAIL'
+ touch "$file_path$fail$test_name.txt"
+ printf 'Test: md5 sum did not match!\n' >> "$file_path$fail$test_name.txt"
+else
+ echo 'MD5 OK'
+ touch "$file_path$ok$test_name.txt"
+ printf 'Test: md5 sum ok!\n' >> "$file_path$ok$test_name.txt"
+ cat "$rx_md5sumfile" >> "$file_path$ok$test_name.txt"
+ cat "$tx_md5sumfile" >> "$file_path$ok$test_name.txt"
+fi
+
+
+
+
+
+
+
+
+
+
+
diff --git a/netcon/docker-test/python/python3/netcon_dockerfile b/netcon/docker-test/python/python3/netcon_dockerfile
new file mode 100644
index 00000000..f960fa30
--- /dev/null
+++ b/netcon/docker-test/python/python3/netcon_dockerfile
@@ -0,0 +1,37 @@
+# ZT Network Containers Test
+FROM fedora:23
+MAINTAINER https://www.zerotier.com/
+
+# Install apps
+RUN yum -y update
+RUN yum clean all
+
+EXPOSE 9993/udp 80/udp
+
+# Add ZT files
+RUN mkdir -p /var/lib/zerotier-one/networks.d
+ADD netcon_identity.public /var/lib/zerotier-one/identity.public
+ADD netcon_identity.secret /var/lib/zerotier-one/identity.secret
+ADD *.conf /var/lib/zerotier-one/networks.d/
+ADD *.conf /
+ADD *.name /
+
+# Install LWIP library used by service
+ADD liblwip.so /var/lib/zerotier-one/liblwip.so
+
+# Install syscall intercept library
+ADD zerotier-intercept /
+ADD libzerotierintercept.so /
+RUN cp libzerotierintercept.so lib/libzerotierintercept.so
+RUN ln -sf /lib/libzerotierintercept.so /lib/libzerotierintercept
+RUN /usr/bin/install -c zerotier-intercept /usr/bin
+
+ADD zerotier-cli /
+ADD zerotier-netcon-service /
+
+# Install test scripts
+ADD netcon_entrypoint.sh /netcon_entrypoint.sh
+RUN chmod -v +x /netcon_entrypoint.sh
+
+# Start ZeroTier-One
+CMD ["./netcon_entrypoint.sh"]
diff --git a/netcon/docker-test/python/python3/netcon_entrypoint.sh b/netcon/docker-test/python/python3/netcon_entrypoint.sh
new file mode 100644
index 00000000..c3c8b281
--- /dev/null
+++ b/netcon/docker-test/python/python3/netcon_entrypoint.sh
@@ -0,0 +1,46 @@
+#!/bin/bash
+
+export PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/
+
+
+# --- Test Parameters ---
+test_namefile=$(ls *.name)
+test_name="${test_namefile%.*}" # test network id
+nwconf=$(ls *.conf) # blank test network config file
+nwid="${nwconf%.*}" # test network id
+file_path=/opt/results/ # test result output file path (fs shared between host and containers)
+file_base="$test_name".txt # test result output file
+tmp_ext=.tmp # temporary filetype used for sharing test data between containers
+address_file="$file_path$test_name"_addr"$tmp_ext" # file shared between host and containers for sharing address (optional)
+bigfile_name=bigfile
+bigfile_size=10M # size of file we want to use for the test
+tx_md5sumfile="$file_path"tx_"$bigfile_name"_md5sum"$tmp_ext"
+
+# --- Network Config ---
+echo '*** ZeroTier Network Containers Test: ' "$test_name"
+chown -R daemon /var/lib/zerotier-one
+chgrp -R daemon /var/lib/zerotier-one
+su daemon -s /bin/bash -c '/zerotier-netcon-service -d -U -p9993 >>/tmp/zerotier-netcon-service.out 2>&1'
+virtip4=""
+while [ -z "$virtip4" ]; do
+ sleep 0.2
+ virtip4=`/zerotier-cli listnetworks | grep -F $nwid | cut -d ' ' -f 9 | sed 's/,/\n/g' | grep -F '.' | cut -d / -f 1`
+ dev=`/zerotier-cli listnetworks | grep -F "" | cut -d ' ' -f 8 | cut -d "_" -f 2 | sed "s/^<dev>//" | tr '\n' '\0'`
+done
+echo '--- Up and running at' $virtip4 ' on network: ' $nwid
+echo '*** Writing address to ' "$address_file"
+echo $virtip4 > "$address_file"
+
+# --- Test section ---
+# Generate large random file for transfer test, share md5sum for monitor container to check
+echo '*** Generating ' "$bigfile_size" ' file'
+dd if=/dev/urandom of="$bigfile_name" bs="$bigfile_size" count=1
+md5sum < "$bigfile_name" > "$tx_md5sumfile"
+echo '*** Wrote MD5 sum to ' "$tx_md5sumfile"
+
+echo '*** Starting application...'
+sleep 0.5
+
+export ZT_NC_NETWORK=/var/lib/zerotier-one/nc_"$dev"
+export LD_PRELOAD=./libzerotierintercept.so
+python3 -m http.server 80
diff --git a/node/CertificateOfMembership.hpp b/node/CertificateOfMembership.hpp
index c6d59397..9a279883 100644
--- a/node/CertificateOfMembership.hpp
+++ b/node/CertificateOfMembership.hpp
@@ -33,6 +33,16 @@
#include "Identity.hpp"
#include "Utils.hpp"
+/**
+ * Default window of time for certificate agreement
+ *
+ * Right now we use time for 'revision' so this is the maximum time divergence
+ * between two certs for them to agree. It comes out to five minutes, which
+ * gives a lot of margin for error if the controller hiccups or its clock
+ * drifts but causes de-authorized peers to fall off fast enough.
+ */
+#define ZT_NETWORK_COM_DEFAULT_REVISION_MAX_DELTA (ZT_NETWORK_AUTOCONF_DELAY * 5)
+
namespace ZeroTier {
/**
diff --git a/node/Cluster.cpp b/node/Cluster.cpp
index e4c4524a..61903307 100644
--- a/node/Cluster.cpp
+++ b/node/Cluster.cpp
@@ -570,10 +570,19 @@ void Cluster::sendViaCluster(const Address &fromPeerAddress,const Address &toPee
Mutex::Lock _l2(_members[mostRecentMemberId].lock);
if (buf.size() > 0)
_send(mostRecentMemberId,CLUSTER_MESSAGE_PROXY_UNITE,buf.data(),buf.size());
- if (_members[mostRecentMemberId].zeroTierPhysicalEndpoints.size() > 0) {
- TRACE("sendViaCluster relaying %u bytes from %s to %s by way of %u",len,fromPeerAddress.toString().c_str(),toPeerAddress.toString().c_str(),(unsigned int)mostRecentMemberId);
- RR->node->putPacket(InetAddress(),_members[mostRecentMemberId].zeroTierPhysicalEndpoints.front(),data,len);
+
+ for(std::vector<InetAddress>::const_iterator i1(_zeroTierPhysicalEndpoints.begin());i1!=_zeroTierPhysicalEndpoints.end();++i1) {
+ for(std::vector<InetAddress>::const_iterator i2(_members[mostRecentMemberId].zeroTierPhysicalEndpoints.begin());i2!=_members[mostRecentMemberId].zeroTierPhysicalEndpoints.end();++i2) {
+ if (i1->ss_family == i2->ss_family) {
+ TRACE("sendViaCluster relaying %u bytes from %s to %s by way of %u (%s->%s)",len,fromPeerAddress.toString().c_str(),toPeerAddress.toString().c_str(),(unsigned int)mostRecentMemberId,i1->toString().c_str(),i2->toString().c_str());
+ RR->node->putPacket(*i1,*i2,data,len);
+ return;
+ }
+ }
}
+
+ TRACE("sendViaCluster relaying %u bytes from %s to %s by way of %u failed: no common endpoints with the same address family!",len,fromPeerAddress.toString().c_str(),toPeerAddress.toString().c_str(),(unsigned int)mostRecentMemberId);
+ return;
}
}
diff --git a/node/Cluster.hpp b/node/Cluster.hpp
index e21d6020..dafbf425 100644
--- a/node/Cluster.hpp
+++ b/node/Cluster.hpp
@@ -47,22 +47,22 @@
/**
* Desired period between doPeriodicTasks() in milliseconds
*/
-#define ZT_CLUSTER_PERIODIC_TASK_PERIOD 50
+#define ZT_CLUSTER_PERIODIC_TASK_PERIOD 20
/**
* How often to flush outgoing message queues (maximum interval)
*/
-#define ZT_CLUSTER_FLUSH_PERIOD 100
+#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 8
+#define ZT_CLUSTER_MAX_QUEUE_PER_SENDER 16
/**
* Expiration time for send queue entries
*/
-#define ZT_CLUSTER_QUEUE_EXPIRATION 5000
+#define ZT_CLUSTER_QUEUE_EXPIRATION 3000
/**
* Chunk size for allocating queue entries
@@ -85,11 +85,8 @@
/**
* Max data per queue entry
- *
- * If we ever support larger transport MTUs this must be increased. The plus
- * 16 is just a small margin and has no special meaning.
*/
-#define ZT_CLUSTER_SEND_QUEUE_DATA_MAX (ZT_UDP_DEFAULT_PAYLOAD_MTU + 16)
+#define ZT_CLUSTER_SEND_QUEUE_DATA_MAX 1500
namespace ZeroTier {
diff --git a/node/Constants.hpp b/node/Constants.hpp
index 4d6c9d07..6c44a8dc 100644
--- a/node/Constants.hpp
+++ b/node/Constants.hpp
@@ -51,8 +51,20 @@
#include <endian.h>
#endif
-// Disable type punning on ARM architecture -- some ARM chips throw SIGBUS on unaligned access
-#if defined(__arm__) || defined(__ARMEL__)
+#ifdef __APPLE__
+#include <TargetConditionals.h>
+#ifndef __UNIX_LIKE__
+#define __UNIX_LIKE__
+#endif
+#ifndef __BSD__
+#define __BSD__
+#endif
+#include <machine/endian.h>
+#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
@@ -73,18 +85,6 @@
#endif
#endif
-// TODO: Android is what? Linux technically, but does it define it?
-
-#ifdef __APPLE__
-#include <TargetConditionals.h>
-#ifndef __UNIX_LIKE__
-#define __UNIX_LIKE__
-#endif
-#ifndef __BSD__
-#define __BSD__
-#endif
-#endif
-
#if defined(_WIN32) || defined(_WIN64)
#ifndef __WINDOWS__
#define __WINDOWS__
@@ -104,9 +104,8 @@
#include <Windows.h>
#endif
-// Assume these are little-endian. PPC is not supported for OSX, and ARM
-// runs in little-endian mode for these OS families.
-#if defined(__APPLE__) || defined(__WINDOWS__)
+// Assume little endian if not defined
+#if (defined(__APPLE__) || defined(__WINDOWS__)) && (!defined(__BYTE_ORDER))
#undef __BYTE_ORDER
#undef __LITTLE_ENDIAN
#undef __BIG_ENDIAN
@@ -163,9 +162,17 @@
#define ZT_MAX_PACKET_FRAGMENTS 4
/**
- * Timeout for receipt of fragmented packets in ms
+ * Size of RX queue
+ *
+ * This is about 2mb, and can be decreased for small devices. A queue smaller
+ * than about 4 is probably going to cause a lot of lost packets.
+ */
+#define ZT_RX_QUEUE_SIZE 64
+
+/**
+ * RX queue entries older than this do not "exist"
*/
-#define ZT_FRAGMENTED_PACKET_RECEIVE_TIMEOUT 500
+#define ZT_RX_QUEUE_EXPIRE 4000
/**
* Length of secret key in bytes -- 256-bit -- do not change
@@ -255,12 +262,17 @@
/**
* Delay between ordinary case pings of direct links
*/
-#define ZT_PEER_DIRECT_PING_DELAY 90000
+#define ZT_PEER_DIRECT_PING_DELAY 60000
/**
* Timeout for overall peer activity (measured from last receive)
*/
-#define ZT_PEER_ACTIVITY_TIMEOUT ((ZT_PEER_DIRECT_PING_DELAY * 4) + ZT_PING_CHECK_INVERVAL)
+#define ZT_PEER_ACTIVITY_TIMEOUT 500000
+
+/**
+ * Timeout for path activity
+ */
+#define ZT_PATH_ACTIVITY_TIMEOUT ZT_PEER_ACTIVITY_TIMEOUT
/**
* No answer timeout to trigger dead path detection
@@ -354,6 +366,15 @@
*/
#define ZT_TEST_NETWORK_ID 0xffffffffffffffffULL
+/**
+ * Desired buffer size for UDP sockets (used in service and osdep but defined here)
+ */
+#if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__))
+#define ZT_UDP_DESIRED_BUF_SIZE 1048576
+#else
+#define ZT_UDP_DESIRED_BUF_SIZE 131072
+#endif
+
/* Ethernet frame types that might be relevant to us */
#define ZT_ETHERTYPE_IPV4 0x0800
#define ZT_ETHERTYPE_ARP 0x0806
diff --git a/node/DeferredPackets.cpp b/node/DeferredPackets.cpp
index c8e63fc8..192b4078 100644
--- a/node/DeferredPackets.cpp
+++ b/node/DeferredPackets.cpp
@@ -26,8 +26,6 @@ namespace ZeroTier {
DeferredPackets::DeferredPackets(const RuntimeEnvironment *renv) :
RR(renv),
- _readPtr(0),
- _writePtr(0),
_waiting(0),
_die(false)
{
@@ -37,39 +35,45 @@ DeferredPackets::~DeferredPackets()
{
_q_m.lock();
_die = true;
- while (_waiting > 0) {
- _q_m.unlock();
+ _q_m.unlock();
+
+ for(;;) {
_q_s.post();
+
_q_m.lock();
+ if (_waiting <= 0) {
+ _q_m.unlock();
+ break;
+ } else {
+ _q_m.unlock();
+ }
}
}
bool DeferredPackets::enqueue(IncomingPacket *pkt)
{
- _q_m.lock();
- const unsigned long p = _writePtr % ZT_DEFFEREDPACKETS_MAX;
- if (_q[p]) {
- _q_m.unlock();
- return false;
- } else {
- _q[p].setToUnsafe(pkt);
- ++_writePtr;
- _q_m.unlock();
- _q_s.post();
- return true;
+ {
+ Mutex::Lock _l(_q_m);
+ if (_q.size() >= ZT_DEFFEREDPACKETS_MAX)
+ return false;
+ _q.push_back(*pkt);
}
+ _q_s.post();
+ return true;
}
int DeferredPackets::process()
{
- SharedPtr<IncomingPacket> pkt;
+ std::list<IncomingPacket> pkt;
_q_m.lock();
+
if (_die) {
_q_m.unlock();
return -1;
}
- while (_readPtr == _writePtr) {
+
+ while (_q.empty()) {
++_waiting;
_q_m.unlock();
_q_s.wait();
@@ -80,10 +84,16 @@ int DeferredPackets::process()
return -1;
}
}
- pkt.swap(_q[_readPtr++ % ZT_DEFFEREDPACKETS_MAX]);
+
+ // Move item from _q list to a dummy list here to avoid copying packet
+ pkt.splice(pkt.end(),_q,_q.begin());
+
_q_m.unlock();
- pkt->tryDecode(RR,true);
+ try {
+ pkt.front().tryDecode(RR,true);
+ } catch ( ... ) {} // drop invalids
+
return 1;
}
diff --git a/node/DeferredPackets.hpp b/node/DeferredPackets.hpp
index 5ba26531..a9855396 100644
--- a/node/DeferredPackets.hpp
+++ b/node/DeferredPackets.hpp
@@ -19,6 +19,8 @@
#ifndef ZT_DEFERREDPACKETS_HPP
#define ZT_DEFERREDPACKETS_HPP
+#include <list>
+
#include "Constants.hpp"
#include "SharedPtr.hpp"
#include "Mutex.hpp"
@@ -28,7 +30,7 @@
/**
* Maximum number of deferred packets
*/
-#define ZT_DEFFEREDPACKETS_MAX 1024
+#define ZT_DEFFEREDPACKETS_MAX 256
namespace ZeroTier {
@@ -53,11 +55,6 @@ public:
/**
* Enqueue a packet
*
- * Since packets enqueue themselves, they call it with 'this' and we wrap
- * them in a SharedPtr<>. This is safe as SharedPtr<> is introspective and
- * supports this. This should not be called from any other code outside
- * IncomingPacket.
- *
* @param pkt Packet to process later (possibly in the background)
* @return False if queue is full
*/
@@ -75,10 +72,8 @@ public:
int process();
private:
- SharedPtr<IncomingPacket> _q[ZT_DEFFEREDPACKETS_MAX];
+ std::list<IncomingPacket> _q;
const RuntimeEnvironment *const RR;
- unsigned long _readPtr;
- unsigned long _writePtr;
volatile int _waiting;
volatile bool _die;
Mutex _q_m;
diff --git a/node/IncomingPacket.cpp b/node/IncomingPacket.cpp
index efb43d23..35c78b29 100644
--- a/node/IncomingPacket.cpp
+++ b/node/IncomingPacket.cpp
@@ -282,7 +282,7 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,SharedPtr<Peer> &peer
}
if (externalSurfaceAddress)
- RR->sa->iam(id.address(),_remoteAddress,externalSurfaceAddress,RR->topology->isRoot(id),RR->node->now());
+ RR->sa->iam(id.address(),_localAddress,_remoteAddress,externalSurfaceAddress,RR->topology->isRoot(id),RR->node->now());
Packet outp(id.address(),RR->identity.address(),Packet::VERB_OK);
outp.append((unsigned char)Packet::VERB_HELLO);
@@ -388,7 +388,7 @@ bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,const SharedPtr<Peer> &p
peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
if (externalSurfaceAddress)
- RR->sa->iam(peer->address(),_remoteAddress,externalSurfaceAddress,trusted,RR->node->now());
+ RR->sa->iam(peer->address(),_localAddress,_remoteAddress,externalSurfaceAddress,trusted,RR->node->now());
} break;
case Packet::VERB_WHOIS: {
@@ -934,10 +934,10 @@ bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,const Sha
switch(addrType) {
case 4: {
InetAddress a(field(ptr,4),4,at<uint16_t>(ptr + 4));
- if ( ((flags & 0x01) == 0) && (Path::isAddressValidForPath(a)) && (!peer->hasActivePathTo(now,a)) && (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,a)) ) {
+ if ( ((flags & 0x01) == 0) && (!peer->hasActivePathTo(now,a)) && (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,a)) ) {
if (++countPerScope[(int)a.ipScope()][0] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str());
- peer->sendHELLO(_localAddress,a,now);
+ peer->sendHELLO(InetAddress(),a,now);
} else {
TRACE("ignoring contact for %s at %s -- too many per scope",peer->address().toString().c_str(),a.toString().c_str());
}
@@ -945,10 +945,10 @@ bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,const Sha
} break;
case 6: {
InetAddress a(field(ptr,16),16,at<uint16_t>(ptr + 16));
- if ( ((flags & 0x01) == 0) && (Path::isAddressValidForPath(a)) && (!peer->hasActivePathTo(now,a)) && (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,a)) ) {
+ if ( ((flags & 0x01) == 0) && (!peer->hasActivePathTo(now,a)) && (RR->node->shouldUsePathForZeroTierTraffic(_localAddress,a)) ) {
if (++countPerScope[(int)a.ipScope()][1] <= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY) {
TRACE("attempting to contact %s at pushed direct path %s",peer->address().toString().c_str(),a.toString().c_str());
- peer->sendHELLO(_localAddress,a,now);
+ peer->sendHELLO(InetAddress(),a,now);
} else {
TRACE("ignoring contact for %s at %s -- too many per scope",peer->address().toString().c_str(),a.toString().c_str());
}
@@ -1016,8 +1016,9 @@ bool IncomingPacket::_doCIRCUIT_TEST(const RuntimeEnvironment *RR,const SharedPt
if (previousHopCredentialLength >= 1) {
switch((*this)[ZT_PACKET_IDX_PAYLOAD + 31 + vlf]) {
case 0x01: { // network certificate of membership for previous hop
- if (previousHopCom.deserialize(*this,ZT_PACKET_IDX_PAYLOAD + 32 + vlf) != (previousHopCredentialLength - 1)) {
- TRACE("dropped CIRCUIT_TEST from %s(%s): previous hop COM invalid",source().toString().c_str(),_remoteAddress.toString().c_str());
+ const unsigned int phcl = previousHopCom.deserialize(*this,ZT_PACKET_IDX_PAYLOAD + 32 + vlf);
+ if (phcl != (previousHopCredentialLength - 1)) {
+ TRACE("dropped CIRCUIT_TEST from %s(%s): previous hop COM invalid (%u != %u)",source().toString().c_str(),_remoteAddress.toString().c_str(),phcl,(previousHopCredentialLength - 1));
return true;
}
} break;
@@ -1033,7 +1034,7 @@ bool IncomingPacket::_doCIRCUIT_TEST(const RuntimeEnvironment *RR,const SharedPt
SharedPtr<Network> nw(RR->node->network(originatorCredentialNetworkId));
if (nw) {
originatorCredentialNetworkConfig = nw->config2();
- if ( (originatorCredentialNetworkConfig) && ((originatorCredentialNetworkConfig->isPublic())||(peer->address() == originatorAddress)||((originatorCredentialNetworkConfig->com())&&(previousHopCom)&&(originatorCredentialNetworkConfig->com().agreesWith(previousHopCom)))) ) {
+ if ( (originatorCredentialNetworkConfig) && ( (originatorCredentialNetworkConfig->isPublic()) || (peer->address() == originatorAddress) || ((originatorCredentialNetworkConfig->com())&&(previousHopCom)&&(originatorCredentialNetworkConfig->com().agreesWith(previousHopCom))) ) ) {
TRACE("CIRCUIT_TEST %.16llx received from hop %s(%s) and originator %s with valid network ID credential %.16llx (verified from originator and next hop)",testId,source().toString().c_str(),_remoteAddress.toString().c_str(),originatorAddress.toString().c_str(),originatorCredentialNetworkId);
} else {
TRACE("dropped CIRCUIT_TEST from %s(%s): originator %s specified network ID %.16llx as credential, and previous hop %s did not supply a valid COM",source().toString().c_str(),_remoteAddress.toString().c_str(),originatorAddress.toString().c_str(),originatorCredentialNetworkId,peer->address().toString().c_str());
@@ -1078,7 +1079,7 @@ bool IncomingPacket::_doCIRCUIT_TEST(const RuntimeEnvironment *RR,const SharedPt
Packet outp(originatorAddress,RR->identity.address(),Packet::VERB_CIRCUIT_TEST_REPORT);
outp.append((uint64_t)timestamp);
outp.append((uint64_t)testId);
- outp.append((uint64_t)now);
+ outp.append((uint64_t)0); // field reserved for future use
outp.append((uint8_t)ZT_VENDOR_ZEROTIER);
outp.append((uint8_t)ZT_PROTO_VERSION);
outp.append((uint8_t)ZEROTIER_ONE_VERSION_MAJOR);
@@ -1111,7 +1112,7 @@ bool IncomingPacket::_doCIRCUIT_TEST(const RuntimeEnvironment *RR,const SharedPt
if ((originatorCredentialNetworkConfig)&&(!originatorCredentialNetworkConfig->isPublic())&&(originatorCredentialNetworkConfig->com())) {
outp.append((uint8_t)0x01); // COM
originatorCredentialNetworkConfig->com().serialize(outp);
- outp.setAt<uint16_t>(previousHopCredentialPos,(uint16_t)(size() - previousHopCredentialPos));
+ outp.setAt<uint16_t>(previousHopCredentialPos,(uint16_t)(outp.size() - (previousHopCredentialPos + 2)));
}
if (remainingHopsPtr < size())
outp.append(field(remainingHopsPtr,size() - remainingHopsPtr),size() - remainingHopsPtr);
diff --git a/node/IncomingPacket.hpp b/node/IncomingPacket.hpp
index 0df20034..96e46c00 100644
--- a/node/IncomingPacket.hpp
+++ b/node/IncomingPacket.hpp
@@ -24,8 +24,6 @@
#include "Packet.hpp"
#include "InetAddress.hpp"
#include "Utils.hpp"
-#include "SharedPtr.hpp"
-#include "AtomicCounter.hpp"
#include "MulticastGroup.hpp"
#include "Peer.hpp"
@@ -55,9 +53,21 @@ class Network;
*/
class IncomingPacket : public Packet
{
- friend class SharedPtr<IncomingPacket>;
-
public:
+ IncomingPacket() :
+ Packet(),
+ _receiveTime(0),
+ _localAddress(),
+ _remoteAddress()
+ {
+ }
+
+ IncomingPacket(const IncomingPacket &p)
+ {
+ // All fields including InetAddress are memcpy'able
+ memcpy(this,&p,sizeof(IncomingPacket));
+ }
+
/**
* Create a new packet-in-decode
*
@@ -72,9 +82,33 @@ public:
Packet(data,len),
_receiveTime(now),
_localAddress(localAddress),
- _remoteAddress(remoteAddress),
- __refCount()
+ _remoteAddress(remoteAddress)
+ {
+ }
+
+ inline IncomingPacket &operator=(const IncomingPacket &p)
+ {
+ // All fields including InetAddress are memcpy'able
+ memcpy(this,&p,sizeof(IncomingPacket));
+ return *this;
+ }
+
+ /**
+ * Init packet-in-decode in place
+ *
+ * @param data Packet data
+ * @param len Packet length
+ * @param localAddress Local interface address
+ * @param remoteAddress Address from which packet came
+ * @param now Current time
+ * @throws std::out_of_range Range error processing packet
+ */
+ inline void init(const void *data,unsigned int len,const InetAddress &localAddress,const InetAddress &remoteAddress,uint64_t now)
{
+ copyFrom(data,len);
+ _receiveTime = now;
+ _localAddress = localAddress;
+ _remoteAddress = remoteAddress;
}
/**
@@ -154,7 +188,6 @@ private:
uint64_t _receiveTime;
InetAddress _localAddress;
InetAddress _remoteAddress;
- AtomicCounter __refCount;
};
} // namespace ZeroTier
diff --git a/node/InetAddress.cpp b/node/InetAddress.cpp
index d5cd227c..dca772e8 100644
--- a/node/InetAddress.cpp
+++ b/node/InetAddress.cpp
@@ -127,8 +127,10 @@ void InetAddress::set(const void *ipBytes,unsigned int ipLen,unsigned int port)
{
memset(this,0,sizeof(InetAddress));
if (ipLen == 4) {
+ uint32_t ipb[1];
+ memcpy(ipb,ipBytes,4);
ss_family = AF_INET;
- reinterpret_cast<struct sockaddr_in *>(this)->sin_addr.s_addr = *(reinterpret_cast<const uint32_t *>(ipBytes));
+ reinterpret_cast<struct sockaddr_in *>(this)->sin_addr.s_addr = ipb[0];
reinterpret_cast<struct sockaddr_in *>(this)->sin_port = Utils::hton((uint16_t)port);
} else if (ipLen == 16) {
ss_family = AF_INET6;
diff --git a/node/Node.cpp b/node/Node.cpp
index bdeca701..1934ef7d 100644
--- a/node/Node.cpp
+++ b/node/Node.cpp
@@ -493,10 +493,10 @@ int Node::addLocalInterfaceAddress(const struct sockaddr_storage *addr)
{
if (Path::isAddressValidForPath(*(reinterpret_cast<const InetAddress *>(addr)))) {
Mutex::Lock _l(_directPaths_m);
- _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
- std::sort(_directPaths.begin(),_directPaths.end());
- _directPaths.erase(std::unique(_directPaths.begin(),_directPaths.end()),_directPaths.end());
- return 1;
+ if (std::find(_directPaths.begin(),_directPaths.end(),*(reinterpret_cast<const InetAddress *>(addr))) == _directPaths.end()) {
+ _directPaths.push_back(*(reinterpret_cast<const InetAddress *>(addr)));
+ return 1;
+ }
}
return 0;
}
@@ -670,6 +670,9 @@ std::string Node::dataStoreGet(const char *name)
bool Node::shouldUsePathForZeroTierTraffic(const InetAddress &localAddress,const InetAddress &remoteAddress)
{
+ if (!Path::isAddressValidForPath(remoteAddress))
+ return false;
+
{
Mutex::Lock _l(_networks_m);
for(std::vector< std::pair< uint64_t, SharedPtr<Network> > >::const_iterator i=_networks.begin();i!=_networks.end();++i) {
diff --git a/node/Packet.hpp b/node/Packet.hpp
index 2381397b..7d1e5c68 100644
--- a/node/Packet.hpp
+++ b/node/Packet.hpp
@@ -934,7 +934,7 @@ public:
* Circuit test hop report:
* <[8] 64-bit timestamp (from original test)>
* <[8] 64-bit test ID (from original test)>
- * <[8] 64-bit reporter timestamp (reporter's clock, 0 if unspec)>
+ * <[8] 64-bit reserved field (set to 0, currently unused)>
* <[1] 8-bit vendor ID (set to 0, currently unused)>
* <[1] 8-bit reporter protocol version>
* <[1] 8-bit reporter major version>
diff --git a/node/Path.hpp b/node/Path.hpp
index 668728e0..cb7622d3 100644
--- a/node/Path.hpp
+++ b/node/Path.hpp
@@ -127,7 +127,7 @@ public:
inline bool active(uint64_t now) const
throw()
{
- return (((now - _lastReceived) < ZT_PEER_ACTIVITY_TIMEOUT)&&(_probation < ZT_PEER_DEAD_PATH_DETECTION_MAX_PROBATION));
+ return (((now - _lastReceived) < ZT_PATH_ACTIVITY_TIMEOUT)&&(_probation < ZT_PEER_DEAD_PATH_DETECTION_MAX_PROBATION));
}
/**
@@ -243,6 +243,14 @@ public:
case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
case InetAddress::IP_SCOPE_SHARED:
case InetAddress::IP_SCOPE_GLOBAL:
+ if (a.ss_family == AF_INET6) {
+ // TEMPORARY HACK: for now, we are going to blacklist he.net IPv6
+ // tunnels due to very spotty performance and low MTU issues over
+ // these IPv6 tunnel links.
+ const uint8_t *ipd = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&a)->sin6_addr.s6_addr);
+ if ((ipd[0] == 0x20)&&(ipd[1] == 0x01)&&(ipd[2] == 0x04)&&(ipd[3] == 0x70))
+ return false;
+ }
return true;
default:
return false;
diff --git a/node/Peer.cpp b/node/Peer.cpp
index 17f9b2ef..87ca94e1 100644
--- a/node/Peer.cpp
+++ b/node/Peer.cpp
@@ -240,70 +240,83 @@ bool Peer::doPingAndKeepalive(uint64_t now,int inetAddressFamily)
return false;
}
-void Peer::pushDirectPaths(Path *path,uint64_t now,bool force)
+bool Peer::pushDirectPaths(const InetAddress &localAddr,const InetAddress &toAddress,uint64_t now,bool force)
{
#ifdef ZT_ENABLE_CLUSTER
// Cluster mode disables normal PUSH_DIRECT_PATHS in favor of cluster-based peer redirection
if (RR->cluster)
- return;
+ return false;
#endif
- if (((now - _lastDirectPathPushSent) >= ZT_DIRECT_PATH_PUSH_INTERVAL)||(force)) {
- _lastDirectPathPushSent = now;
+ if (!force) {
+ if ((now - _lastDirectPathPushSent) < ZT_DIRECT_PATH_PUSH_INTERVAL)
+ return false;
+ else _lastDirectPathPushSent = now;
+ }
- std::vector<InetAddress> dps(RR->node->directPaths());
- if (dps.empty())
- return;
+ std::vector<InetAddress> dps(RR->node->directPaths());
+ std::vector<InetAddress> sym(RR->sa->getSymmetricNatPredictions());
+ for(unsigned long i=0,added=0;i<sym.size();++i) {
+ InetAddress tmp(sym[(unsigned long)RR->node->prng() % sym.size()]);
+ if (std::find(dps.begin(),dps.end(),tmp) == dps.end()) {
+ dps.push_back(tmp);
+ if (++added >= ZT_PUSH_DIRECT_PATHS_MAX_PER_SCOPE_AND_FAMILY)
+ break;
+ }
+ }
+ if (dps.empty())
+ return false;
#ifdef ZT_TRACE
- {
- std::string ps;
- for(std::vector<InetAddress>::const_iterator p(dps.begin());p!=dps.end();++p) {
- if (ps.length() > 0)
- ps.push_back(',');
- ps.append(p->toString());
- }
- TRACE("pushing %u direct paths to %s: %s",(unsigned int)dps.size(),_id.address().toString().c_str(),ps.c_str());
+ {
+ std::string ps;
+ for(std::vector<InetAddress>::const_iterator p(dps.begin());p!=dps.end();++p) {
+ if (ps.length() > 0)
+ ps.push_back(',');
+ ps.append(p->toString());
}
+ TRACE("pushing %u direct paths to %s: %s",(unsigned int)dps.size(),_id.address().toString().c_str(),ps.c_str());
+ }
#endif
- std::vector<InetAddress>::const_iterator p(dps.begin());
- while (p != dps.end()) {
- Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
- outp.addSize(2); // leave room for count
-
- unsigned int count = 0;
- while ((p != dps.end())&&((outp.size() + 24) < ZT_PROTO_MAX_PACKET_LENGTH)) {
- uint8_t addressType = 4;
- switch(p->ss_family) {
- case AF_INET:
- break;
- case AF_INET6:
- addressType = 6;
- break;
- default: // we currently only push IP addresses
- ++p;
- continue;
- }
+ std::vector<InetAddress>::const_iterator p(dps.begin());
+ while (p != dps.end()) {
+ Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PUSH_DIRECT_PATHS);
+ outp.addSize(2); // leave room for count
+
+ unsigned int count = 0;
+ while ((p != dps.end())&&((outp.size() + 24) < 1200)) {
+ uint8_t addressType = 4;
+ switch(p->ss_family) {
+ case AF_INET:
+ break;
+ case AF_INET6:
+ addressType = 6;
+ break;
+ default: // we currently only push IP addresses
+ ++p;
+ continue;
+ }
- outp.append((uint8_t)0); // no flags
- outp.append((uint16_t)0); // no extensions
- outp.append(addressType);
- outp.append((uint8_t)((addressType == 4) ? 6 : 18));
- outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
- outp.append((uint16_t)p->port());
+ outp.append((uint8_t)0); // no flags
+ outp.append((uint16_t)0); // no extensions
+ outp.append(addressType);
+ outp.append((uint8_t)((addressType == 4) ? 6 : 18));
+ outp.append(p->rawIpData(),((addressType == 4) ? 4 : 16));
+ outp.append((uint16_t)p->port());
- ++count;
- ++p;
- }
+ ++count;
+ ++p;
+ }
- if (count) {
- outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
- outp.armor(_key,true);
- path->send(RR,outp.data(),outp.size(),now);
- }
+ if (count) {
+ outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count);
+ outp.armor(_key,true);
+ RR->node->putPacket(localAddr,toAddress,outp.data(),outp.size(),0);
}
}
+
+ return true;
}
bool Peer::resetWithinScope(InetAddress::IpScope scope,uint64_t now)
@@ -373,7 +386,7 @@ bool Peer::validateAndSetNetworkMembershipCertificate(uint64_t nwid,const Certif
// Check signature, log and return if cert is invalid
if (com.signedBy() != Network::controllerFor(nwid)) {
- TRACE("rejected network membership certificate for %.16llx signed by %s: signer not a controller of this network",(unsigned long long)_id,com.signedBy().toString().c_str());
+ TRACE("rejected network membership certificate for %.16llx signed by %s: signer not a controller of this network",(unsigned long long)nwid,com.signedBy().toString().c_str());
return false; // invalid signer
}
@@ -382,7 +395,7 @@ bool Peer::validateAndSetNetworkMembershipCertificate(uint64_t nwid,const Certif
// We are the controller: RR->identity.address() == controller() == cert.signedBy()
// So, verify that we signed th cert ourself
if (!com.verify(RR->identity)) {
- TRACE("rejected network membership certificate for %.16llx self signed by %s: signature check failed",(unsigned long long)_id,com.signedBy().toString().c_str());
+ TRACE("rejected network membership certificate for %.16llx self signed by %s: signature check failed",(unsigned long long)nwid,com.signedBy().toString().c_str());
return false; // invalid signature
}
@@ -398,7 +411,7 @@ bool Peer::validateAndSetNetworkMembershipCertificate(uint64_t nwid,const Certif
}
if (!com.verify(signer->identity())) {
- TRACE("rejected network membership certificate for %.16llx signed by %s: signature check failed",(unsigned long long)_id,com.signedBy().toString().c_str());
+ TRACE("rejected network membership certificate for %.16llx signed by %s: signature check failed",(unsigned long long)nwid,com.signedBy().toString().c_str());
return false; // invalid signature
}
}
@@ -419,7 +432,7 @@ bool Peer::needsOurNetworkMembershipCertificate(uint64_t nwid,uint64_t now,bool
const uint64_t tmp = lastPushed;
if (updateLastPushedTime)
lastPushed = now;
- return ((now - tmp) >= (ZT_NETWORK_AUTOCONF_DELAY / 2));
+ return ((now - tmp) >= (ZT_NETWORK_AUTOCONF_DELAY / 3));
}
void Peer::clean(uint64_t now)
diff --git a/node/Peer.hpp b/node/Peer.hpp
index 5796baf9..94c58ae8 100644
--- a/node/Peer.hpp
+++ b/node/Peer.hpp
@@ -170,11 +170,13 @@ public:
/**
* Push direct paths back to self if we haven't done so in the configured timeout
*
- * @param path Remote path to use to send the push
+ * @param localAddr Local address
+ * @param toAddress Remote address to send push to (usually from path)
* @param now Current time
* @param force If true, push regardless of rate limit
+ * @return True if something was actually sent
*/
- void pushDirectPaths(Path *path,uint64_t now,bool force);
+ bool pushDirectPaths(const InetAddress &localAddr,const InetAddress &toAddress,uint64_t now,bool force);
/**
* @return All known direct paths to this peer (active or inactive)
diff --git a/node/SelfAwareness.cpp b/node/SelfAwareness.cpp
index db069046..8bed0c51 100644
--- a/node/SelfAwareness.cpp
+++ b/node/SelfAwareness.cpp
@@ -20,6 +20,9 @@
#include <stdlib.h>
#include <string.h>
+#include <set>
+#include <vector>
+
#include "Constants.hpp"
#include "SelfAwareness.hpp"
#include "RuntimeEnvironment.hpp"
@@ -64,34 +67,18 @@ SelfAwareness::~SelfAwareness()
{
}
-void SelfAwareness::iam(const Address &reporter,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now)
+void SelfAwareness::iam(const Address &reporter,const InetAddress &receivedOnLocalAddress,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now)
{
const InetAddress::IpScope scope = myPhysicalAddress.ipScope();
- // This would be weird, e.g. a public IP talking to 10.0.0.1, so just ignore it.
- // If your network is this weird it's probably not reliable information.
- if (scope != reporterPhysicalAddress.ipScope())
+ if ((scope != reporterPhysicalAddress.ipScope())||(scope == InetAddress::IP_SCOPE_NONE)||(scope == InetAddress::IP_SCOPE_LOOPBACK)||(scope == InetAddress::IP_SCOPE_MULTICAST))
return;
- // Some scopes we ignore, and global scope IPs are only used for this
- // mechanism if they come from someone we trust (e.g. a root).
- switch(scope) {
- case InetAddress::IP_SCOPE_NONE:
- case InetAddress::IP_SCOPE_LOOPBACK:
- case InetAddress::IP_SCOPE_MULTICAST:
- return;
- case InetAddress::IP_SCOPE_GLOBAL:
- if (!trusted)
- return;
- break;
- default:
- break;
- }
-
Mutex::Lock _l(_phy_m);
- PhySurfaceEntry &entry = _phy[PhySurfaceKey(reporter,reporterPhysicalAddress,scope)];
+ PhySurfaceEntry &entry = _phy[PhySurfaceKey(reporter,receivedOnLocalAddress,reporterPhysicalAddress,scope)];
- if ( ((now - entry.ts) < ZT_SELFAWARENESS_ENTRY_TIMEOUT) && (!entry.mySurface.ipsEqual(myPhysicalAddress)) ) {
+ if ( (trusted) && ((now - entry.ts) < ZT_SELFAWARENESS_ENTRY_TIMEOUT) && (!entry.mySurface.ipsEqual(myPhysicalAddress)) ) {
+ // Changes to external surface reported by trusted peers causes path reset in this scope
entry.mySurface = myPhysicalAddress;
entry.ts = now;
TRACE("physical address %s for scope %u as seen from %s(%s) differs from %s, resetting paths in scope",myPhysicalAddress.toString().c_str(),(unsigned int)scope,reporter.toString().c_str(),reporterPhysicalAddress.toString().c_str(),entry.mySurface.toString().c_str());
@@ -123,6 +110,7 @@ void SelfAwareness::iam(const Address &reporter,const InetAddress &reporterPhysi
}
}
} else {
+ // Otherwise just update DB to use to determine external surface info
entry.mySurface = myPhysicalAddress;
entry.ts = now;
}
@@ -140,4 +128,60 @@ void SelfAwareness::clean(uint64_t now)
}
}
+std::vector<InetAddress> SelfAwareness::getSymmetricNatPredictions()
+{
+ /* This is based on ideas and strategies found here:
+ * https://tools.ietf.org/html/draft-takeda-symmetric-nat-traversal-00
+ *
+ * In short: a great many symmetric NATs allocate ports sequentially.
+ * This is common on enterprise and carrier grade NATs as well as consumer
+ * devices. This code generates a list of "you might try this" addresses by
+ * extrapolating likely port assignments from currently known external
+ * global IPv4 surfaces. These can then be included in a PUSH_DIRECT_PATHS
+ * message to another peer, causing it to possibly try these addresses and
+ * bust our local symmetric NAT. It works often enough to be worth the
+ * extra bit of code and does no harm in cases where it fails. */
+
+ // Gather unique surfaces indexed by local received-on address and flag
+ // us as behind a symmetric NAT if there is more than one.
+ std::map< InetAddress,std::set<InetAddress> > surfaces;
+ bool symmetric = false;
+ {
+ Mutex::Lock _l(_phy_m);
+ Hashtable< PhySurfaceKey,PhySurfaceEntry >::Iterator i(_phy);
+ PhySurfaceKey *k = (PhySurfaceKey *)0;
+ PhySurfaceEntry *e = (PhySurfaceEntry *)0;
+ while (i.next(k,e)) {
+ if ((e->mySurface.ss_family == AF_INET)&&(e->mySurface.ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
+ std::set<InetAddress> &s = surfaces[k->receivedOnLocalAddress];
+ s.insert(e->mySurface);
+ symmetric = symmetric||(s.size() > 1);
+ }
+ }
+ }
+
+ // If we appear to be symmetrically NATed, generate and return extrapolations
+ // of those surfaces. Since PUSH_DIRECT_PATHS is sent multiple times, we
+ // probabilistically generate extrapolations of anywhere from +1 to +5 to
+ // increase the odds that it will work "eventually".
+ if (symmetric) {
+ std::vector<InetAddress> r;
+ for(std::map< InetAddress,std::set<InetAddress> >::iterator si(surfaces.begin());si!=surfaces.end();++si) {
+ for(std::set<InetAddress>::iterator i(si->second.begin());i!=si->second.end();++i) {
+ InetAddress ipp(*i);
+ unsigned int p = ipp.port() + 1 + ((unsigned int)RR->node->prng() & 3);
+ if (p >= 65535)
+ p -= 64510; // NATs seldom use ports <=1024 so wrap to 1025
+ ipp.setPort(p);
+ if ((si->second.count(ipp) == 0)&&(std::find(r.begin(),r.end(),ipp) == r.end())) {
+ r.push_back(ipp);
+ }
+ }
+ }
+ return r;
+ }
+
+ return std::vector<InetAddress>();
+}
+
} // namespace ZeroTier
diff --git a/node/SelfAwareness.hpp b/node/SelfAwareness.hpp
index 2534d986..06c264a9 100644
--- a/node/SelfAwareness.hpp
+++ b/node/SelfAwareness.hpp
@@ -42,12 +42,13 @@ public:
* Called when a trusted remote peer informs us of our external network address
*
* @param reporter ZeroTier address of reporting peer
+ * @param receivedOnLocalAddress Local address on which report was received
* @param reporterPhysicalAddress Physical address that reporting peer seems to have
* @param myPhysicalAddress Physical address that peer says we have
* @param trusted True if this peer is trusted as an authority to inform us of external address changes
* @param now Current time
*/
- void iam(const Address &reporter,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now);
+ void iam(const Address &reporter,const InetAddress &receivedOnLocalAddress,const InetAddress &reporterPhysicalAddress,const InetAddress &myPhysicalAddress,bool trusted,uint64_t now);
/**
* Clean up database periodically
@@ -56,18 +57,26 @@ public:
*/
void clean(uint64_t now);
+ /**
+ * If we appear to be behind a symmetric NAT, get predictions for possible external endpoints
+ *
+ * @return Symmetric NAT predictions or empty vector if none
+ */
+ std::vector<InetAddress> getSymmetricNatPredictions();
+
private:
struct PhySurfaceKey
{
Address reporter;
+ InetAddress receivedOnLocalAddress;
InetAddress reporterPhysicalAddress;
InetAddress::IpScope scope;
PhySurfaceKey() : reporter(),scope(InetAddress::IP_SCOPE_NONE) {}
- PhySurfaceKey(const Address &r,const InetAddress &ra,InetAddress::IpScope s) : reporter(r),reporterPhysicalAddress(ra),scope(s) {}
+ PhySurfaceKey(const Address &r,const InetAddress &rol,const InetAddress &ra,InetAddress::IpScope s) : reporter(r),receivedOnLocalAddress(rol),reporterPhysicalAddress(ra),scope(s) {}
inline unsigned long hashCode() const throw() { return ((unsigned long)reporter.toInt() + (unsigned long)scope); }
- inline bool operator==(const PhySurfaceKey &k) const throw() { return ((reporter == k.reporter)&&(reporterPhysicalAddress == k.reporterPhysicalAddress)&&(scope == k.scope)); }
+ inline bool operator==(const PhySurfaceKey &k) const throw() { return ((reporter == k.reporter)&&(receivedOnLocalAddress == k.receivedOnLocalAddress)&&(reporterPhysicalAddress == k.reporterPhysicalAddress)&&(scope == k.scope)); }
};
struct PhySurfaceEntry
{
diff --git a/node/Switch.cpp b/node/Switch.cpp
index 4c91a855..968d1a4a 100644
--- a/node/Switch.cpp
+++ b/node/Switch.cpp
@@ -60,7 +60,6 @@ Switch::Switch(const RuntimeEnvironment *renv) :
RR(renv),
_lastBeaconResponse(0),
_outstandingWhoisRequests(32),
- _defragQueue(32),
_lastUniteAttempt(8) // only really used on root servers and upstreams, and it'll grow there just fine
{
}
@@ -72,11 +71,14 @@ Switch::~Switch()
void Switch::onRemotePacket(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len)
{
try {
+ const uint64_t now = RR->node->now();
+
if (len == 13) {
/* LEGACY: before VERB_PUSH_DIRECT_PATHS, peers used broadcast
* announcements on the LAN to solve the 'same network problem.' We
* no longer send these, but we'll listen for them for a while to
* locate peers with versions <1.0.4. */
+
Address beaconAddr(reinterpret_cast<const char *>(data) + 8,5);
if (beaconAddr == RR->identity.address())
return;
@@ -84,7 +86,6 @@ void Switch::onRemotePacket(const InetAddress &localAddr,const InetAddress &from
return;
SharedPtr<Peer> peer(RR->topology->getPeer(beaconAddr));
if (peer) { // we'll only respond to beacons from known peers
- const uint64_t now = RR->node->now();
if ((now - _lastBeaconResponse) >= 2500) { // limit rate of responses
_lastBeaconResponse = now;
Packet outp(peer->address(),RR->identity.address(),Packet::VERB_NOP);
@@ -92,11 +93,209 @@ void Switch::onRemotePacket(const InetAddress &localAddr,const InetAddress &from
RR->node->putPacket(localAddr,fromAddr,outp.data(),outp.size());
}
}
- } else if (len > ZT_PROTO_MIN_FRAGMENT_LENGTH) {
- if (((const unsigned char *)data)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR) {
- _handleRemotePacketFragment(localAddr,fromAddr,data,len);
- } else if (len >= ZT_PROTO_MIN_PACKET_LENGTH) {
- _handleRemotePacketHead(localAddr,fromAddr,data,len);
+
+ } else if (len > ZT_PROTO_MIN_FRAGMENT_LENGTH) { // min length check is important!
+ if (reinterpret_cast<const uint8_t *>(data)[ZT_PACKET_FRAGMENT_IDX_FRAGMENT_INDICATOR] == ZT_PACKET_FRAGMENT_INDICATOR) {
+ // Handle fragment ----------------------------------------------------
+
+ Packet::Fragment fragment(data,len);
+ const Address destination(fragment.destination());
+
+ if (destination != RR->identity.address()) {
+ // Fragment is not for us, so try to relay it
+ if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
+ fragment.incrementHops();
+
+ // Note: we don't bother initiating NAT-t for fragments, since heads will set that off.
+ // It wouldn't hurt anything, just redundant and unnecessary.
+ SharedPtr<Peer> relayTo = RR->topology->getPeer(destination);
+ if ((!relayTo)||(!relayTo->send(fragment.data(),fragment.size(),now))) {
+#ifdef ZT_ENABLE_CLUSTER
+ if (RR->cluster) {
+ RR->cluster->sendViaCluster(Address(),destination,fragment.data(),fragment.size(),false);
+ return;
+ }
+#endif
+
+ // Don't know peer or no direct path -- so relay via root server
+ relayTo = RR->topology->getBestRoot();
+ if (relayTo)
+ relayTo->send(fragment.data(),fragment.size(),now);
+ }
+ } else {
+ TRACE("dropped relay [fragment](%s) -> %s, max hops exceeded",fromAddr.toString().c_str(),destination.toString().c_str());
+ }
+ } else {
+ // Fragment looks like ours
+ const uint64_t fragmentPacketId = fragment.packetId();
+ const unsigned int fragmentNumber = fragment.fragmentNumber();
+ const unsigned int totalFragments = fragment.totalFragments();
+
+ if ((totalFragments <= ZT_MAX_PACKET_FRAGMENTS)&&(fragmentNumber < ZT_MAX_PACKET_FRAGMENTS)&&(fragmentNumber > 0)&&(totalFragments > 1)) {
+ // Fragment appears basically sane. Its fragment number must be
+ // 1 or more, since a Packet with fragmented bit set is fragment 0.
+ // Total fragments must be more than 1, otherwise why are we
+ // seeing a Packet::Fragment?
+
+ Mutex::Lock _l(_rxQueue_m);
+ RXQueueEntry *const rq = _findRXQueueEntry(now,fragmentPacketId);
+
+ if ((!rq->timestamp)||(rq->packetId != fragmentPacketId)) {
+ // No packet found, so we received a fragment without its head.
+ //TRACE("fragment (%u/%u) of %.16llx from %s",fragmentNumber + 1,totalFragments,fragmentPacketId,fromAddr.toString().c_str());
+
+ rq->timestamp = now;
+ rq->packetId = fragmentPacketId;
+ rq->frags[fragmentNumber - 1] = fragment;
+ rq->totalFragments = totalFragments; // total fragment count is known
+ rq->haveFragments = 1 << fragmentNumber; // we have only this fragment
+ rq->complete = false;
+ } else if (!(rq->haveFragments & (1 << fragmentNumber))) {
+ // We have other fragments and maybe the head, so add this one and check
+ //TRACE("fragment (%u/%u) of %.16llx from %s",fragmentNumber + 1,totalFragments,fragmentPacketId,fromAddr.toString().c_str());
+
+ rq->frags[fragmentNumber - 1] = fragment;
+ rq->totalFragments = totalFragments;
+
+ if (Utils::countBits(rq->haveFragments |= (1 << fragmentNumber)) == totalFragments) {
+ // We have all fragments -- assemble and process full Packet
+ //TRACE("packet %.16llx is complete, assembling and processing...",fragmentPacketId);
+
+ for(unsigned int f=1;f<totalFragments;++f)
+ rq->frag0.append(rq->frags[f - 1].payload(),rq->frags[f - 1].payloadLength());
+
+ if (rq->frag0.tryDecode(RR,false)) {
+ rq->timestamp = 0; // packet decoded, free entry
+ } else {
+ rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
+ }
+ }
+ } // else this is a duplicate fragment, ignore
+ }
+ }
+
+ // --------------------------------------------------------------------
+ } else if (len >= ZT_PROTO_MIN_PACKET_LENGTH) { // min length check is important!
+ // Handle packet head -------------------------------------------------
+
+ // See packet format in Packet.hpp to understand this
+ const uint64_t packetId = (
+ (((uint64_t)reinterpret_cast<const uint8_t *>(data)[0]) << 56) |
+ (((uint64_t)reinterpret_cast<const uint8_t *>(data)[1]) << 48) |
+ (((uint64_t)reinterpret_cast<const uint8_t *>(data)[2]) << 40) |
+ (((uint64_t)reinterpret_cast<const uint8_t *>(data)[3]) << 32) |
+ (((uint64_t)reinterpret_cast<const uint8_t *>(data)[4]) << 24) |
+ (((uint64_t)reinterpret_cast<const uint8_t *>(data)[5]) << 16) |
+ (((uint64_t)reinterpret_cast<const uint8_t *>(data)[6]) << 8) |
+ ((uint64_t)reinterpret_cast<const uint8_t *>(data)[7])
+ );
+ const Address destination(reinterpret_cast<const uint8_t *>(data) + 8,ZT_ADDRESS_LENGTH);
+ const Address source(reinterpret_cast<const uint8_t *>(data) + 13,ZT_ADDRESS_LENGTH);
+
+ // Catch this and toss it -- it would never work, but it could happen if we somehow
+ // mistakenly guessed an address we're bound to as a destination for another peer.
+ if (source == RR->identity.address())
+ return;
+
+ //TRACE("<< %.16llx %s -> %s (size: %u)",(unsigned long long)packet->packetId(),source.toString().c_str(),destination.toString().c_str(),packet->size());
+
+ if (destination != RR->identity.address()) {
+ Packet packet(data,len);
+
+ // Packet is not for us, so try to relay it
+ if (packet.hops() < ZT_RELAY_MAX_HOPS) {
+ packet.incrementHops();
+
+ SharedPtr<Peer> relayTo = RR->topology->getPeer(destination);
+ if ((relayTo)&&((relayTo->send(packet.data(),packet.size(),now)))) {
+ Mutex::Lock _l(_lastUniteAttempt_m);
+ uint64_t &luts = _lastUniteAttempt[_LastUniteKey(source,destination)];
+ if ((now - luts) >= ZT_MIN_UNITE_INTERVAL) {
+ luts = now;
+ unite(source,destination);
+ }
+ } else {
+#ifdef ZT_ENABLE_CLUSTER
+ if (RR->cluster) {
+ bool shouldUnite;
+ {
+ Mutex::Lock _l(_lastUniteAttempt_m);
+ uint64_t &luts = _lastUniteAttempt[_LastUniteKey(source,destination)];
+ shouldUnite = ((now - luts) >= ZT_MIN_UNITE_INTERVAL);
+ if (shouldUnite)
+ luts = now;
+ }
+ RR->cluster->sendViaCluster(source,destination,packet.data(),packet.size(),shouldUnite);
+ return;
+ }
+#endif
+
+ relayTo = RR->topology->getBestRoot(&source,1,true);
+ if (relayTo)
+ relayTo->send(packet.data(),packet.size(),now);
+ }
+ } else {
+ TRACE("dropped relay %s(%s) -> %s, max hops exceeded",packet.source().toString().c_str(),fromAddr.toString().c_str(),destination.toString().c_str());
+ }
+ } else if ((reinterpret_cast<const uint8_t *>(data)[ZT_PACKET_IDX_FLAGS] & ZT_PROTO_FLAG_FRAGMENTED) != 0) {
+ // Packet is the head of a fragmented packet series
+
+ Mutex::Lock _l(_rxQueue_m);
+ RXQueueEntry *const rq = _findRXQueueEntry(now,packetId);
+
+ if ((!rq->timestamp)||(rq->packetId != packetId)) {
+ // If we have no other fragments yet, create an entry and save the head
+ //TRACE("fragment (0/?) of %.16llx from %s",pid,fromAddr.toString().c_str());
+
+ rq->timestamp = now;
+ rq->packetId = packetId;
+ rq->frag0.init(data,len,localAddr,fromAddr,now);
+ rq->totalFragments = 0;
+ rq->haveFragments = 1;
+ rq->complete = false;
+ } else if (!(rq->haveFragments & 1)) {
+ // If we have other fragments but no head, see if we are complete with the head
+
+ if ((rq->totalFragments > 1)&&(Utils::countBits(rq->haveFragments |= 1) == rq->totalFragments)) {
+ // We have all fragments -- assemble and process full Packet
+ //TRACE("packet %.16llx is complete, assembling and processing...",pid);
+
+ rq->frag0.init(data,len,localAddr,fromAddr,now);
+ for(unsigned int f=1;f<rq->totalFragments;++f)
+ rq->frag0.append(rq->frags[f - 1].payload(),rq->frags[f - 1].payloadLength());
+
+ if (rq->frag0.tryDecode(RR,false)) {
+ rq->timestamp = 0; // packet decoded, free entry
+ } else {
+ rq->complete = true; // set complete flag but leave entry since it probably needs WHOIS or something
+ }
+ } else {
+ // Still waiting on more fragments, but keep the head
+ rq->frag0.init(data,len,localAddr,fromAddr,now);
+ }
+ } // else this is a duplicate head, ignore
+ } else {
+ // Packet is unfragmented, so just process it
+ IncomingPacket packet(data,len,localAddr,fromAddr,now);
+ if (!packet.tryDecode(RR,false)) {
+ Mutex::Lock _l(_rxQueue_m);
+ RXQueueEntry *rq = &(_rxQueue[ZT_RX_QUEUE_SIZE - 1]);
+ unsigned long i = ZT_RX_QUEUE_SIZE - 1;
+ while ((i)&&(rq->timestamp)) {
+ RXQueueEntry *tmp = &(_rxQueue[--i]);
+ if (tmp->timestamp < rq->timestamp)
+ rq = tmp;
+ }
+ rq->timestamp = now;
+ rq->packetId = packetId;
+ rq->frag0 = packet;
+ rq->totalFragments = 1;
+ rq->haveFragments = 1;
+ rq->complete = true;
+ }
+ }
+
+ // --------------------------------------------------------------------
}
}
} catch (std::exception &ex) {
@@ -451,10 +650,13 @@ void Switch::doAnythingWaitingForPeer(const SharedPtr<Peer> &peer)
{ // finish processing any packets waiting on peer's public key / identity
Mutex::Lock _l(_rxQueue_m);
- for(std::list< SharedPtr<IncomingPacket> >::iterator rxi(_rxQueue.begin());rxi!=_rxQueue.end();) {
- if ((*rxi)->tryDecode(RR,false))
- _rxQueue.erase(rxi++);
- else ++rxi;
+ unsigned long i = ZT_RX_QUEUE_SIZE;
+ while (i) {
+ RXQueueEntry *rq = &(_rxQueue[--i]);
+ if ((rq->timestamp)&&(rq->complete)) {
+ if (rq->frag0.tryDecode(RR,false))
+ rq->timestamp = 0;
+ }
}
}
@@ -478,31 +680,31 @@ unsigned long Switch::doTimerTasks(uint64_t now)
Mutex::Lock _l(_contactQueue_m);
for(std::list<ContactQueueEntry>::iterator qi(_contactQueue.begin());qi!=_contactQueue.end();) {
if (now >= qi->fireAtTime) {
- if (qi->peer->hasActiveDirectPath(now)) {
- // Cancel if connection has succeeded
+ if (!qi->peer->pushDirectPaths(qi->localAddr,qi->inaddr,now,true))
+ qi->peer->sendHELLO(qi->localAddr,qi->inaddr,now);
+ _contactQueue.erase(qi++);
+ continue;
+ /* Old symmetric NAT buster code, obsoleted by port prediction alg in SelfAwareness but left around for now in case we revert
+ if (qi->strategyIteration == 0) {
+ // First strategy: send packet directly to destination
+ qi->peer->sendHELLO(qi->localAddr,qi->inaddr,now);
+ } else if (qi->strategyIteration <= 3) {
+ // Strategies 1-3: try escalating ports for symmetric NATs that remap sequentially
+ InetAddress tmpaddr(qi->inaddr);
+ int p = (int)qi->inaddr.port() + qi->strategyIteration;
+ if (p > 65535)
+ p -= 64511;
+ tmpaddr.setPort((unsigned int)p);
+ qi->peer->sendHELLO(qi->localAddr,tmpaddr,now);
+ } else {
+ // All strategies tried, expire entry
_contactQueue.erase(qi++);
continue;
- } else {
- if (qi->strategyIteration == 0) {
- // First strategy: send packet directly to destination
- qi->peer->sendHELLO(qi->localAddr,qi->inaddr,now);
- } else if (qi->strategyIteration <= 3) {
- // Strategies 1-3: try escalating ports for symmetric NATs that remap sequentially
- InetAddress tmpaddr(qi->inaddr);
- int p = (int)qi->inaddr.port() + qi->strategyIteration;
- if (p < 0xffff) {
- tmpaddr.setPort((unsigned int)p);
- qi->peer->sendHELLO(qi->localAddr,tmpaddr,now);
- } else qi->strategyIteration = 5;
- } else {
- // All strategies tried, expire entry
- _contactQueue.erase(qi++);
- continue;
- }
- ++qi->strategyIteration;
- qi->fireAtTime = now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY;
- nextDelay = std::min(nextDelay,(unsigned long)ZT_NAT_T_TACTICAL_ESCALATION_DELAY);
}
+ ++qi->strategyIteration;
+ qi->fireAtTime = now + ZT_NAT_T_TACTICAL_ESCALATION_DELAY;
+ nextDelay = std::min(nextDelay,(unsigned long)ZT_NAT_T_TACTICAL_ESCALATION_DELAY);
+ */
} else {
nextDelay = std::min(nextDelay,(unsigned long)(qi->fireAtTime - now));
}
@@ -546,29 +748,6 @@ unsigned long Switch::doTimerTasks(uint64_t now)
}
}
- { // Time out RX queue packets that never got WHOIS lookups or other info.
- Mutex::Lock _l(_rxQueue_m);
- for(std::list< SharedPtr<IncomingPacket> >::iterator i(_rxQueue.begin());i!=_rxQueue.end();) {
- if ((now - (*i)->receiveTime()) > ZT_RECEIVE_QUEUE_TIMEOUT) {
- TRACE("RX %s -> %s timed out",(*i)->source().toString().c_str(),(*i)->destination().toString().c_str());
- _rxQueue.erase(i++);
- } else ++i;
- }
- }
-
- { // Time out packets that didn't get all their fragments.
- Mutex::Lock _l(_defragQueue_m);
- Hashtable< uint64_t,DefragQueueEntry >::Iterator i(_defragQueue);
- uint64_t *packetId = (uint64_t *)0;
- DefragQueueEntry *qe = (DefragQueueEntry *)0;
- while (i.next(packetId,qe)) {
- if ((now - qe->creationTime) > ZT_FRAGMENTED_PACKET_RECEIVE_TIMEOUT) {
- TRACE("incomplete fragmented packet %.16llx timed out, fragments discarded",*packetId);
- _defragQueue.erase(*packetId);
- }
- }
- }
-
{ // Remove really old last unite attempt entries to keep table size controlled
Mutex::Lock _l(_lastUniteAttempt_m);
Hashtable< _LastUniteKey,uint64_t >::Iterator i(_lastUniteAttempt);
@@ -583,180 +762,6 @@ unsigned long Switch::doTimerTasks(uint64_t now)
return nextDelay;
}
-void Switch::_handleRemotePacketFragment(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len)
-{
- Packet::Fragment fragment(data,len);
- Address destination(fragment.destination());
-
- if (destination != RR->identity.address()) {
- // Fragment is not for us, so try to relay it
- if (fragment.hops() < ZT_RELAY_MAX_HOPS) {
- fragment.incrementHops();
-
- // Note: we don't bother initiating NAT-t for fragments, since heads will set that off.
- // It wouldn't hurt anything, just redundant and unnecessary.
- SharedPtr<Peer> relayTo = RR->topology->getPeer(destination);
- if ((!relayTo)||(!relayTo->send(fragment.data(),fragment.size(),RR->node->now()))) {
-#ifdef ZT_ENABLE_CLUSTER
- if (RR->cluster) {
- RR->cluster->sendViaCluster(Address(),destination,fragment.data(),fragment.size(),false);
- return;
- }
-#endif
-
- // Don't know peer or no direct path -- so relay via root server
- relayTo = RR->topology->getBestRoot();
- if (relayTo)
- relayTo->send(fragment.data(),fragment.size(),RR->node->now());
- }
- } else {
- TRACE("dropped relay [fragment](%s) -> %s, max hops exceeded",fromAddr.toString().c_str(),destination.toString().c_str());
- }
- } else {
- // Fragment looks like ours
- uint64_t pid = fragment.packetId();
- unsigned int fno = fragment.fragmentNumber();
- unsigned int tf = fragment.totalFragments();
-
- if ((tf <= ZT_MAX_PACKET_FRAGMENTS)&&(fno < ZT_MAX_PACKET_FRAGMENTS)&&(fno > 0)&&(tf > 1)) {
- // Fragment appears basically sane. Its fragment number must be
- // 1 or more, since a Packet with fragmented bit set is fragment 0.
- // Total fragments must be more than 1, otherwise why are we
- // seeing a Packet::Fragment?
-
- Mutex::Lock _l(_defragQueue_m);
- DefragQueueEntry &dq = _defragQueue[pid];
-
- if (!dq.creationTime) {
- // We received a Packet::Fragment without its head, so queue it and wait
-
- dq.creationTime = RR->node->now();
- dq.frags[fno - 1] = fragment;
- dq.totalFragments = tf; // total fragment count is known
- dq.haveFragments = 1 << fno; // we have only this fragment
- //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
- } else if (!(dq.haveFragments & (1 << fno))) {
- // We have other fragments and maybe the head, so add this one and check
-
- dq.frags[fno - 1] = fragment;
- dq.totalFragments = tf;
- //TRACE("fragment (%u/%u) of %.16llx from %s",fno + 1,tf,pid,fromAddr.toString().c_str());
-
- if (Utils::countBits(dq.haveFragments |= (1 << fno)) == tf) {
- // We have all fragments -- assemble and process full Packet
- //TRACE("packet %.16llx is complete, assembling and processing...",pid);
-
- SharedPtr<IncomingPacket> packet(dq.frag0);
- for(unsigned int f=1;f<tf;++f)
- packet->append(dq.frags[f - 1].payload(),dq.frags[f - 1].payloadLength());
- _defragQueue.erase(pid); // dq no longer valid after this
-
- if (!packet->tryDecode(RR,false)) {
- Mutex::Lock _l(_rxQueue_m);
- _rxQueue.push_back(packet);
- }
- }
- } // else this is a duplicate fragment, ignore
- }
- }
-}
-
-void Switch::_handleRemotePacketHead(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len)
-{
- const uint64_t now = RR->node->now();
- SharedPtr<IncomingPacket> packet(new IncomingPacket(data,len,localAddr,fromAddr,now));
-
- Address source(packet->source());
- Address destination(packet->destination());
-
- // Catch this and toss it -- it would never work, but it could happen if we somehow
- // mistakenly guessed an address we're bound to as a destination for another peer.
- if (source == RR->identity.address())
- return;
-
- //TRACE("<< %.16llx %s -> %s (size: %u)",(unsigned long long)packet->packetId(),source.toString().c_str(),destination.toString().c_str(),packet->size());
-
- if (destination != RR->identity.address()) {
- // Packet is not for us, so try to relay it
- if (packet->hops() < ZT_RELAY_MAX_HOPS) {
- packet->incrementHops();
-
- SharedPtr<Peer> relayTo = RR->topology->getPeer(destination);
- if ((relayTo)&&((relayTo->send(packet->data(),packet->size(),now)))) {
- Mutex::Lock _l(_lastUniteAttempt_m);
- uint64_t &luts = _lastUniteAttempt[_LastUniteKey(source,destination)];
- if ((now - luts) >= ZT_MIN_UNITE_INTERVAL) {
- luts = now;
- unite(source,destination);
- }
- } else {
-#ifdef ZT_ENABLE_CLUSTER
- if (RR->cluster) {
- bool shouldUnite;
- {
- Mutex::Lock _l(_lastUniteAttempt_m);
- uint64_t &luts = _lastUniteAttempt[_LastUniteKey(source,destination)];
- shouldUnite = ((now - luts) >= ZT_MIN_UNITE_INTERVAL);
- if (shouldUnite)
- luts = now;
- }
- RR->cluster->sendViaCluster(source,destination,packet->data(),packet->size(),shouldUnite);
- return;
- }
-#endif
-
- relayTo = RR->topology->getBestRoot(&source,1,true);
- if (relayTo)
- relayTo->send(packet->data(),packet->size(),now);
- }
- } else {
- TRACE("dropped relay %s(%s) -> %s, max hops exceeded",packet->source().toString().c_str(),fromAddr.toString().c_str(),destination.toString().c_str());
- }
- } else if (packet->fragmented()) {
- // Packet is the head of a fragmented packet series
-
- uint64_t pid = packet->packetId();
- Mutex::Lock _l(_defragQueue_m);
- DefragQueueEntry &dq = _defragQueue[pid];
-
- if (!dq.creationTime) {
- // If we have no other fragments yet, create an entry and save the head
-
- dq.creationTime = now;
- dq.frag0 = packet;
- dq.totalFragments = 0; // 0 == unknown, waiting for Packet::Fragment
- dq.haveFragments = 1; // head is first bit (left to right)
- //TRACE("fragment (0/?) of %.16llx from %s",pid,fromAddr.toString().c_str());
- } else if (!(dq.haveFragments & 1)) {
- // If we have other fragments but no head, see if we are complete with the head
-
- if ((dq.totalFragments)&&(Utils::countBits(dq.haveFragments |= 1) == dq.totalFragments)) {
- // We have all fragments -- assemble and process full Packet
-
- //TRACE("packet %.16llx is complete, assembling and processing...",pid);
- // packet already contains head, so append fragments
- for(unsigned int f=1;f<dq.totalFragments;++f)
- packet->append(dq.frags[f - 1].payload(),dq.frags[f - 1].payloadLength());
- _defragQueue.erase(pid); // dq no longer valid after this
-
- if (!packet->tryDecode(RR,false)) {
- Mutex::Lock _l(_rxQueue_m);
- _rxQueue.push_back(packet);
- }
- } else {
- // Still waiting on more fragments, so queue the head
- dq.frag0 = packet;
- }
- } // else this is a duplicate head, ignore
- } else {
- // Packet is unfragmented, so just process it
- if (!packet->tryDecode(RR,false)) {
- Mutex::Lock _l(_rxQueue_m);
- _rxQueue.push_back(packet);
- }
- }
-}
-
Address Switch::_sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted)
{
SharedPtr<Peer> root(RR->topology->getBestRoot(peersAlreadyConsulted,numPeersAlreadyConsulted,false));
@@ -813,12 +818,13 @@ bool Switch::_trySend(const Packet &packet,bool encrypt,uint64_t nwid)
relay = RR->topology->getBestRoot();
if (!(relay)||(!(viaPath = relay->getBestPath(now))))
- return false; // no paths, no root servers?
+ return false; // no paths, no root servers?, no relays? :P~~~
}
if ((network)&&(relay)&&(network->isAllowed(peer))) {
// Push hints for direct connectivity to this peer if we are relaying
- peer->pushDirectPaths(viaPath,now,false);
+ peer->pushDirectPaths(viaPath->localAddress(),viaPath->address(),now,false);
+ viaPath->sent(now);
}
Packet tmp(packet);
diff --git a/node/Switch.hpp b/node/Switch.hpp
index f77bf86c..ce4f00a1 100644
--- a/node/Switch.hpp
+++ b/node/Switch.hpp
@@ -150,8 +150,6 @@ public:
unsigned long doTimerTasks(uint64_t now);
private:
- void _handleRemotePacketFragment(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
- void _handleRemotePacketHead(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
Address _sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted);
bool _trySend(const Packet &packet,bool encrypt,uint64_t nwid);
@@ -169,23 +167,40 @@ private:
Hashtable< Address,WhoisRequest > _outstandingWhoisRequests;
Mutex _outstandingWhoisRequests_m;
- // Packet defragmentation queue -- comes before RX queue in path
- struct DefragQueueEntry
+ // Packets waiting for WHOIS replies or other decode info or missing fragments
+ struct RXQueueEntry
{
- DefragQueueEntry() : creationTime(0),totalFragments(0),haveFragments(0) {}
- uint64_t creationTime;
- SharedPtr<IncomingPacket> frag0;
- Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1];
+ RXQueueEntry() : timestamp(0) {}
+ uint64_t timestamp; // 0 if entry is not in use
+ uint64_t packetId;
+ IncomingPacket frag0; // head of packet
+ Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1]; // later fragments (if any)
unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
uint32_t haveFragments; // bit mask, LSB to MSB
+ bool complete; // if true, packet is complete
};
- Hashtable< uint64_t,DefragQueueEntry > _defragQueue;
- Mutex _defragQueue_m;
-
- // ZeroTier-layer RX queue of incoming packets in the process of being decoded
- std::list< SharedPtr<IncomingPacket> > _rxQueue;
+ RXQueueEntry _rxQueue[ZT_RX_QUEUE_SIZE];
Mutex _rxQueue_m;
+ /* Returns the matching or oldest entry. Caller must check timestamp and
+ * packet ID to determine which. */
+ inline RXQueueEntry *_findRXQueueEntry(uint64_t now,uint64_t packetId)
+ {
+ RXQueueEntry *rq;
+ RXQueueEntry *oldest = &(_rxQueue[ZT_RX_QUEUE_SIZE - 1]);
+ unsigned long i = ZT_RX_QUEUE_SIZE;
+ while (i) {
+ rq = &(_rxQueue[--i]);
+ if ((rq->packetId == packetId)&&(rq->timestamp))
+ return rq;
+ if ((now - rq->timestamp) >= ZT_RX_QUEUE_EXPIRE)
+ rq->timestamp = 0;
+ if (rq->timestamp < oldest->timestamp)
+ oldest = rq;
+ }
+ return oldest;
+ }
+
// ZeroTier-layer TX queue entry
struct TXQueueEntry
{
diff --git a/node/Utils.hpp b/node/Utils.hpp
index 17c00459..3f4cc765 100644
--- a/node/Utils.hpp
+++ b/node/Utils.hpp
@@ -51,9 +51,9 @@ public:
static inline bool secureEq(const void *a,const void *b,unsigned int len)
throw()
{
- char diff = 0;
+ uint8_t diff = 0;
for(unsigned int i=0;i<len;++i)
- diff |= ( (reinterpret_cast<const char *>(a))[i] ^ (reinterpret_cast<const char *>(b))[i] );
+ diff |= ( (reinterpret_cast<const uint8_t *>(a))[i] ^ (reinterpret_cast<const uint8_t *>(b))[i] );
return (diff == 0);
}
diff --git a/one.cpp b/one.cpp
index 115ad265..f68e3cec 100644
--- a/one.cpp
+++ b/one.cpp
@@ -70,14 +70,27 @@ using namespace ZeroTier;
static OneService *volatile zt1Service = (OneService *)0;
+#define PROGRAM_NAME "ZeroTier One"
+#define COPYRIGHT_NOTICE "Copyright © 2011–2016 ZeroTier, Inc."
+#define LICENSE_GRANT \
+ "This is free software: you may copy, modify, and/or distribute this" ZT_EOL_S \
+ "work under the terms of the GNU General Public License, version 3 or" ZT_EOL_S \
+ "later as published by the Free Software Foundation." ZT_EOL_S \
+ "No warranty expressed or implied." ZT_EOL_S
+
/****************************************************************************/
/* zerotier-cli personality */
/****************************************************************************/
static void cliPrintHelp(const char *pn,FILE *out)
{
- fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2015 ZeroTier, Inc."ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
- fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
+ fprintf(out,
+ "%s version %d.%d.%d" ZT_EOL_S,
+ PROGRAM_NAME,
+ ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
+ fprintf(out,
+ COPYRIGHT_NOTICE ZT_EOL_S
+ LICENSE_GRANT ZT_EOL_S);
fprintf(out,"Usage: %s [-switches] <command/path> [<args>]"ZT_EOL_S""ZT_EOL_S,pn);
fprintf(out,"Available switches:"ZT_EOL_S);
fprintf(out," -h - Display this help"ZT_EOL_S);
@@ -550,8 +563,13 @@ static int cli(int argc,char **argv)
static void idtoolPrintHelp(FILE *out,const char *pn)
{
- fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2015 ZeroTier, Inc."ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
- fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
+ fprintf(out,
+ "%s version %d.%d.%d" ZT_EOL_S,
+ PROGRAM_NAME,
+ ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
+ fprintf(out,
+ COPYRIGHT_NOTICE ZT_EOL_S
+ LICENSE_GRANT ZT_EOL_S);
fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
@@ -891,8 +909,13 @@ static BOOL IsCurrentUserLocalAdministrator(void)
static void printHelp(const char *cn,FILE *out)
{
- fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2015 ZeroTier, Inc."ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
- fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
+ fprintf(out,
+ "%s version %d.%d.%d" ZT_EOL_S,
+ PROGRAM_NAME,
+ ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
+ fprintf(out,
+ COPYRIGHT_NOTICE ZT_EOL_S
+ LICENSE_GRANT ZT_EOL_S);
std::string updateUrl(OneService::autoUpdateUrl());
if (updateUrl.length())
fprintf(out,"Automatic updates enabled:"ZT_EOL_S" %s"ZT_EOL_S" (all updates are securely authenticated by 256-bit ECDSA signature)"ZT_EOL_S""ZT_EOL_S,updateUrl.c_str());
diff --git a/osdep/Binder.hpp b/osdep/Binder.hpp
new file mode 100644
index 00000000..b68e6dac
--- /dev/null
+++ b/osdep/Binder.hpp
@@ -0,0 +1,321 @@
+/*
+ * ZeroTier One - Network Virtualization Everywhere
+ * Copyright (C) 2011-2016 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/>.
+ */
+
+#ifndef ZT_BINDER_HPP
+#define ZT_BINDER_HPP
+
+#include "../node/Constants.hpp"
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __WINDOWS__
+#include <WinSock2.h>
+#include <Windows.h>
+#include <ShlObj.h>
+#include <netioapi.h>
+#include <iphlpapi.h>
+#else
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <ifaddrs.h>
+#endif
+
+#include <string>
+#include <vector>
+#include <algorithm>
+#include <utility>
+
+#include "../node/NonCopyable.hpp"
+#include "../node/InetAddress.hpp"
+#include "../node/Mutex.hpp"
+
+#include "Phy.hpp"
+
+/**
+ * Period between binder rescans/refreshes
+ *
+ * OneService also does this on detected restarts.
+ */
+#define ZT_BINDER_REFRESH_PERIOD 30000
+
+namespace ZeroTier {
+
+/**
+ * Enumerates local devices and binds to all potential ZeroTier path endpoints
+ *
+ * This replaces binding to wildcard (0.0.0.0 and ::0) with explicit binding
+ * as part of the path to default gateway support. Under the hood it uses
+ * different queries on different OSes to enumerate devices, and also exposes
+ * device enumeration and endpoint IP data for use elsewhere.
+ *
+ * On OSes that do not support local port enumeration or where this is not
+ * meaningful, this degrades to binding to wildcard.
+ */
+class Binder : NonCopyable
+{
+private:
+ struct _Binding
+ {
+ _Binding() :
+ udpSock((PhySocket *)0),
+ tcpListenSock((PhySocket *)0),
+ address() {}
+
+ PhySocket *udpSock;
+ PhySocket *tcpListenSock;
+ InetAddress address;
+ };
+
+public:
+ Binder() {}
+
+ /**
+ * Close all bound ports
+ *
+ * This should be called on shutdown. It closes listen sockets and UDP ports
+ * but not TCP connections from any TCP listen sockets.
+ *
+ * @param phy Physical interface
+ */
+ template<typename PHY_HANDLER_TYPE>
+ void closeAll(Phy<PHY_HANDLER_TYPE> &phy)
+ {
+ Mutex::Lock _l(_lock);
+ for(typename std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i) {
+ phy.close(i->udpSock,false);
+ phy.close(i->tcpListenSock,false);
+ }
+ }
+
+ /**
+ * Scan local devices and addresses and rebind TCP and UDP
+ *
+ * This should be called after wake from sleep, on detected network device
+ * changes, on startup, or periodically (e.g. every 30-60s).
+ *
+ * @param phy Physical interface
+ * @param port Port to bind to on all interfaces (TCP and UDP)
+ * @param ignoreInterfacesByName Ignore these interfaces by name
+ * @param ignoreInterfacesByNamePrefix Ignore these interfaces by name-prefix (starts-with, e.g. zt ignores zt*)
+ * @param ignoreInterfacesByAddress Ignore these interfaces by address
+ * @tparam PHY_HANDLER_TYPE Type for Phy<> template
+ * @tparam INTERFACE_CHECKER Type for class containing shouldBindInterface() method
+ */
+ template<typename PHY_HANDLER_TYPE,typename INTERFACE_CHECKER>
+ void refresh(Phy<PHY_HANDLER_TYPE> &phy,unsigned int port,INTERFACE_CHECKER &ifChecker)
+ {
+ std::vector<InetAddress> localIfAddrs;
+ std::vector<_Binding> newBindings;
+ std::vector<std::string>::const_iterator si;
+ std::vector<InetAddress>::const_iterator ii;
+ typename std::vector<_Binding>::const_iterator bi;
+ PhySocket *udps;
+ //PhySocket *tcps;
+ InetAddress ip;
+ Mutex::Lock _l(_lock);
+
+#ifdef __WINDOWS__
+
+ char aabuf[32768];
+ ULONG aalen = sizeof(aabuf);
+ if (GetAdaptersAddresses(AF_UNSPEC,GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER,(void *)0,reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf),&aalen) == NO_ERROR) {
+ PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
+ while (a) {
+ PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
+ while (ua) {
+ InetAddress ip(ua->Address.lpSockaddr);
+ if (ifChecker.shouldBindInterface("",ip)) {
+ switch(ip.ipScope()) {
+ default: break;
+ case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
+ case InetAddress::IP_SCOPE_GLOBAL:
+ //case InetAddress::IP_SCOPE_LINK_LOCAL:
+ case InetAddress::IP_SCOPE_SHARED:
+ case InetAddress::IP_SCOPE_PRIVATE:
+ ip.setPort(port);
+ localIfAddrs.push_back(ip);
+ break;
+ }
+ }
+ ua = ua->Next;
+ }
+ a = a->Next;
+ }
+ }
+
+#else // not __WINDOWS__
+
+ struct ifaddrs *ifatbl = (struct ifaddrs *)0;
+ struct ifaddrs *ifa;
+ if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
+ ifa = ifatbl;
+ while (ifa) {
+ if ((ifa->ifa_name)&&(ifa->ifa_addr)) {
+ ip = *(ifa->ifa_addr);
+ if (ifChecker.shouldBindInterface(ifa->ifa_name,ip)) {
+ switch(ip.ipScope()) {
+ default: break;
+ case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
+ case InetAddress::IP_SCOPE_GLOBAL:
+ //case InetAddress::IP_SCOPE_LINK_LOCAL:
+ case InetAddress::IP_SCOPE_SHARED:
+ case InetAddress::IP_SCOPE_PRIVATE:
+ ip.setPort(port);
+ localIfAddrs.push_back(ip);
+ break;
+ }
+ }
+ }
+ ifa = ifa->ifa_next;
+ }
+ freeifaddrs(ifatbl);
+ }
+
+#endif
+
+ // Default to binding to wildcard if we can't enumerate addresses
+ if (localIfAddrs.size() == 0) {
+ localIfAddrs.push_back(InetAddress((uint32_t)0,port));
+ localIfAddrs.push_back(InetAddress((const void *)"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,port));
+ }
+
+ // Close any old bindings to anything that doesn't exist anymore
+ for(bi=_bindings.begin();bi!=_bindings.end();++bi) {
+ if (std::find(localIfAddrs.begin(),localIfAddrs.end(),bi->address) == localIfAddrs.end()) {
+ phy.close(bi->udpSock,false);
+ phy.close(bi->tcpListenSock,false);
+ }
+ }
+
+ for(ii=localIfAddrs.begin();ii!=localIfAddrs.end();++ii) {
+ // Copy over bindings that still are valid
+ for(bi=_bindings.begin();bi!=_bindings.end();++bi) {
+ if (bi->address == *ii) {
+ newBindings.push_back(*bi);
+ break;
+ }
+ }
+
+ // Add new bindings
+ if (bi == _bindings.end()) {
+ udps = phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(*ii)),(void *)0,ZT_UDP_DESIRED_BUF_SIZE);
+ if (udps) {
+ //tcps = phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&ii),(void *)0);
+ //if (tcps) {
+ newBindings.push_back(_Binding());
+ newBindings.back().udpSock = udps;
+ //newBindings.back().tcpListenSock = tcps;
+ newBindings.back().address = *ii;
+ //} else {
+ // phy.close(udps,false);
+ //}
+ }
+ }
+ }
+
+ /*
+ for(bi=newBindings.begin();bi!=newBindings.end();++bi) {
+ printf("Binder: bound to %s\n",bi->address.toString().c_str());
+ }
+ */
+
+ // Swapping pointers and then letting the old one fall out of scope is faster than copying again
+ _bindings.swap(newBindings);
+ }
+
+ /**
+ * Send a UDP packet from the specified local interface, or all
+ *
+ * Unfortunately even by examining the routing table there is no ultimately
+ * robust way to tell where we might reach another host that works in all
+ * environments. As a result, we send packets with null (wildcard) local
+ * addresses from *every* bound interface.
+ *
+ * These are typically initial HELLOs, path probes, etc., since normal
+ * conversations will have a local endpoint address. So the cost is low and
+ * if the peer is not reachable via that route then the packet will go
+ * nowhere and nothing will happen.
+ *
+ * It will of course only send via interface bindings of the same socket
+ * family. No point in sending V4 via V6 or vice versa.
+ *
+ * In any case on most hosts there's only one or two interfaces that we
+ * will use, so none of this is particularly costly.
+ *
+ * @param local Local interface address or null address for 'all'
+ * @param remote Remote address
+ * @param data Data to send
+ * @param len Length of data
+ * @param v4ttl If non-zero, send this packet with the specified IP TTL (IPv4 only)
+ */
+ template<typename PHY_HANDLER_TYPE>
+ inline bool udpSend(Phy<PHY_HANDLER_TYPE> &phy,const InetAddress &local,const InetAddress &remote,const void *data,unsigned int len,unsigned int v4ttl = 0) const
+ {
+ Mutex::Lock _l(_lock);
+ if (local) {
+ for(typename std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i) {
+ if (i->address == local) {
+ if ((v4ttl)&&(local.ss_family == AF_INET))
+ phy.setIp4UdpTtl(i->udpSock,v4ttl);
+ const bool result = phy.udpSend(i->udpSock,reinterpret_cast<const struct sockaddr *>(&remote),data,len);
+ if ((v4ttl)&&(local.ss_family == AF_INET))
+ phy.setIp4UdpTtl(i->udpSock,255);
+ return result;
+ }
+ }
+ return false;
+ } else {
+ bool result = false;
+ for(typename std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i) {
+ if (i->address.ss_family == remote.ss_family) {
+ if ((v4ttl)&&(remote.ss_family == AF_INET))
+ phy.setIp4UdpTtl(i->udpSock,v4ttl);
+ result |= phy.udpSend(i->udpSock,reinterpret_cast<const struct sockaddr *>(&remote),data,len);
+ if ((v4ttl)&&(remote.ss_family == AF_INET))
+ phy.setIp4UdpTtl(i->udpSock,255);
+ }
+ }
+ return result;
+ }
+ }
+
+ /**
+ * @return All currently bound local interface addresses
+ */
+ inline std::vector<InetAddress> allBoundLocalInterfaceAddresses()
+ {
+ Mutex::Lock _l(_lock);
+ std::vector<InetAddress> aa;
+ for(std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i)
+ aa.push_back(i->address);
+ return aa;
+ }
+
+private:
+ std::vector<_Binding> _bindings;
+ Mutex _lock;
+};
+
+} // namespace ZeroTier
+
+#endif
diff --git a/osdep/Http.cpp b/osdep/Http.cpp
index 2e13dd3a..6e3135de 100644
--- a/osdep/Http.cpp
+++ b/osdep/Http.cpp
@@ -53,7 +53,7 @@ static const struct http_parser_settings HTTP_PARSER_SETTINGS = {
struct HttpPhyHandler
{
// not used
- inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len) {}
+ inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len) {}
inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from) {}
inline void phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
diff --git a/osdep/LinuxEthernetTap.cpp b/osdep/LinuxEthernetTap.cpp
index 3e225b36..c66b7a38 100644
--- a/osdep/LinuxEthernetTap.cpp
+++ b/osdep/LinuxEthernetTap.cpp
@@ -83,8 +83,11 @@ LinuxEthernetTap::LinuxEthernetTap(
throw std::runtime_error("max tap MTU is 2800");
_fd = ::open("/dev/net/tun",O_RDWR);
- if (_fd <= 0)
- throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
+ if (_fd <= 0) {
+ _fd = ::open("/dev/tun",O_RDWR);
+ if (_fd <= 0)
+ throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
+ }
struct ifreq ifr;
memset(&ifr,0,sizeof(ifr));
diff --git a/osdep/Phy.hpp b/osdep/Phy.hpp
index 0f993c9f..c32a36fd 100644
--- a/osdep/Phy.hpp
+++ b/osdep/Phy.hpp
@@ -89,7 +89,7 @@ typedef void PhySocket;
*
* For all platforms:
*
- * phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
+ * phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
* phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
* phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
* phyOnTcpClose(PhySocket *sock,void **uptr)
@@ -963,7 +963,7 @@ public:
long n = (long)::recvfrom(s->sock,buf,sizeof(buf),0,(struct sockaddr *)&ss,&slen);
if (n > 0) {
try {
- _handler->phyOnDatagram((PhySocket *)&(*s),&(s->uptr),(const struct sockaddr *)&ss,(void *)buf,(unsigned long)n);
+ _handler->phyOnDatagram((PhySocket *)&(*s),&(s->uptr),(const struct sockaddr *)&(s->saddr),(const struct sockaddr *)&ss,(void *)buf,(unsigned long)n);
} catch ( ... ) {}
} else if (n < 0)
break;
diff --git a/osdep/RoutingTable.cpp b/osdep/RoutingTable.cpp
new file mode 100644
index 00000000..40523898
--- /dev/null
+++ b/osdep/RoutingTable.cpp
@@ -0,0 +1,608 @@
+/*
+ * ZeroTier One - Network Virtualization Everywhere
+ * Copyright (C) 2011-2016 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/>.
+ */
+
+#include "../node/Constants.hpp"
+
+#ifdef __WINDOWS__
+#include <WinSock2.h>
+#include <Windows.h>
+#include <netioapi.h>
+#include <IPHlpApi.h>
+#endif
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef __UNIX_LIKE__
+#include <unistd.h>
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <net/route.h>
+#include <net/if.h>
+#include <net/if_dl.h>
+#include <ifaddrs.h>
+#endif
+
+#include <vector>
+#include <algorithm>
+#include <utility>
+
+#include "RoutingTable.hpp"
+
+#define ZT_BSD_ROUTE_CMD "/sbin/route"
+#define ZT_LINUX_IP_COMMAND "/sbin/ip"
+
+namespace ZeroTier {
+
+// ---------------------------------------------------------------------------
+
+#ifdef __LINUX__
+
+std::vector<RoutingTable::Entry> RoutingTable::get(bool includeLinkLocal,bool includeLoopback)
+{
+ char buf[131072];
+ char *stmp,*stmp2;
+ std::vector<RoutingTable::Entry> entries;
+
+ {
+ int fd = ::open("/proc/net/route",O_RDONLY);
+ if (fd <= 0)
+ buf[0] = (char)0;
+ else {
+ int n = (int)::read(fd,buf,sizeof(buf) - 1);
+ ::close(fd);
+ if (n < 0) n = 0;
+ buf[n] = (char)0;
+ }
+ }
+
+ int lineno = 0;
+ for(char *line=Utils::stok(buf,"\r\n",&stmp);(line);line=Utils::stok((char *)0,"\r\n",&stmp)) {
+ if (lineno == 0) {
+ ++lineno;
+ continue; // skip header
+ }
+
+ char *iface = (char *)0;
+ uint32_t destination = 0;
+ uint32_t gateway = 0;
+ int metric = 0;
+ uint32_t mask = 0;
+
+ int fno = 0;
+ for(char *f=Utils::stok(line,"\t \r\n",&stmp2);(f);f=Utils::stok((char *)0,"\t \r\n",&stmp2)) {
+ switch(fno) {
+ case 0: iface = f; break;
+ case 1: destination = (uint32_t)Utils::hexStrToULong(f); break;
+ case 2: gateway = (uint32_t)Utils::hexStrToULong(f); break;
+ case 6: metric = (int)Utils::strToInt(f); break;
+ case 7: mask = (uint32_t)Utils::hexStrToULong(f); break;
+ }
+ ++fno;
+ }
+
+ if ((iface)&&(destination)) {
+ RoutingTable::Entry e;
+ if (destination)
+ e.destination.set(&destination,4,Utils::countBits(mask));
+ e.gateway.set(&gateway,4,0);
+ e.deviceIndex = 0; // not used on Linux
+ e.metric = metric;
+ Utils::scopy(e.device,sizeof(e.device),iface);
+ if ((e.destination)&&((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback())&&(strcmp(iface,"lo")))))
+ entries.push_back(e);
+ }
+
+ ++lineno;
+ }
+
+ {
+ int fd = ::open("/proc/net/ipv6_route",O_RDONLY);
+ if (fd <= 0)
+ buf[0] = (char)0;
+ else {
+ int n = (int)::read(fd,buf,sizeof(buf) - 1);
+ ::close(fd);
+ if (n < 0) n = 0;
+ buf[n] = (char)0;
+ }
+ }
+
+ for(char *line=Utils::stok(buf,"\r\n",&stmp);(line);line=Utils::stok((char *)0,"\r\n",&stmp)) {
+ char *destination = (char *)0;
+ unsigned int destPrefixLen = 0;
+ char *gateway = (char *)0; // next hop in ipv6 terminology
+ int metric = 0;
+ char *device = (char *)0;
+
+ int fno = 0;
+ for(char *f=Utils::stok(line,"\t \r\n",&stmp2);(f);f=Utils::stok((char *)0,"\t \r\n",&stmp2)) {
+ switch(fno) {
+ case 0: destination = f; break;
+ case 1: destPrefixLen = (unsigned int)Utils::hexStrToULong(f); break;
+ case 4: gateway = f; break;
+ case 5: metric = (int)Utils::hexStrToLong(f); break;
+ case 9: device = f; break;
+ }
+ ++fno;
+ }
+
+ if ((device)&&(destination)) {
+ unsigned char tmp[16];
+ RoutingTable::Entry e;
+ Utils::unhex(destination,tmp,16);
+ if ((!Utils::isZero(tmp,16))&&(tmp[0] != 0xff))
+ e.destination.set(tmp,16,destPrefixLen);
+ Utils::unhex(gateway,tmp,16);
+ e.gateway.set(tmp,16,0);
+ e.deviceIndex = 0; // not used on Linux
+ e.metric = metric;
+ Utils::scopy(e.device,sizeof(e.device),device);
+ if ((e.destination)&&((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback())&&(strcmp(device,"lo")))))
+ entries.push_back(e);
+ }
+ }
+
+ std::sort(entries.begin(),entries.end());
+ return entries;
+}
+
+RoutingTable::Entry RoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric,bool ifscope)
+{
+ char metstr[128];
+
+ if ((!gateway)&&((!device)||(!device[0])))
+ return RoutingTable::Entry();
+
+ Utils::snprintf(metstr,sizeof(metstr),"%d",metric);
+
+ if (metric < 0) {
+ long pid = (long)vfork();
+ if (pid == 0) {
+ if (gateway) {
+ if ((device)&&(device[0])) {
+ ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","del",destination.toString().c_str(),"via",gateway.toIpString().c_str(),"dev",device,(const char *)0);
+ } else {
+ ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","del",destination.toString().c_str(),"via",gateway.toIpString().c_str(),(const char *)0);
+ }
+ } else {
+ ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","del",destination.toString().c_str(),"dev",device,(const char *)0);
+ }
+ ::_exit(-1);
+ } else if (pid > 0) {
+ int exitcode = -1;
+ ::waitpid(pid,&exitcode,0);
+ }
+ } else {
+ long pid = (long)vfork();
+ if (pid == 0) {
+ if (gateway) {
+ if ((device)&&(device[0])) {
+ ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","replace",destination.toString().c_str(),"metric",metstr,"via",gateway.toIpString().c_str(),"dev",device,(const char *)0);
+ } else {
+ ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","replace",destination.toString().c_str(),"metric",metstr,"via",gateway.toIpString().c_str(),(const char *)0);
+ }
+ } else {
+ ::execl(ZT_LINUX_IP_COMMAND,ZT_LINUX_IP_COMMAND,"route","replace",destination.toString().c_str(),"metric",metstr,"dev",device,(const char *)0);
+ }
+ ::_exit(-1);
+ } else if (pid > 0) {
+ int exitcode = -1;
+ ::waitpid(pid,&exitcode,0);
+ }
+ }
+
+ std::vector<RoutingTable::Entry> rtab(get(true,true));
+ std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
+ for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
+ if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
+ if ((device)&&(device[0])) {
+ if (!strcmp(device,e->device)) {
+ if (metric == e->metric)
+ bestEntry = e;
+ }
+ }
+ if (bestEntry == rtab.end())
+ bestEntry = e;
+ }
+ }
+ if (bestEntry != rtab.end())
+ return *bestEntry;
+
+ return RoutingTable::Entry();
+}
+
+#endif // __LINUX__
+
+// ---------------------------------------------------------------------------
+
+#ifdef __BSD__
+
+std::vector<RoutingTable::Entry> RoutingTable::get(bool includeLinkLocal,bool includeLoopback)
+{
+ std::vector<RoutingTable::Entry> entries;
+ int mib[6];
+ size_t needed;
+
+ mib[0] = CTL_NET;
+ mib[1] = PF_ROUTE;
+ mib[2] = 0;
+ mib[3] = 0;
+ mib[4] = NET_RT_DUMP;
+ mib[5] = 0;
+ if (!sysctl(mib,6,NULL,&needed,NULL,0)) {
+ if (needed <= 0)
+ return entries;
+
+ char *buf = (char *)::malloc(needed);
+ if (buf) {
+ if (!sysctl(mib,6,buf,&needed,NULL,0)) {
+ struct rt_msghdr *rtm;
+ for(char *next=buf,*end=buf+needed;next<end;) {
+ rtm = (struct rt_msghdr *)next;
+ char *saptr = (char *)(rtm + 1);
+ char *saend = next + rtm->rtm_msglen;
+
+ if (((rtm->rtm_flags & RTF_LLINFO) == 0)&&((rtm->rtm_flags & RTF_HOST) == 0)&&((rtm->rtm_flags & RTF_UP) != 0)&&((rtm->rtm_flags & RTF_MULTICAST) == 0)) {
+ RoutingTable::Entry e;
+ e.deviceIndex = -9999; // unset
+
+ int which = 0;
+ while (saptr < saend) {
+ struct sockaddr *sa = (struct sockaddr *)saptr;
+ unsigned int salen = sa->sa_len;
+ if (!salen)
+ break;
+
+ // Skip missing fields in rtm_addrs bit field
+ while ((rtm->rtm_addrs & 1) == 0) {
+ rtm->rtm_addrs >>= 1;
+ ++which;
+ if (which > 6)
+ break;
+ }
+ if (which > 6)
+ break;
+
+ rtm->rtm_addrs >>= 1;
+ switch(which++) {
+ case 0:
+ //printf("RTA_DST\n");
+ if (sa->sa_family == AF_INET6) {
+ struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
+ // Nobody expects the Spanish inquisition!
+ if ((sin6->sin6_addr.s6_addr[0] == 0xfe)&&((sin6->sin6_addr.s6_addr[1] & 0xc0) == 0x80)) {
+ // Our chief weapon is... in-band signaling!
+ // Seriously who in the living fuck thought this was a good idea and
+ // then had the sadistic idea to not document it anywhere? Of course it's
+ // not like there is any documentation on BSD sysctls anyway.
+ unsigned int interfaceIndex = ((((unsigned int)sin6->sin6_addr.s6_addr[2]) << 8) & 0xff) | (((unsigned int)sin6->sin6_addr.s6_addr[3]) & 0xff);
+ sin6->sin6_addr.s6_addr[2] = 0;
+ sin6->sin6_addr.s6_addr[3] = 0;
+ if (!sin6->sin6_scope_id)
+ sin6->sin6_scope_id = interfaceIndex;
+ }
+ }
+ e.destination = *sa;
+ break;
+ case 1:
+ //printf("RTA_GATEWAY\n");
+ switch(sa->sa_family) {
+ case AF_LINK:
+ e.deviceIndex = (int)((const struct sockaddr_dl *)sa)->sdl_index;
+ break;
+ case AF_INET:
+ case AF_INET6:
+ e.gateway = *sa;
+ break;
+ }
+ break;
+ case 2: {
+ if (e.destination.isV6()) {
+ salen = sizeof(struct sockaddr_in6); // Confess!
+ unsigned int bits = 0;
+ for(int i=0;i<16;++i) {
+ unsigned char c = (unsigned char)((const struct sockaddr_in6 *)sa)->sin6_addr.s6_addr[i];
+ if (c == 0xff)
+ bits += 8;
+ else break;
+ /* must they be multiples of 8? Most of the BSD source I can find says yes..?
+ else {
+ while ((c & 0x80) == 0x80) {
+ ++bits;
+ c <<= 1;
+ }
+ break;
+ }
+ */
+ }
+ e.destination.setPort(bits);
+ } else {
+ salen = sizeof(struct sockaddr_in); // Confess!
+ e.destination.setPort((unsigned int)Utils::countBits((uint32_t)((const struct sockaddr_in *)sa)->sin_addr.s_addr));
+ }
+ //printf("RTA_NETMASK\n");
+ } break;
+ /*
+ case 3:
+ //printf("RTA_GENMASK\n");
+ break;
+ case 4:
+ //printf("RTA_IFP\n");
+ break;
+ case 5:
+ //printf("RTA_IFA\n");
+ break;
+ case 6:
+ //printf("RTA_AUTHOR\n");
+ break;
+ */
+ }
+
+ saptr += salen;
+ }
+
+ e.metric = (int)rtm->rtm_rmx.rmx_hopcount;
+ if (e.metric < 0)
+ e.metric = 0;
+
+ InetAddress::IpScope dscope = e.destination.ipScope();
+ if ( ((includeLinkLocal)||(dscope != InetAddress::IP_SCOPE_LINK_LOCAL)) && ((includeLoopback)||((dscope != InetAddress::IP_SCOPE_LOOPBACK) && (e.gateway.ipScope() != InetAddress::IP_SCOPE_LOOPBACK) )))
+ entries.push_back(e);
+ }
+
+ next = saend;
+ }
+ }
+
+ ::free(buf);
+ }
+ }
+
+ for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e1(entries.begin());e1!=entries.end();++e1) {
+ if ((!e1->device[0])&&(e1->deviceIndex >= 0))
+ if_indextoname(e1->deviceIndex,e1->device);
+ }
+ for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e1(entries.begin());e1!=entries.end();++e1) {
+ if ((!e1->device[0])&&(e1->gateway)) {
+ int bestMetric = 9999999;
+ for(std::vector<ZeroTier::RoutingTable::Entry>::iterator e2(entries.begin());e2!=entries.end();++e2) {
+ if ((e2->destination.containsAddress(e1->gateway))&&(e2->metric <= bestMetric)) {
+ bestMetric = e2->metric;
+ Utils::scopy(e1->device,sizeof(e1->device),e2->device);
+ }
+ }
+ }
+ }
+
+ std::sort(entries.begin(),entries.end());
+
+ return entries;
+}
+
+RoutingTable::Entry RoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric,bool ifscope)
+{
+ if ((!gateway)&&((!device)||(!device[0])))
+ return RoutingTable::Entry();
+
+ std::vector<RoutingTable::Entry> rtab(get(true,true));
+
+ for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
+ if (e->destination == destination) {
+ if (((!device)||(!device[0]))||(!strcmp(device,e->device))) {
+ long p = (long)fork();
+ if (p > 0) {
+ int exitcode = -1;
+ ::waitpid(p,&exitcode,0);
+ } else if (p == 0) {
+ ::close(STDOUT_FILENO);
+ ::close(STDERR_FILENO);
+ ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"delete",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),(const char *)0);
+ ::_exit(-1);
+ }
+ }
+ }
+ }
+
+ if (metric < 0)
+ return RoutingTable::Entry();
+
+ {
+ char hcstr[64];
+ Utils::snprintf(hcstr,sizeof(hcstr),"%d",metric);
+ long p = (long)fork();
+ if (p > 0) {
+ int exitcode = -1;
+ ::waitpid(p,&exitcode,0);
+ } else if (p == 0) {
+ ::close(STDOUT_FILENO);
+ ::close(STDERR_FILENO);
+ if (gateway) {
+ ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"add",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),gateway.toIpString().c_str(),"-hopcount",hcstr,(const char *)0);
+ } else if ((device)&&(device[0])) {
+ ::execl(ZT_BSD_ROUTE_CMD,ZT_BSD_ROUTE_CMD,"add",(destination.isV6() ? "-inet6" : "-inet"),destination.toString().c_str(),"-interface",device,"-hopcount",hcstr,(const char *)0);
+ }
+ ::_exit(-1);
+ }
+ }
+
+ rtab = get(true,true);
+ std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
+ for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
+ if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
+ if ((device)&&(device[0])) {
+ if (!strcmp(device,e->device)) {
+ if (metric == e->metric)
+ bestEntry = e;
+ }
+ }
+ if (bestEntry == rtab.end())
+ bestEntry = e;
+ }
+ }
+ if (bestEntry != rtab.end())
+ return *bestEntry;
+
+ return RoutingTable::Entry();
+}
+
+#endif // __BSD__
+
+// ---------------------------------------------------------------------------
+
+#ifdef __WINDOWS__
+
+static void _copyInetAddressToSockaddrInet(const InetAddress &a,SOCKADDR_INET &sinet)
+{
+ memset(&sinet,0,sizeof(sinet));
+ if (a.isV4()) {
+ sinet.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)a.rawIpData());
+ sinet.Ipv4.sin_family = AF_INET;
+ sinet.Ipv4.sin_port = htons(a.port());
+ } else if (a.isV6()) {
+ memcpy(sinet.Ipv6.sin6_addr.u.Byte,a.rawIpData(),16);
+ sinet.Ipv6.sin6_family = AF_INET6;
+ sinet.Ipv6.sin6_port = htons(a.port());
+ }
+}
+
+std::vector<RoutingTable::Entry> RoutingTable::get(bool includeLinkLocal,bool includeLoopback) const
+{
+ std::vector<RoutingTable::Entry> entries;
+ PMIB_IPFORWARD_TABLE2 rtbl = NULL;
+
+ if (GetIpForwardTable2(AF_UNSPEC,&rtbl) != NO_ERROR)
+ return entries;
+ if (!rtbl)
+ return entries;
+
+ for(ULONG r=0;r<rtbl->NumEntries;++r) {
+ RoutingTable::Entry e;
+ switch(rtbl->Table[r].DestinationPrefix.Prefix.si_family) {
+ case AF_INET:
+ e.destination.set(&(rtbl->Table[r].DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr),4,rtbl->Table[r].DestinationPrefix.PrefixLength);
+ break;
+ case AF_INET6:
+ e.destination.set(rtbl->Table[r].DestinationPrefix.Prefix.Ipv6.sin6_addr.u.Byte,16,rtbl->Table[r].DestinationPrefix.PrefixLength);
+ break;
+ }
+ switch(rtbl->Table[r].NextHop.si_family) {
+ case AF_INET:
+ e.gateway.set(&(rtbl->Table[r].NextHop.Ipv4.sin_addr.S_un.S_addr),4,0);
+ break;
+ case AF_INET6:
+ e.gateway.set(rtbl->Table[r].NextHop.Ipv6.sin6_addr.u.Byte,16,0);
+ break;
+ }
+ e.deviceIndex = (int)rtbl->Table[r].InterfaceIndex;
+ e.metric = (int)rtbl->Table[r].Metric;
+ ConvertInterfaceLuidToNameA(&(rtbl->Table[r].InterfaceLuid),e.device,sizeof(e.device));
+ if ((e.destination)&&((includeLinkLocal)||(!e.destination.isLinkLocal()))&&((includeLoopback)||((!e.destination.isLoopback())&&(!e.gateway.isLoopback()))))
+ entries.push_back(e);
+ }
+
+ FreeMibTable(rtbl);
+ std::sort(entries.begin(),entries.end());
+ return entries;
+}
+
+RoutingTable::Entry RoutingTable::set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric,bool ifscope)
+{
+ NET_LUID luid;
+ luid.Value = 0;
+ if (ConvertInterfaceNameToLuidA(device,&luid) != NO_ERROR)
+ return RoutingTable::Entry();
+
+ bool needCreate = true;
+ PMIB_IPFORWARD_TABLE2 rtbl = NULL;
+ if (GetIpForwardTable2(AF_UNSPEC,&rtbl) != NO_ERROR)
+ return RoutingTable::Entry();
+ if (!rtbl)
+ return RoutingTable::Entry();
+ for(ULONG r=0;r<rtbl->NumEntries;++r) {
+ if (rtbl->Table[r].InterfaceLuid.Value == luid.Value) {
+ InetAddress rdest;
+ switch(rtbl->Table[r].DestinationPrefix.Prefix.si_family) {
+ case AF_INET:
+ rdest.set(&(rtbl->Table[r].DestinationPrefix.Prefix.Ipv4.sin_addr.S_un.S_addr),4,rtbl->Table[r].DestinationPrefix.PrefixLength);
+ break;
+ case AF_INET6:
+ rdest.set(rtbl->Table[r].DestinationPrefix.Prefix.Ipv6.sin6_addr.u.Byte,16,rtbl->Table[r].DestinationPrefix.PrefixLength);
+ break;
+ }
+ if (rdest == destination) {
+ if (metric >= 0) {
+ _copyInetAddressToSockaddrInet(gateway,rtbl->Table[r].NextHop);
+ rtbl->Table[r].Metric = metric;
+ SetIpForwardEntry2(&(rtbl->Table[r]));
+ needCreate = false;
+ } else {
+ DeleteIpForwardEntry2(&(rtbl->Table[r]));
+ FreeMibTable(rtbl);
+ return RoutingTable::Entry();
+ }
+ }
+ }
+ }
+ FreeMibTable(rtbl);
+
+ if ((metric >= 0)&&(needCreate)) {
+ MIB_IPFORWARD_ROW2 nr;
+ InitializeIpForwardEntry(&nr);
+ nr.InterfaceLuid.Value = luid.Value;
+ _copyInetAddressToSockaddrInet(destination,nr.DestinationPrefix.Prefix);
+ nr.DestinationPrefix.PrefixLength = destination.netmaskBits();
+ _copyInetAddressToSockaddrInet(gateway,nr.NextHop);
+ nr.Metric = metric;
+ nr.Protocol = MIB_IPPROTO_NETMGMT;
+ DWORD result = CreateIpForwardEntry2(&nr);
+ if (result != NO_ERROR)
+ return RoutingTable::Entry();
+ }
+
+ std::vector<RoutingTable::Entry> rtab(get(true,true));
+ std::vector<RoutingTable::Entry>::iterator bestEntry(rtab.end());
+ for(std::vector<RoutingTable::Entry>::iterator e(rtab.begin());e!=rtab.end();++e) {
+ if ((e->destination == destination)&&(e->gateway.ipsEqual(gateway))) {
+ if ((device)&&(device[0])) {
+ if (!strcmp(device,e->device)) {
+ if (metric == e->metric)
+ bestEntry = e;
+ }
+ }
+ if (bestEntry == rtab.end())
+ bestEntry = e;
+ }
+ }
+ if (bestEntry != rtab.end())
+ return *bestEntry;
+ return RoutingTable::Entry();
+}
+
+#endif // __WINDOWS__
+
+// ---------------------------------------------------------------------------
+
+} // namespace ZeroTier
diff --git a/osdep/RoutingTable.hpp b/osdep/RoutingTable.hpp
new file mode 100644
index 00000000..6f430136
--- /dev/null
+++ b/osdep/RoutingTable.hpp
@@ -0,0 +1,92 @@
+/*
+ * ZeroTier One - Network Virtualization Everywhere
+ * Copyright (C) 2011-2016 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/>.
+ */
+
+#ifndef ZT_ROUTINGTABLE_HPP
+#define ZT_ROUTINGTABLE_HPP
+
+#include <vector>
+
+#include "../node/Constants.hpp"
+#include "../node/InetAddress.hpp"
+
+namespace ZeroTier {
+
+class RoutingTable
+{
+public:
+ struct Entry
+ {
+ /**
+ * Destination IP and netmask bits (CIDR format)
+ */
+ InetAddress destination;
+
+ /**
+ * Gateway or null address if direct link-level route, netmask/port part of InetAddress not used
+ */
+ InetAddress gateway;
+
+ /**
+ * System device index or ID (not included in comparison operators, may not be set on all platforms)
+ */
+ int deviceIndex;
+
+ /**
+ * Metric or hop count -- higher = lower routing priority
+ */
+ int metric;
+
+ /**
+ * Interface scoped route? (always false if not meaningful on this OS)
+ */
+ bool ifscope;
+
+ /**
+ * System device name (may be empty if it doesn't exist or isn't important on this OS)
+ */
+ char device[128];
+
+ /**
+ * @return True if at least one required field is present (object is not null)
+ */
+ inline operator bool() const { return ((destination)||(gateway)); }
+ };
+
+ /**
+ * Get routing table
+ *
+ * @param includeLinkLocal Include link-local IPs?
+ * @param includeLoopback Include loopback routes?
+ */
+ static std::vector<RoutingTable::Entry> get(bool includeLinkLocal,bool includeLoopback);
+
+ /**
+ * Add or replace a routing table entry
+ *
+ * @param destination Route destination
+ * @param gateway Gateway or null if local
+ * @param device Device name (if applicable)
+ * @param metric Route metric (if applicable)
+ * @param ifscope Interface bound route? If so, device must be set. (only applicable on some OSes)
+ */
+ static RoutingTable::Entry set(const InetAddress &destination,const InetAddress &gateway,const char *device,int metric,bool ifscope);
+};
+
+} // namespace ZeroTier
+
+#endif
diff --git a/osdep/WindowsEthernetTap.cpp b/osdep/WindowsEthernetTap.cpp
index 5cf74aa6..d60c0d54 100644
--- a/osdep/WindowsEthernetTap.cpp
+++ b/osdep/WindowsEthernetTap.cpp
@@ -68,7 +68,6 @@ typedef BOOL (WINAPI *SetupDiSetClassInstallParamsA_t)(_In_ HDEVINFO DeviceInfoS
typedef CONFIGRET (WINAPI *CM_Get_Device_ID_ExA_t)(_In_ DEVINST dnDevInst,_Out_writes_(BufferLen) PSTR Buffer,_In_ ULONG BufferLen,_In_ ULONG ulFlags,_In_opt_ HMACHINE hMachine);
typedef BOOL (WINAPI *SetupDiGetDeviceInstanceIdA_t)(_In_ HDEVINFO DeviceInfoSet,_In_ PSP_DEVINFO_DATA DeviceInfoData,_Out_writes_opt_(DeviceInstanceIdSize) PSTR DeviceInstanceId,_In_ DWORD DeviceInstanceIdSize,_Out_opt_ PDWORD RequiredSize);
-
namespace ZeroTier {
namespace {
@@ -477,7 +476,7 @@ WindowsEthernetTap::WindowsEthernetTap(
std::string mySubkeyName;
if (mtu > 2800)
- throw std::runtime_error("MTU too large for Windows tap");
+ throw std::runtime_error("MTU too large.");
// We "tag" registry entries with the network ID to identify persistent devices
Utils::snprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)nwid);
@@ -696,37 +695,39 @@ bool WindowsEthernetTap::removeIp(const InetAddress &ip)
try {
MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
- for(DWORD i=0;i<ipt->NumEntries;++i) {
- if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
- InetAddress addr;
- switch(ipt->Table[i].Address.si_family) {
- case AF_INET:
- addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
- break;
- case AF_INET6:
- addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
- if (addr.ipScope() == InetAddress::IP_SCOPE_LINK_LOCAL)
- continue; // can't remove link-local IPv6 addresses
- break;
- }
- if (addr == ip) {
- DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
- FreeMibTable(ipt);
-
- std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
- std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
- std::string ipstr(ip.toIpString());
- for(std::vector<std::string>::iterator rip(regIps.begin()),rm(regSubnetMasks.begin());((rip!=regIps.end())&&(rm!=regSubnetMasks.end()));++rip,++rm) {
- if (*rip == ipstr) {
- regIps.erase(rip);
- regSubnetMasks.erase(rm);
- _setRegistryIPv4Value("IPAddress",regIps);
- _setRegistryIPv4Value("SubnetMask",regSubnetMasks);
+ if ((ipt)&&(ipt->NumEntries > 0)) {
+ for(DWORD i=0;i<(DWORD)ipt->NumEntries;++i) {
+ if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
+ InetAddress addr;
+ switch(ipt->Table[i].Address.si_family) {
+ case AF_INET:
+ addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
+ break;
+ case AF_INET6:
+ addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
+ if (addr.ipScope() == InetAddress::IP_SCOPE_LINK_LOCAL)
+ continue; // can't remove link-local IPv6 addresses
break;
- }
}
+ if (addr == ip) {
+ DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
+ FreeMibTable(ipt);
+
+ std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
+ std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
+ std::string ipstr(ip.toIpString());
+ for(std::vector<std::string>::iterator rip(regIps.begin()),rm(regSubnetMasks.begin());((rip!=regIps.end())&&(rm!=regSubnetMasks.end()));++rip,++rm) {
+ if (*rip == ipstr) {
+ regIps.erase(rip);
+ regSubnetMasks.erase(rm);
+ _setRegistryIPv4Value("IPAddress",regIps);
+ _setRegistryIPv4Value("SubnetMask",regSubnetMasks);
+ break;
+ }
+ }
- return true;
+ return true;
+ }
}
}
}
@@ -747,19 +748,21 @@ std::vector<InetAddress> WindowsEthernetTap::ips() const
try {
MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
- for(DWORD i=0;i<ipt->NumEntries;++i) {
- if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
- switch(ipt->Table[i].Address.si_family) {
- case AF_INET: {
- InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
- if (ip != InetAddress::LO4)
- addrs.push_back(ip);
- } break;
- case AF_INET6: {
- InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
- if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
- addrs.push_back(ip);
- } break;
+ if ((ipt)&&(ipt->NumEntries > 0)) {
+ for(DWORD i=0;i<(DWORD)ipt->NumEntries;++i) {
+ if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
+ switch(ipt->Table[i].Address.si_family) {
+ case AF_INET: {
+ InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
+ if (ip != InetAddress::LO4)
+ addrs.push_back(ip);
+ } break;
+ case AF_INET6: {
+ InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
+ if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
+ addrs.push_back(ip);
+ } break;
+ }
}
}
}
@@ -768,7 +771,7 @@ std::vector<InetAddress> WindowsEthernetTap::ips() const
} catch ( ... ) {} // sanity check, shouldn't happen unless out of memory
std::sort(addrs.begin(),addrs.end());
- std::unique(addrs.begin(),addrs.end());
+ addrs.erase(std::unique(addrs.begin(),addrs.end()),addrs.end());
return addrs;
}
@@ -825,14 +828,16 @@ void WindowsEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,
unsigned char mcastbuf[TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE];
DWORD bytesReturned = 0;
if (DeviceIoControl(t,TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS,(LPVOID)0,0,(LPVOID)mcastbuf,sizeof(mcastbuf),&bytesReturned,NULL)) {
- MAC mac;
- DWORD i = 0;
- while ((i + 6) <= bytesReturned) {
- mac.setTo(mcastbuf + i,6);
- i += 6;
- if ((mac.isMulticast())&&(!mac.isBroadcast())) {
- // exclude the nulls that may be returned or any other junk Windows puts in there
- newGroups.push_back(MulticastGroup(mac,0));
+ if ((bytesReturned > 0)&&(bytesReturned <= TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE)) { // sanity check
+ MAC mac;
+ DWORD i = 0;
+ while ((i + 6) <= bytesReturned) {
+ mac.setTo(mcastbuf + i,6);
+ i += 6;
+ if ((mac.isMulticast())&&(!mac.isBroadcast())) {
+ // exclude the nulls that may be returned or any other junk Windows puts in there
+ newGroups.push_back(MulticastGroup(mac,0));
+ }
}
}
}
@@ -842,7 +847,7 @@ void WindowsEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,
newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
std::sort(newGroups.begin(),newGroups.end());
- std::unique(newGroups.begin(),newGroups.end());
+ newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
@@ -869,18 +874,19 @@ void WindowsEthernetTap::threadMain()
try {
while (_run) {
// Because Windows
+ Sleep(250);
setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
- Sleep(500);
+ Sleep(250);
setPersistentTapDeviceState(_deviceInstanceId.c_str(),true);
- Sleep(500);
+ Sleep(250);
setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
- Sleep(500);
+ Sleep(250);
setPersistentTapDeviceState(_deviceInstanceId.c_str(),true);
- Sleep(500);
+ Sleep(250);
_tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
if (_tap == INVALID_HANDLE_VALUE) {
- Sleep(1000);
+ Sleep(250);
continue;
}
@@ -948,7 +954,7 @@ void WindowsEthernetTap::threadMain()
ipnr.ReachabilityTime.LastUnreachable = 1;
DWORD result = CreateIpNetEntry2(&ipnr);
if (result != NO_ERROR)
- Sleep(500);
+ Sleep(250);
else break;
}
for(int i=0;i<8;++i) {
@@ -963,7 +969,7 @@ void WindowsEthernetTap::threadMain()
nr.Protocol = MIB_IPPROTO_NETMGMT;
DWORD result = CreateIpForwardEntry2(&nr);
if (result != NO_ERROR)
- Sleep(500);
+ Sleep(250);
else break;
}
}
@@ -1021,8 +1027,10 @@ void WindowsEthernetTap::threadMain()
}
}
- if ((waitResult == WAIT_TIMEOUT)||(waitResult == WAIT_FAILED))
+ if ((waitResult == WAIT_TIMEOUT)||(waitResult == WAIT_FAILED)) {
+ Sleep(250); // guard against spinning under some conditions
continue;
+ }
if (HasOverlappedIoCompleted(&tapOvlRead)) {
DWORD bytesRead = 0;
@@ -1075,11 +1083,13 @@ NET_IFINDEX WindowsEthernetTap::_getDeviceIndex()
if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
throw std::runtime_error("GetIfTable2Ex() failed");
- for(ULONG i=0;i<ift->NumEntries;++i) {
- if (ift->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
- NET_IFINDEX idx = ift->Table[i].InterfaceIndex;
- FreeMibTable(ift);
- return idx;
+ if (ift->NumEntries > 0) {
+ for(ULONG i=0;i<ift->NumEntries;++i) {
+ if (ift->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
+ NET_IFINDEX idx = ift->Table[i].InterfaceIndex;
+ FreeMibTable(ift);
+ return idx;
+ }
}
}
diff --git a/selftest.cpp b/selftest.cpp
index 9870c16a..468299c8 100644
--- a/selftest.cpp
+++ b/selftest.cpp
@@ -804,7 +804,7 @@ struct TestPhyHandlers;
static Phy<TestPhyHandlers *> *testPhyInstance = (Phy<TestPhyHandlers *> *)0;
struct TestPhyHandlers
{
- inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
+ inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
{
++phyTestUdpPacketCount;
}
@@ -852,7 +852,7 @@ struct TestPhyHandlers
inline void phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN) {}
inline void phyOnUnixClose(PhySocket *sock,void **uptr) {}
inline void phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len) {}
- inline void phyOnUnixWritable(PhySocket *sock,void **uptr) {}
+ inline void phyOnUnixWritable(PhySocket *sock,void **uptr,bool b) {}
#endif // __UNIX_LIKE__
inline void phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable) {}
diff --git a/service/OneService.cpp b/service/OneService.cpp
index 593f58aa..01828ffe 100644
--- a/service/OneService.cpp
+++ b/service/OneService.cpp
@@ -46,6 +46,7 @@
#include "../osdep/Http.hpp"
#include "../osdep/BackgroundResolver.hpp"
#include "../osdep/PortMapper.hpp"
+#include "../osdep/Binder.hpp"
#include "OneService.hpp"
#include "ControlPlane.hpp"
@@ -114,8 +115,9 @@ namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
#define ZT_MAX_HTTP_MESSAGE_SIZE (1024 * 1024 * 64)
#define ZT_MAX_HTTP_CONNECTIONS 64
-// Interface metric for ZeroTier taps
-#define ZT_IF_METRIC 32768
+// Interface metric for ZeroTier taps -- this ensures that if we are on WiFi and also
+// bridged via ZeroTier to the same LAN traffic will (if the OS is sane) prefer WiFi.
+#define ZT_IF_METRIC 5000
// How often to check for new multicast subscriptions on a tap device
#define ZT_TAP_CHECK_MULTICAST_INTERVAL 5000
@@ -134,7 +136,7 @@ namespace ZeroTier { typedef BSDEthernetTap EthernetTap; }
#define ZT_TCP_FALLBACK_AFTER 60000
// How often to check for local interface addresses
-#define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 300000
+#define ZT_LOCAL_INTERFACE_CHECK_INTERVAL 60000
namespace ZeroTier {
@@ -149,6 +151,7 @@ public:
bool isValidSigningIdentity(const Identity &id)
{
return (
+ /* 0001 - 0004 : obsolete, used in old versions */
/* 0005 */ (id == Identity("ba57ea350e:0:9d4be6d7f86c5660d5ee1951a3d759aa6e12a84fc0c0b74639500f1dbc1a8c566622e7d1c531967ebceb1e9d1761342f88324a8ba520c93c35f92f35080fa23f"))
/* 0006 */ ||(id == Identity("5067b21b83:0:8af477730f5055c48135b84bed6720a35bca4c0e34be4060a4c636288b1ec22217eb22709d610c66ed464c643130c51411bbb0294eef12fbe8ecc1a1e2c63a7a"))
/* 0007 */ ||(id == Identity("4f5e97a8f1:0:57880d056d7baeb04bbc057d6f16e6cb41388570e87f01492fce882485f65a798648595610a3ad49885604e7fb1db2dd3c2c534b75e42c3c0b110ad07b4bb138"))
@@ -444,18 +447,90 @@ struct TcpConnection
Mutex writeBuf_m;
};
-// Use a bigger buffer on AMD64 since these are likely to be bigger and
-// servers. Otherwise use a smaller buffer. This makes no difference
-// except under very high load.
-#if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__))
-#define ZT_UDP_DESIRED_BUF_SIZE 1048576
-#else
-#define ZT_UDP_DESIRED_BUF_SIZE 131072
-#endif
+// Used to pseudo-randomize local source port picking
+static volatile unsigned int _udpPortPickerCounter = 0;
class OneServiceImpl : public OneService
{
public:
+ // begin member variables --------------------------------------------------
+
+ const std::string _homePath;
+ BackgroundResolver _tcpFallbackResolver;
+#ifdef ZT_ENABLE_NETWORK_CONTROLLER
+ SqliteNetworkController *_controller;
+#endif
+ Phy<OneServiceImpl *> _phy;
+ Node *_node;
+
+ /*
+ * To properly handle NAT/gateway craziness we use three local UDP ports:
+ *
+ * [0] is the normal/default port, usually 9993
+ * [1] is a port dervied from our ZeroTier address
+ * [2] is a port computed from the normal/default for use with uPnP/NAT-PMP mappings
+ *
+ * [2] exists because on some gateways trying to do regular NAT-t interferes
+ * destructively with uPnP port mapping behavior in very weird buggy ways.
+ * It's only used if uPnP/NAT-PMP is enabled in this build.
+ */
+
+ Binder _bindings[3];
+ unsigned int _ports[3];
+ uint16_t _portsBE[3]; // ports in big-endian network byte order as in sockaddr
+
+ // Sockets for JSON API -- bound only to V4 and V6 localhost
+ PhySocket *_v4TcpControlSocket;
+ PhySocket *_v6TcpControlSocket;
+
+ // JSON API handler
+ ControlPlane *_controlPlane;
+
+ // Time we last received a packet from a global address
+ uint64_t _lastDirectReceiveFromGlobal;
+#ifdef ZT_TCP_FALLBACK_RELAY
+ uint64_t _lastSendToGlobalV4;
+#endif
+
+ // Last potential sleep/wake event
+ uint64_t _lastRestart;
+
+ // Deadline for the next background task service function
+ volatile uint64_t _nextBackgroundTaskDeadline;
+
+ // Tap devices by network ID
+ std::map< uint64_t,EthernetTap * > _taps;
+ std::map< uint64_t,std::vector<InetAddress> > _tapAssignedIps; // ZeroTier assigned IPs, not user or dhcp assigned
+ Mutex _taps_m;
+
+ // Active TCP/IP connections
+ std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
+ TcpConnection *_tcpFallbackTunnel;
+
+ // Termination status information
+ ReasonForTermination _termReason;
+ std::string _fatalErrorMessage;
+ Mutex _termReason_m;
+
+ // uPnP/NAT-PMP port mapper if enabled
+#ifdef ZT_USE_MINIUPNPC
+ PortMapper *_portMapper;
+#endif
+
+ // Cluster management instance if enabled
+#ifdef ZT_ENABLE_CLUSTER
+ PhySocket *_clusterMessageSocket;
+ ClusterGeoIpService *_clusterGeoIpService;
+ ClusterDefinition *_clusterDefinition;
+ unsigned int _clusterMemberId;
+#endif
+
+ // Set to false to force service to stop
+ volatile bool _run;
+ Mutex _run_m;
+
+ // end member variables ----------------------------------------------------
+
OneServiceImpl(const char *hp,unsigned int port) :
_homePath((hp) ? hp : ".")
,_tcpFallbackResolver(ZT_TCP_FALLBACK_RELAY)
@@ -466,14 +541,14 @@ public:
,_node((Node *)0)
,_controlPlane((ControlPlane *)0)
,_lastDirectReceiveFromGlobal(0)
- ,_lastSendToGlobal(0)
+#ifdef ZT_TCP_FALLBACK_RELAY
+ ,_lastSendToGlobalV4(0)
+#endif
,_lastRestart(0)
,_nextBackgroundTaskDeadline(0)
,_tcpFallbackTunnel((TcpConnection *)0)
,_termReason(ONE_STILL_RUNNING)
- ,_port(0)
#ifdef ZT_USE_MINIUPNPC
- ,_v4UpnpUdpSocket((PhySocket *)0)
,_portMapper((PortMapper *)0)
#endif
#ifdef ZT_ENABLE_CLUSTER
@@ -484,65 +559,74 @@ public:
#endif
,_run(true)
{
+ _ports[0] = 0;
+ _ports[1] = 0;
+ _ports[2] = 0;
+
+ // The control socket is bound to the default/static port on localhost. If we
+ // can do this, we have successfully allocated a port. The binders will take
+ // care of binding non-local addresses for ZeroTier traffic.
const int portTrials = (port == 0) ? 256 : 1; // if port is 0, pick random
for(int k=0;k<portTrials;++k) {
if (port == 0) {
unsigned int randp = 0;
Utils::getSecureRandom(&randp,sizeof(randp));
- port = 40000 + (randp % 25500);
+ port = 20000 + (randp % 45500);
}
- _v4LocalAddress = InetAddress((uint32_t)0,port);
- _v4UdpSocket = _phy.udpBind((const struct sockaddr *)&_v4LocalAddress,reinterpret_cast<void *>(&_v4LocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
-
- if (_v4UdpSocket) {
+ if (_trialBind(port)) {
struct sockaddr_in in4;
memset(&in4,0,sizeof(in4));
in4.sin_family = AF_INET;
- in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @localhost
+ in4.sin_addr.s_addr = Utils::hton((uint32_t)0x7f000001); // right now we just listen for TCP @127.0.0.1
in4.sin_port = Utils::hton((uint16_t)port);
- _v4TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
-
- if (_v4TcpListenSocket) {
- _v6LocalAddress = InetAddress("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,port);
- _v6UdpSocket = _phy.udpBind((const struct sockaddr *)&_v6LocalAddress,reinterpret_cast<void *>(&_v6LocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
-
- struct sockaddr_in6 in6;
- memset((void *)&in6,0,sizeof(in6));
- in6.sin6_family = AF_INET6;
- in6.sin6_port = in4.sin_port;
- in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
- _v6TcpListenSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
-
- _port = port;
- break; // success!
+ _v4TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in4,this);
+
+ struct sockaddr_in6 in6;
+ memset((void *)&in6,0,sizeof(in6));
+ in6.sin6_family = AF_INET6;
+ in6.sin6_port = in4.sin_port;
+ in6.sin6_addr.s6_addr[15] = 1; // IPv6 localhost == ::1
+ _v6TcpControlSocket = _phy.tcpListen((const struct sockaddr *)&in6,this);
+
+ // We must bind one of IPv4 or IPv6 -- support either failing to support hosts that
+ // have only IPv4 or only IPv6 stacks.
+ if ((_v4TcpControlSocket)||(_v6TcpControlSocket)) {
+ _ports[0] = port;
+ break;
} else {
- _phy.close(_v4UdpSocket,false);
+ if (_v4TcpControlSocket)
+ _phy.close(_v4TcpControlSocket,false);
+ if (_v6TcpControlSocket)
+ _phy.close(_v6TcpControlSocket,false);
+ port = 0;
}
+ } else {
+ port = 0;
}
-
- port = 0;
}
- if (_port == 0)
- throw std::runtime_error("cannot bind to port");
+ if (_ports[0] == 0)
+ throw std::runtime_error("cannot bind to local control interface port");
char portstr[64];
- Utils::snprintf(portstr,sizeof(portstr),"%u",_port);
+ Utils::snprintf(portstr,sizeof(portstr),"%u",_ports[0]);
OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),std::string(portstr));
}
virtual ~OneServiceImpl()
{
- _phy.close(_v4UdpSocket);
- _phy.close(_v6UdpSocket);
- _phy.close(_v4TcpListenSocket);
- _phy.close(_v6TcpListenSocket);
+ for(int i=0;i<3;++i)
+ _bindings[i].closeAll(_phy);
+
+ _phy.close(_v4TcpControlSocket);
+ _phy.close(_v6TcpControlSocket);
+
#ifdef ZT_ENABLE_CLUSTER
_phy.close(_clusterMessageSocket);
#endif
+
#ifdef ZT_USE_MINIUPNPC
- _phy.close(_v4UpnpUdpSocket);
delete _portMapper;
#endif
#ifdef ZT_ENABLE_NETWORK_CONTROLLER
@@ -571,7 +655,9 @@ public:
_termReason = ONE_UNRECOVERABLE_ERROR;
_fatalErrorMessage = "authtoken.secret could not be written";
return _termReason;
- } else OSUtils::lockDownFile(authTokenPath.c_str(),false);
+ } else {
+ OSUtils::lockDownFile(authTokenPath.c_str(),false);
+ }
}
}
authToken = _trimString(authToken);
@@ -587,24 +673,49 @@ public:
SnodePathCheckFunction,
SnodeEventCallback);
-#ifdef ZT_USE_MINIUPNPC
- // Bind a secondary port for use with uPnP, since some NAT routers
- // (cough Ubiquity Edge cough) barf up a lung if you do both conventional
- // NAT-t and uPnP from behind the same port. I think this is a bug, but
- // everyone else's router bugs are our problem. :P
- for(int k=0;k<512;++k) {
- unsigned int mapperPort = 40000 + (((_port + 1) * (k + 1)) % 25500);
- char uniqueName[64];
- _v4UpnpLocalAddress = InetAddress(0,mapperPort);
- _v4UpnpUdpSocket = _phy.udpBind((const struct sockaddr *)&_v4UpnpLocalAddress,reinterpret_cast<void *>(&_v4UpnpLocalAddress),ZT_UDP_DESIRED_BUF_SIZE);
- if (_v4UpnpUdpSocket) {
- Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx",_node->address());
- _portMapper = new PortMapper(mapperPort,uniqueName);
+ // Attempt to bind to a secondary port chosen from our ZeroTier address.
+ // This exists because there are buggy NATs out there that fail if more
+ // than one device behind the same NAT tries to use the same internal
+ // private address port number.
+ _ports[1] = 20000 + ((unsigned int)_node->address() % 45500);
+ for(int i=0;;++i) {
+ if (i > 1000) {
+ _ports[1] = 0;
break;
+ } else if (++_ports[1] >= 65536) {
+ _ports[1] = 20000;
+ }
+ if (_trialBind(_ports[1]))
+ break;
+ }
+
+#ifdef ZT_USE_MINIUPNPC
+ // If we're running uPnP/NAT-PMP, bind a *third* port for that. We can't
+ // use the other two ports for that because some NATs do really funky
+ // stuff with ports that are explicitly mapped that breaks things.
+ if (_ports[1]) {
+ _ports[2] = _ports[1];
+ for(int i=0;;++i) {
+ if (i > 1000) {
+ _ports[2] = 0;
+ break;
+ } else if (++_ports[2] >= 65536) {
+ _ports[2] = 20000;
+ }
+ if (_trialBind(_ports[2]))
+ break;
+ }
+ if (_ports[2]) {
+ char uniqueName[64];
+ Utils::snprintf(uniqueName,sizeof(uniqueName),"ZeroTier/%.10llx@%u",_node->address(),_ports[2]);
+ _portMapper = new PortMapper(_ports[2],uniqueName);
}
}
#endif
+ for(int i=0;i<3;++i)
+ _portsBE[i] = Utils::hton((uint16_t)_ports[i]);
+
#ifdef ZT_ENABLE_NETWORK_CONTROLLER
_controller = new SqliteNetworkController(_node,(_homePath + ZT_PATH_SEPARATOR_S + ZT_CONTROLLER_DB_PATH).c_str(),(_homePath + ZT_PATH_SEPARATOR_S + "circuitTestResults.d").c_str());
_node->setNetconfMaster((void *)_controller);
@@ -699,6 +810,7 @@ public:
_lastRestart = clockShouldBe;
uint64_t lastTapMulticastGroupCheck = 0;
uint64_t lastTcpFallbackResolve = 0;
+ uint64_t lastBindRefresh = 0;
uint64_t lastLocalInterfaceAddressCheck = (OSUtils::now() - ZT_LOCAL_INTERFACE_CHECK_INTERVAL) + 15000; // do this in 15s to give portmapper time to configure and other things time to settle
#ifdef ZT_AUTO_UPDATE
uint64_t lastSoftwareUpdateCheck = 0;
@@ -711,9 +823,28 @@ public:
_termReason = ONE_NORMAL_TERMINATION;
_termReason_m.unlock();
break;
- } else _run_m.unlock();
+ } else {
+ _run_m.unlock();
+ }
+
+ const uint64_t now = OSUtils::now();
- uint64_t now = OSUtils::now();
+ // Attempt to detect sleep/wake events by detecting delay overruns
+ bool restarted = false;
+ if ((now > clockShouldBe)&&((now - clockShouldBe) > 10000)) {
+ _lastRestart = now;
+ restarted = true;
+ }
+
+ // Refresh bindings in case device's interfaces have changed
+ if (((now - lastBindRefresh) >= ZT_BINDER_REFRESH_PERIOD)||(restarted)) {
+ lastBindRefresh = now;
+ for(int i=0;i<3;++i) {
+ if (_ports[i]) {
+ _bindings[i].refresh(_phy,_ports[i],*this);
+ }
+ }
+ }
uint64_t dl = _nextBackgroundTaskDeadline;
if (dl <= now) {
@@ -721,10 +852,6 @@ public:
dl = _nextBackgroundTaskDeadline;
}
- // Attempt to detect sleep/wake events by detecting delay overruns
- if ((now > clockShouldBe)&&((now - clockShouldBe) > 2000))
- _lastRestart = now;
-
#ifdef ZT_AUTO_UPDATE
if ((now - lastSoftwareUpdateCheck) >= ZT_AUTO_UPDATE_CHECK_PERIOD) {
lastSoftwareUpdateCheck = now;
@@ -756,76 +883,19 @@ public:
if ((now - lastLocalInterfaceAddressCheck) >= ZT_LOCAL_INTERFACE_CHECK_INTERVAL) {
lastLocalInterfaceAddressCheck = now;
- _node->clearLocalInterfaceAddresses();
-#ifdef ZT_USE_MINIUPNPC
- std::vector<InetAddress> mappedAddresses(_portMapper->get());
- for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
- _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
-#endif
+ _node->clearLocalInterfaceAddresses();
-#ifdef __UNIX_LIKE__
- std::vector<std::string> ztDevices;
- {
- Mutex::Lock _l(_taps_m);
- for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
- ztDevices.push_back(t->second->deviceName());
- }
- struct ifaddrs *ifatbl = (struct ifaddrs *)0;
- if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
- struct ifaddrs *ifa = ifatbl;
- while (ifa) {
- if ((ifa->ifa_name)&&(ifa->ifa_addr)&&(!isBlacklistedLocalInterfaceForZeroTierTraffic(ifa->ifa_name))) {
- bool isZT = false;
- for(std::vector<std::string>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
- if (*d == ifa->ifa_name) {
- isZT = true;
- break;
- }
- }
- if (!isZT) {
- InetAddress ip(ifa->ifa_addr);
- ip.setPort(_port);
- _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip));
- }
- }
- ifa = ifa->ifa_next;
- }
- freeifaddrs(ifatbl);
+#ifdef ZT_USE_MINIUPNPC
+ if (_portMapper) {
+ std::vector<InetAddress> mappedAddresses(_portMapper->get());
+ for(std::vector<InetAddress>::const_iterator ext(mappedAddresses.begin());ext!=mappedAddresses.end();++ext)
+ _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*ext)));
}
-#endif // __UNIX_LIKE__
+#endif
-#ifdef __WINDOWS__
- std::vector<NET_LUID> ztDevices;
- {
- Mutex::Lock _l(_taps_m);
- for(std::map< uint64_t,EthernetTap *>::const_iterator t(_taps.begin());t!=_taps.end();++t)
- ztDevices.push_back(t->second->luid());
- }
- char aabuf[16384];
- ULONG aalen = sizeof(aabuf);
- if (GetAdaptersAddresses(AF_UNSPEC,GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER,(void *)0,reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf),&aalen) == NO_ERROR) {
- PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
- while (a) {
- bool isZT = false;
- for(std::vector<NET_LUID>::const_iterator d(ztDevices.begin());d!=ztDevices.end();++d) {
- if (a->Luid.Value == d->Value) {
- isZT = true;
- break;
- }
- }
- if (!isZT) {
- PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
- while (ua) {
- InetAddress ip(ua->Address.lpSockaddr);
- ip.setPort(_port);
- _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&ip));
- ua = ua->Next;
- }
- }
- a = a->Next;
- }
- }
-#endif // __WINDOWS__
+ std::vector<InetAddress> boundAddrs(_bindings[0].allBoundLocalInterfaceAddresses());
+ for(std::vector<InetAddress>::const_iterator i(boundAddrs.begin());i!=boundAddrs.end();++i)
+ _node->addLocalInterfaceAddress(reinterpret_cast<const struct sockaddr_storage *>(&(*i)));
}
const unsigned long delay = (dl > now) ? (unsigned long)(dl - now) : 100;
@@ -898,7 +968,7 @@ public:
// Begin private implementation methods
- inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
+ inline void phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
{
#ifdef ZT_ENABLE_CLUSTER
if (sock == _clusterMessageSocket) {
@@ -915,9 +985,10 @@ public:
if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(from)->ipScope() == InetAddress::IP_SCOPE_GLOBAL))
_lastDirectReceiveFromGlobal = OSUtils::now();
- ZT_ResultCode rc = _node->processWirePacket(
+
+ const ZT_ResultCode rc = _node->processWirePacket(
OSUtils::now(),
- reinterpret_cast<const struct sockaddr_storage *>(*uptr),
+ reinterpret_cast<const struct sockaddr_storage *>(localAddr),
(const struct sockaddr_storage *)from, // Phy<> uses sockaddr_storage, so it'll always be that big
data,
len,
@@ -970,28 +1041,32 @@ public:
inline void phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
{
- // Incoming TCP connections are HTTP JSON API requests.
-
- TcpConnection *tc = new TcpConnection();
- _tcpConnections.insert(tc);
-
- tc->type = TcpConnection::TCP_HTTP_INCOMING;
- tc->shouldKeepAlive = true;
- tc->parent = this;
- tc->sock = sockN;
- tc->from = from;
- http_parser_init(&(tc->parser),HTTP_REQUEST);
- tc->parser.data = (void *)tc;
- tc->messageSize = 0;
- tc->lastActivity = OSUtils::now();
- tc->currentHeaderField = "";
- tc->currentHeaderValue = "";
- tc->url = "";
- tc->status = "";
- tc->headers.clear();
- tc->body = "";
- tc->writeBuf = "";
- *uptrN = (void *)tc;
+ if ((!from)||(reinterpret_cast<const InetAddress *>(from)->ipScope() != InetAddress::IP_SCOPE_LOOPBACK)) {
+ // Non-Loopback: deny (for now)
+ _phy.close(sockN,false);
+ return;
+ } else {
+ // Loopback == HTTP JSON API request
+ TcpConnection *tc = new TcpConnection();
+ _tcpConnections.insert(tc);
+ tc->type = TcpConnection::TCP_HTTP_INCOMING;
+ tc->shouldKeepAlive = true;
+ tc->parent = this;
+ tc->sock = sockN;
+ tc->from = from;
+ http_parser_init(&(tc->parser),HTTP_REQUEST);
+ tc->parser.data = (void *)tc;
+ tc->messageSize = 0;
+ tc->lastActivity = OSUtils::now();
+ tc->currentHeaderField = "";
+ tc->currentHeaderValue = "";
+ tc->url = "";
+ tc->status = "";
+ tc->headers.clear();
+ tc->body = "";
+ tc->writeBuf = "";
+ *uptrN = (void *)tc;
+ }
}
inline void phyOnTcpClose(PhySocket *sock,void **uptr)
@@ -1064,9 +1139,10 @@ public:
}
if (from) {
- ZT_ResultCode rc = _node->processWirePacket(
+ InetAddress fakeTcpLocalInterfaceAddress((uint32_t)0xffffffff,0xffff);
+ const ZT_ResultCode rc = _node->processWirePacket(
OSUtils::now(),
- &ZT_SOCKADDR_NULL,
+ reinterpret_cast<struct sockaddr_storage *>(&fakeTcpLocalInterfaceAddress),
reinterpret_cast<struct sockaddr_storage *>(&from),
data,
plen,
@@ -1281,103 +1357,79 @@ public:
inline int nodeWirePacketSendFunction(const struct sockaddr_storage *localAddr,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
{
-#ifdef ZT_USE_MINIUPNPC
- if ((localAddr->ss_family == AF_INET)&&(reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == reinterpret_cast<const struct sockaddr_in *>(&_v4UpnpLocalAddress)->sin_port)) {
-#ifdef ZT_BREAK_UDP
- if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
-#endif
- if (addr->ss_family == AF_INET) {
- if (ttl)
- _phy.setIp4UdpTtl(_v4UpnpUdpSocket,ttl);
- const int result = ((_phy.udpSend(_v4UpnpUdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
- if (ttl)
- _phy.setIp4UdpTtl(_v4UpnpUdpSocket,255);
- return result;
- } else {
- return -1;
- }
-#ifdef ZT_BREAK_UDP
+ unsigned int fromBindingNo = 0;
+
+ if (addr->ss_family == AF_INET) {
+ if (reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port == 0) {
+ // If sender is sending from wildcard (null address), choose the secondary backup
+ // port 1/4 of the time. (but only for IPv4)
+ fromBindingNo = (++_udpPortPickerCounter & 0x4) >> 2;
+ if (!_ports[fromBindingNo])
+ fromBindingNo = 0;
+ } else {
+ const uint16_t lp = reinterpret_cast<const struct sockaddr_in *>(localAddr)->sin_port;
+ if (lp == _portsBE[1])
+ fromBindingNo = 1;
+ else if (lp == _portsBE[2])
+ fromBindingNo = 2;
}
-#endif
- }
-#endif // ZT_USE_MINIUPNPC
-
- int result = -1;
- switch(addr->ss_family) {
- case AF_INET:
-#ifdef ZT_BREAK_UDP
- if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
-#endif
- if (_v4UdpSocket) {
- if (ttl)
- _phy.setIp4UdpTtl(_v4UdpSocket,ttl);
- result = ((_phy.udpSend(_v4UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
- if (ttl)
- _phy.setIp4UdpTtl(_v4UdpSocket,255);
- }
-#ifdef ZT_BREAK_UDP
- }
-#endif
#ifdef ZT_TCP_FALLBACK_RELAY
- // TCP fallback tunnel support
- if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
- uint64_t now = OSUtils::now();
-
- // Engage TCP tunnel fallback if we haven't received anything valid from a global
- // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
- // valid direct traffic we'll stop using it and close the socket after a while.
- if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
- if (_tcpFallbackTunnel) {
- Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
- if (!_tcpFallbackTunnel->writeBuf.length())
- _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
- unsigned long mlen = len + 7;
- _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
- _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
- _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
- _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
- _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
- _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
- _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
- _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
- _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
- result = 0;
- } else if (((now - _lastSendToGlobal) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobal) > (ZT_PING_CHECK_INVERVAL / 2))) {
- std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
- if (tunnelIps.empty()) {
- if (!_tcpFallbackResolver.running())
- _tcpFallbackResolver.resolveNow();
- } else {
- bool connected = false;
- InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
- addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
- _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
- }
+ // TCP fallback tunnel support, currently IPv4 only
+ if ((len >= 16)&&(reinterpret_cast<const InetAddress *>(addr)->ipScope() == InetAddress::IP_SCOPE_GLOBAL)) {
+ // Engage TCP tunnel fallback if we haven't received anything valid from a global
+ // IP address in ZT_TCP_FALLBACK_AFTER milliseconds. If we do start getting
+ // valid direct traffic we'll stop using it and close the socket after a while.
+ const uint64_t now = OSUtils::now();
+ if (((now - _lastDirectReceiveFromGlobal) > ZT_TCP_FALLBACK_AFTER)&&((now - _lastRestart) > ZT_TCP_FALLBACK_AFTER)) {
+ if (_tcpFallbackTunnel) {
+ Mutex::Lock _l(_tcpFallbackTunnel->writeBuf_m);
+ if (!_tcpFallbackTunnel->writeBuf.length())
+ _phy.setNotifyWritable(_tcpFallbackTunnel->sock,true);
+ unsigned long mlen = len + 7;
+ _tcpFallbackTunnel->writeBuf.push_back((char)0x17);
+ _tcpFallbackTunnel->writeBuf.push_back((char)0x03);
+ _tcpFallbackTunnel->writeBuf.push_back((char)0x03); // fake TLS 1.2 header
+ _tcpFallbackTunnel->writeBuf.push_back((char)((mlen >> 8) & 0xff));
+ _tcpFallbackTunnel->writeBuf.push_back((char)(mlen & 0xff));
+ _tcpFallbackTunnel->writeBuf.push_back((char)4); // IPv4
+ _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_addr.s_addr))),4);
+ _tcpFallbackTunnel->writeBuf.append(reinterpret_cast<const char *>(reinterpret_cast<const void *>(&(reinterpret_cast<const struct sockaddr_in *>(addr)->sin_port))),2);
+ _tcpFallbackTunnel->writeBuf.append((const char *)data,len);
+ } else if (((now - _lastSendToGlobalV4) < ZT_TCP_FALLBACK_AFTER)&&((now - _lastSendToGlobalV4) > (ZT_PING_CHECK_INVERVAL / 2))) {
+ std::vector<InetAddress> tunnelIps(_tcpFallbackResolver.get());
+ if (tunnelIps.empty()) {
+ if (!_tcpFallbackResolver.running())
+ _tcpFallbackResolver.resolveNow();
+ } else {
+ bool connected = false;
+ InetAddress addr(tunnelIps[(unsigned long)now % tunnelIps.size()]);
+ addr.setPort(ZT_TCP_FALLBACK_RELAY_PORT);
+ _phy.tcpConnect(reinterpret_cast<const struct sockaddr *>(&addr),connected);
}
}
-
- _lastSendToGlobal = now;
}
+ _lastSendToGlobalV4 = now;
+ }
#endif // ZT_TCP_FALLBACK_RELAY
+ } else if (addr->ss_family == AF_INET6) {
+ if (reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port != 0) {
+ const uint16_t lp = reinterpret_cast<const struct sockaddr_in6 *>(localAddr)->sin6_port;
+ if (lp == _portsBE[1])
+ fromBindingNo = 1;
+ else if (lp == _portsBE[2])
+ fromBindingNo = 2;
+ }
+ } else {
+ return -1;
+ }
- break;
-
- case AF_INET6:
-#ifdef ZT_BREAK_UDP
- if (!OSUtils::fileExists("/tmp/ZT_BREAK_UDP")) {
-#endif
- if (_v6UdpSocket)
- result = ((_phy.udpSend(_v6UdpSocket,(const struct sockaddr *)addr,data,len) != 0) ? 0 : -1);
#ifdef ZT_BREAK_UDP
- }
+ if (OSUtils::fileExists("/tmp/ZT_BREAK_UDP"))
+ return 0; // silently break UDP
#endif
- break;
- default:
- return -1;
- }
- return result;
+ return (_bindings[fromBindingNo].udpSend(_phy,*(reinterpret_cast<const InetAddress *>(localAddr)),*(reinterpret_cast<const InetAddress *>(addr)),data,len,ttl)) ? 0 : -1;
}
inline void nodeVirtualNetworkFrameFunction(uint64_t nwid,void **nuptr,uint64_t sourceMac,uint64_t destMac,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len)
@@ -1461,6 +1513,25 @@ public:
_phy.close(tc->sock); // will call close handler, which deletes from _tcpConnections
}
+ bool shouldBindInterface(const char *ifname,const InetAddress &ifaddr)
+ {
+ if (isBlacklistedLocalInterfaceForZeroTierTraffic(ifname))
+ return false;
+
+ Mutex::Lock _l(_taps_m);
+ for(std::map< uint64_t,EthernetTap * >::const_iterator t(_taps.begin());t!=_taps.end();++t) {
+ if (t->second) {
+ std::vector<InetAddress> ips(t->second->ips());
+ for(std::vector<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
+ if (i->ipsEqual(ifaddr))
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
std::string _dataStorePrepPath(const char *name) const
{
std::string p(_homePath);
@@ -1478,52 +1549,40 @@ public:
return p;
}
- const std::string _homePath;
- BackgroundResolver _tcpFallbackResolver;
-#ifdef ZT_ENABLE_NETWORK_CONTROLLER
- SqliteNetworkController *_controller;
-#endif
- Phy<OneServiceImpl *> _phy;
- Node *_node;
- InetAddress _v4LocalAddress,_v6LocalAddress;
- PhySocket *_v4UdpSocket;
- PhySocket *_v6UdpSocket;
- PhySocket *_v4TcpListenSocket;
- PhySocket *_v6TcpListenSocket;
- ControlPlane *_controlPlane;
- uint64_t _lastDirectReceiveFromGlobal;
- uint64_t _lastSendToGlobal;
- uint64_t _lastRestart;
- volatile uint64_t _nextBackgroundTaskDeadline;
-
- std::map< uint64_t,EthernetTap * > _taps;
- std::map< uint64_t,std::vector<InetAddress> > _tapAssignedIps; // ZeroTier assigned IPs, not user or dhcp assigned
- Mutex _taps_m;
-
- std::set< TcpConnection * > _tcpConnections; // no mutex for this since it's done in the main loop thread only
- TcpConnection *_tcpFallbackTunnel;
-
- ReasonForTermination _termReason;
- std::string _fatalErrorMessage;
- Mutex _termReason_m;
-
- unsigned int _port;
-
-#ifdef ZT_USE_MINIUPNPC
- InetAddress _v4UpnpLocalAddress;
- PhySocket *_v4UpnpUdpSocket;
- PortMapper *_portMapper;
-#endif
+ bool _trialBind(unsigned int port)
+ {
+ struct sockaddr_in in4;
+ struct sockaddr_in6 in6;
+ PhySocket *tb;
+
+ memset(&in4,0,sizeof(in4));
+ in4.sin_family = AF_INET;
+ in4.sin_port = Utils::hton((uint16_t)port);
+ tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0,0);
+ if (tb) {
+ _phy.close(tb,false);
+ tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in4),(void *)0);
+ if (tb) {
+ _phy.close(tb,false);
+ return true;
+ }
+ }
-#ifdef ZT_ENABLE_CLUSTER
- PhySocket *_clusterMessageSocket;
- ClusterGeoIpService *_clusterGeoIpService;
- ClusterDefinition *_clusterDefinition;
- unsigned int _clusterMemberId;
-#endif
+ memset(&in6,0,sizeof(in6));
+ in6.sin6_family = AF_INET6;
+ in6.sin6_port = Utils::hton((uint16_t)port);
+ tb = _phy.udpBind(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0,0);
+ if (tb) {
+ _phy.close(tb,false);
+ tb = _phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&in6),(void *)0);
+ if (tb) {
+ _phy.close(tb,false);
+ return true;
+ }
+ }
- bool _run;
- Mutex _run_m;
+ return false;
+ }
};
static int SnodeVirtualNetworkConfigFunction(ZT_Node *node,void *uptr,uint64_t nwid,void **nuptr,enum ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nwconf)
diff --git a/version.h b/version.h
index efff7cef..62045ed8 100644
--- a/version.h
+++ b/version.h
@@ -32,6 +32,6 @@
/**
* Revision
*/
-#define ZEROTIER_ONE_VERSION_REVISION 4
+#define ZEROTIER_ONE_VERSION_REVISION 5
#endif