From 7127d2b811c25b04feb13d1ac070df88614550aa Mon Sep 17 00:00:00 2001 From: Joseph Henry Date: Thu, 21 Jan 2016 15:10:26 -0800 Subject: [PATCH 01/45] Updated unit tests + README --- netcon/README.md | 10 ++++++---- netcon/docker-test/build_tests.sh | 2 +- .../monitor_dockerfile | 0 .../monitor_entrypoint.sh | 0 .../netcon_dockerfile | 2 +- .../netcon_entrypoint.sh | 0 6 files changed, 8 insertions(+), 6 deletions(-) rename netcon/docker-test/httpd/{httpd-2.4.17-3.fc23.x86_64 => httpd-2.4.18-1.fc23.x86_64}/monitor_dockerfile (100%) rename netcon/docker-test/httpd/{httpd-2.4.17-3.fc23.x86_64 => httpd-2.4.18-1.fc23.x86_64}/monitor_entrypoint.sh (100%) rename netcon/docker-test/httpd/{httpd-2.4.17-3.fc23.x86_64 => httpd-2.4.18-1.fc23.x86_64}/netcon_dockerfile (95%) rename netcon/docker-test/httpd/{httpd-2.4.17-3.fc23.x86_64 => httpd-2.4.18-1.fc23.x86_64}/netcon_entrypoint.sh (100%) diff --git a/netcon/README.md b/netcon/README.md index 413efc2b4..d694064ae 100644 --- a/netcon/README.md +++ b/netcon/README.md @@ -154,9 +154,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) Generate two pairs of identity keys. Each public/private pair will be used by the *netcon* and *monitor* containers: +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: + +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 +178,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 +187,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/docker-test/build_tests.sh b/netcon/docker-test/build_tests.sh index f360124b6..65009f18d 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/httpd/httpd-2.4.18-1.fc23.x86_64/monitor_dockerfile similarity index 100% rename from netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/monitor_dockerfile rename to netcon/docker-test/httpd/httpd-2.4.18-1.fc23.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/httpd/httpd-2.4.18-1.fc23.x86_64/monitor_entrypoint.sh similarity index 100% rename from netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/monitor_entrypoint.sh rename to netcon/docker-test/httpd/httpd-2.4.18-1.fc23.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/httpd/httpd-2.4.18-1.fc23.x86_64/netcon_dockerfile similarity index 95% rename from netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/netcon_dockerfile rename to netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/netcon_dockerfile index 90739f108..3053a832f 100644 --- a/netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/netcon_dockerfile +++ b/netcon/docker-test/httpd/httpd-2.4.18-1.fc23.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 httpd-2.4.18-1.fc23.x86_64 RUN yum clean all EXPOSE 9993/udp 80/udp 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 similarity index 100% rename from netcon/docker-test/httpd/httpd-2.4.17-3.fc23.x86_64/netcon_entrypoint.sh rename to netcon/docker-test/httpd/httpd-2.4.18-1.fc23.x86_64/netcon_entrypoint.sh From bccd60125b5bf51a038bbd7951fb68bbc28df99f Mon Sep 17 00:00:00 2001 From: Joseph Henry Date: Thu, 21 Jan 2016 15:52:54 -0800 Subject: [PATCH 02/45] Added python, python3, darkhttpd unit tests --- .../darkhttpd-1.11.x86_64/monitor_dockerfile | 24 ++++++ .../monitor_entrypoint.sh | 80 +++++++++++++++++++ .../darkhttpd-1.11.x86_64/netcon_dockerfile | 38 +++++++++ .../netcon_entrypoint.sh | 46 +++++++++++ .../python/python/monitor_dockerfile | 24 ++++++ .../python/python/monitor_entrypoint.sh | 80 +++++++++++++++++++ .../python/python/netcon_dockerfile | 38 +++++++++ .../python/python/netcon_entrypoint.sh | 46 +++++++++++ .../python/python3/monitor_dockerfile | 24 ++++++ .../python/python3/monitor_entrypoint.sh | 80 +++++++++++++++++++ .../python/python3/netcon_dockerfile | 37 +++++++++ .../python/python3/netcon_entrypoint.sh | 46 +++++++++++ 12 files changed, 563 insertions(+) create mode 100644 netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_dockerfile create mode 100644 netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_entrypoint.sh create mode 100644 netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/netcon_dockerfile create mode 100644 netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/netcon_entrypoint.sh create mode 100644 netcon/docker-test/python/python/monitor_dockerfile create mode 100644 netcon/docker-test/python/python/monitor_entrypoint.sh create mode 100644 netcon/docker-test/python/python/netcon_dockerfile create mode 100644 netcon/docker-test/python/python/netcon_entrypoint.sh create mode 100644 netcon/docker-test/python/python3/monitor_dockerfile create mode 100644 netcon/docker-test/python/python3/monitor_entrypoint.sh create mode 100644 netcon/docker-test/python/python3/netcon_dockerfile create mode 100644 netcon/docker-test/python/python3/netcon_entrypoint.sh diff --git a/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_dockerfile b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_dockerfile new file mode 100644 index 000000000..d2d2a0cbf --- /dev/null +++ b/netcon/docker-test/darkhttpd/darkhttpd-1.11.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/darkhttpd/darkhttpd-1.11.x86_64/monitor_entrypoint.sh b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/monitor_entrypoint.sh new file mode 100644 index 000000000..c8fca5a34 --- /dev/null +++ b/netcon/docker-test/darkhttpd/darkhttpd-1.11.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/darkhttpd/darkhttpd-1.11.x86_64/netcon_dockerfile b/netcon/docker-test/darkhttpd/darkhttpd-1.11.x86_64/netcon_dockerfile new file mode 100644 index 000000000..66a39d88e --- /dev/null +++ b/netcon/docker-test/darkhttpd/darkhttpd-1.11.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 darkhttpd-1.11 +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/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 000000000..978696a89 --- /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/^//" | 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/python/python/monitor_dockerfile b/netcon/docker-test/python/python/monitor_dockerfile new file mode 100644 index 000000000..d2d2a0cbf --- /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 000000000..c8fca5a34 --- /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 000000000..6646f670d --- /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 000000000..5e1a19b87 --- /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/^//" | 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 000000000..d2d2a0cbf --- /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 000000000..c8fca5a34 --- /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 000000000..f960fa302 --- /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 000000000..c3c8b281f --- /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/^//" | 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 From 7526ed705cf79490fbe924912a3b0da64166d2b7 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 21 Jan 2016 16:01:24 -0800 Subject: [PATCH 03/45] Check for /dev/tun as well as /dev/net/tun since some Linux devices put it there. --- osdep/LinuxEthernetTap.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/osdep/LinuxEthernetTap.cpp b/osdep/LinuxEthernetTap.cpp index 3e225b366..c66b7a38b 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)); From bafdb54752e8e953715a6547d13716b9c59e9d53 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 21 Jan 2016 16:02:16 -0800 Subject: [PATCH 04/45] New dev version: 1.1.5 --- version.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.h b/version.h index efff7cefd..62045ed81 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 From 3993dfa2a55516cfc5aee95f6889dc6ea8653918 Mon Sep 17 00:00:00 2001 From: Grant Limberg Date: Fri, 22 Jan 2016 18:06:58 -0800 Subject: [PATCH 05/45] Fix JNI for API changes in 1.1.4 --- java/jni/com_zerotierone_sdk_Node.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/java/jni/com_zerotierone_sdk_Node.cpp b/java/jni/com_zerotierone_sdk_Node.cpp index 2c1b68071..dbabf8032 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); } From 95d28494f6fbe352ac7746f0c544e3527534ba0d Mon Sep 17 00:00:00 2001 From: Joseph Henry Date: Mon, 25 Jan 2016 12:55:29 -0800 Subject: [PATCH 06/45] Mac OSX Port - Lightly tested --- make-mac.mk | 14 +++++++++++++- netcon/Intercept.c | 44 ++++++++++++++++++++++++++++++++++++++------ netcon/Intercept.h | 24 +++++++++++++++++------- netcon/LWIPStack.hpp | 6 ++++++ netcon/README.md | 16 ++++++++++++++++ netcon/RPC.c | 16 +++++++++++----- 6 files changed, 101 insertions(+), 19 deletions(-) diff --git a/make-mac.mk b/make-mac.mk index ffaf822da..20e09c4b2 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 @@ -97,7 +109,7 @@ official: FORCE 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 9c4feedfb..48276c966 100644 --- a/netcon/Intercept.c +++ b/netcon/Intercept.c @@ -38,20 +38,25 @@ #include #include #include -#include #include #include #include -#include #include #include #include #include #include #include -#include /* for NPROTO */ -#define SOCK_MAX (SOCK_PACKET + 1) +#if defined(__linux__) + #include + #include + #include /* 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 b399993b2..9593468fd 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 + +#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 fedbdd5f1..2ad1a843c 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 d694064ae..12d48c1d0 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. diff --git a/netcon/RPC.c b/netcon/RPC.c index a69658929..7d5c11e0d 100644 --- a/netcon/RPC.c +++ b/netcon/RPC.c @@ -3,7 +3,10 @@ #include #include #include + +#if defined(__linux__) #include +#endif #include #include @@ -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(×tamp)); 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], ×tring, 20 ); /* timestamp */ #endif From 9cb4bbe2b879f766c7cdfc998ddd55d15ce201a2 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Tue, 26 Jan 2016 12:42:44 -0800 Subject: [PATCH 07/45] Save test results for circuit tests in memory and then cancel the test and send the results when the test is queried later. This way you can POST a test and then come GET the result at the appointed time. --- controller/SqliteNetworkController.cpp | 142 ++++++++++++++----------- controller/SqliteNetworkController.hpp | 11 +- 2 files changed, 85 insertions(+), 68 deletions(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index 0e90163de..7857ed567 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -555,7 +555,11 @@ 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)); return 200; @@ -1235,6 +1239,22 @@ unsigned int SqliteNetworkController::_doCPGet( } + } 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()) { + + responseBody = "["; + responseBody.append(cte->second.jsonResults); + responseBody.push_back(']'); + responseContentType = "application/json"; + + _node->circuitTestEnd(cte->second.test); + ::free((void *)cte->second.test); + _circuitTests.erase(cte); + + } // else 404 + } // else 404 } else { @@ -1930,73 +1950,67 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c void SqliteNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report) { - static Mutex circuitTestWriteLock; + char tmp[65535]; + SqliteNetworkController *const self = reinterpret_cast(test->ptr); - const uint64_t now = OSUtils::now(); + if (!test) + return; + if (!report) + return; - SqliteNetworkController *const c = reinterpret_cast(test->ptr); - char tmp[128]; + Mutex::Lock _l(self->_lock); + std::map< uint64_t,_CircuitTestEntry >::iterator cte(self->_circuitTests.find(test->testId)); - 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(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(&(report->receivedOnLocalAddress))->toString().c_str(), - reinterpret_cast(&(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(&(report->receivedOnLocalAddress))->toString().c_str(), + reinterpret_cast(&(report->receivedFromRemoteAddress))->toString().c_str()); + + cte->second.jsonResults.append(tmp); } } // namespace ZeroTier diff --git a/controller/SqliteNetworkController.hpp b/controller/SqliteNetworkController.hpp index 0e2bb63e7..d58b3fc93 100644 --- a/controller/SqliteNetworkController.hpp +++ b/controller/SqliteNetworkController.hpp @@ -123,7 +123,7 @@ private: std::string _circuitTestPath; std::string _instanceId; - // A circular buffer last log + // Recent request log by device address and network ID struct _LLEntry { _LLEntry() @@ -148,12 +148,15 @@ private: // Total requests by this address / network ID pair (also serves mod IN_MEMORY_LOG_SIZE as circular buffer ptr) uint64_t totalRequests; }; - - // Last log entries by address and network ID pair std::map< std::pair,_LLEntry > _lastLog; // Circuit tests outstanding - std::map< uint64_t,ZT_CircuitTest * > _circuitTests; + struct _CircuitTestEntry + { + ZT_CircuitTest *test; + std::string jsonResults; + }; + std::map< uint64_t,_CircuitTestEntry > _circuitTests; sqlite3 *_db; From 4655a59912ba61b2f79f74976e2448c0fb32c402 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 28 Jan 2016 17:59:31 -0800 Subject: [PATCH 08/45] typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 123fbf019..1a93a4348 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 From 7a63fdc447322da3630774a894822bbe6fbb708f Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 1 Feb 2016 14:41:54 -0800 Subject: [PATCH 09/45] Fix for GitHub issue #298 and hopefully #297 --- node/InetAddress.cpp | 4 +++- selftest.cpp | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/node/InetAddress.cpp b/node/InetAddress.cpp index d5cd227cd..dca772e8f 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(this)->sin_addr.s_addr = *(reinterpret_cast(ipBytes)); + reinterpret_cast(this)->sin_addr.s_addr = ipb[0]; reinterpret_cast(this)->sin_port = Utils::hton((uint16_t)port); } else if (ipLen == 16) { ss_family = AF_INET6; diff --git a/selftest.cpp b/selftest.cpp index 9870c16a0..847b08b67 100644 --- a/selftest.cpp +++ b/selftest.cpp @@ -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) {} From f8eb6b00674a218cef20fd2ad6803fdecabc82ab Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 3 Feb 2016 13:56:35 -0800 Subject: [PATCH 10/45] Add NodeHistory table on sqlite controller. --- controller/SqliteNetworkController.cpp | 38 +++++++++++++++++++++++--- controller/SqliteNetworkController.hpp | 27 ------------------ controller/schema.sql | 14 ++++++++++ controller/schema.sql.c | 14 ++++++++++ 4 files changed, 62 insertions(+), 31 deletions(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index 7857ed567..bee4fbf1f 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -61,8 +61,8 @@ // 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 @@ -146,8 +146,31 @@ 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" + " 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"); } @@ -1182,6 +1205,7 @@ unsigned int SqliteNetworkController::_doCPGet( responseBody.append("],\n\t\"recentLog\": ["); + /* { std::map< std::pair,_LLEntry >::const_iterator lli(_lastLog.find(std::pair(Address(address),nwid))); if (lli != _lastLog.end()) { @@ -1212,6 +1236,7 @@ unsigned int SqliteNetworkController::_doCPGet( } } } + */ responseBody.append("]\n}\n"); @@ -1561,12 +1586,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(); + + // Check rate limit circuit breaker to prevent flooding + /* _LLEntry &lastLogEntry = _lastLog[std::pair(identity.address(),nwid)]; if ((now - lastLogEntry.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD) return NetworkController::NETCONF_QUERY_IGNORE; lastLogEntry.lastRequestTime = now; + */ NetworkRecord network; memset(&network,0,sizeof(network)); @@ -1654,6 +1682,7 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c // Add log entry to in-memory circular log + /* { const unsigned long ptr = (unsigned long)lastLogEntry.totalRequests % ZT_SQLITENETWORKCONTROLLER_IN_MEMORY_LOG_SIZE; lastLogEntry.l[ptr].ts = now; @@ -1665,6 +1694,7 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c ++lastLogEntry.totalRequests; // TODO: push or save these somewhere } + */ // Check member authorization diff --git a/controller/SqliteNetworkController.hpp b/controller/SqliteNetworkController.hpp index d58b3fc93..6562058ac 100644 --- a/controller/SqliteNetworkController.hpp +++ b/controller/SqliteNetworkController.hpp @@ -123,33 +123,6 @@ private: std::string _circuitTestPath; std::string _instanceId; - // Recent request log by device address and network ID - struct _LLEntry - { - _LLEntry() - { - for(long i=0;il[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; - }; - std::map< std::pair,_LLEntry > _lastLog; - // Circuit tests outstanding struct _CircuitTestEntry { diff --git a/controller/schema.sql b/controller/schema.sql index b6db7fa48..c40e5cacd 100644 --- a/controller/schema.sql +++ b/controller/schema.sql @@ -34,6 +34,20 @@ 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), + 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 a5b9130b5..45cc0d33c 100644 --- a/controller/schema.sql.c +++ b/controller/schema.sql.c @@ -35,6 +35,20 @@ " 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"\ +" 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"\ From 2e04dc03f26464cc1d3a9f3aca71a0e9025d355b Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 3 Feb 2016 18:10:56 -0800 Subject: [PATCH 11/45] Logging to NodeHistory, SQL queries. --- controller/SqliteNetworkController.cpp | 133 +++++++++++++++---------- controller/SqliteNetworkController.hpp | 8 ++ 2 files changed, 89 insertions(+), 52 deletions(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index bee4fbf1f..7338dc291 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -69,11 +69,14 @@ // Drop requests for a given peer and network ID that occur more frequently // than this (ms). -#define ZT_NETCONF_MIN_REQUEST_PERIOD 1000 +#define ZT_NETCONF_MIN_REQUEST_PERIOD 500 // Delay between backups in milliseconds #define ZT_NETCONF_BACKUP_PERIOD 120000 +// Number of NodeHistory entries to maintain per node and network (can be changed) +#define ZT_NETCONF_NODE_HISTORY_LENGTH 16 + namespace ZeroTier { namespace { @@ -200,6 +203,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,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 DISTINCT nodeId FROM NodeHistory WHERE networkId = ? AND requestTime >= ? AND networkRequestAuthorized != 0 ORDER BY nodeId ASC",-1,&_sGetActiveNodesOnNetwork,(const char **)0) != SQLITE_OK) + ||(sqlite3_prepare_v2(_db,"SELECT networkVisitCounter,networkRequestAuthorized,requestTime,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) @@ -290,6 +300,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); @@ -1198,46 +1213,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,_LLEntry >::const_iterator lli(_lastLog.find(std::pair(Address(address),nwid))); - if (lli != _lastLog.end()) { - const _LLEntry &lastLogEntry = lli->second; - uint64_t eptr = lastLogEntry.totalRequests; - for(int k=0;k(identity.address(),nwid)]; - if ((now - lastLogEntry.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD) - return NetworkController::NETCONF_QUERY_IGNORE; - lastLogEntry.lastRequestTime = now; - */ + { + uint64_t &lrt = _lastRequestTime[identity.address()]; + if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD) + return NetworkController::NETCONF_QUERY_IGNORE; + lrt = now; + } NetworkRecord network; memset(&network,0,sizeof(network)); @@ -1680,21 +1685,45 @@ 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_text(_sAddNodeHistoryEntry,6,mdstr.c_str(),-1,SQLITE_STATIC); + if (fastr.length() > 0) + sqlite3_bind_text(_sAddNodeHistoryEntry,7,fastr.c_str(),-1,SQLITE_STATIC); + else sqlite3_bind_null(_sAddNodeHistoryEntry,7); + 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 diff --git a/controller/SqliteNetworkController.hpp b/controller/SqliteNetworkController.hpp index 6562058ac..22441f110 100644 --- a/controller/SqliteNetworkController.hpp +++ b/controller/SqliteNetworkController.hpp @@ -131,6 +131,9 @@ private: }; std::map< uint64_t,_CircuitTestEntry > _circuitTests; + // Last request time by address, for rate limitation + std::map< Address,uint64_t > _lastRequestTime; + sqlite3 *_db; sqlite3_stmt *_sGetNetworkById; @@ -138,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; From fab6f4450d741b37f8b1181e2914db3d63f9fdcc Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 4 Feb 2016 12:17:55 -0800 Subject: [PATCH 12/45] /active subpath off networks --- controller/SqliteNetworkController.cpp | 37 +++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index 7338dc291..899186adb 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -75,7 +75,10 @@ #define ZT_NETCONF_BACKUP_PERIOD 120000 // Number of NodeHistory entries to maintain per node and network (can be changed) -#define ZT_NETCONF_NODE_HISTORY_LENGTH 16 +#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) namespace ZeroTier { @@ -207,7 +210,7 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c ||(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,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 DISTINCT nodeId FROM NodeHistory WHERE networkId = ? AND requestTime >= ? AND networkRequestAuthorized != 0 ORDER BY nodeId ASC",-1,&_sGetActiveNodesOnNetwork,(const char **)0) != SQLITE_OK) + ||(sqlite3_prepare_v2(_db,"SELECT nodeId,COUNT(nodeId),MAX(requestTime) FROM NodeHistory WHERE networkId = ? AND requestTime >= ? AND networkRequestAuthorized > 0 GROUP BY nodeId",-1,&_sGetActiveNodesOnNetwork,(const char **)0) != SQLITE_OK) ||(sqlite3_prepare_v2(_db,"SELECT networkVisitCounter,networkRequestAuthorized,requestTime,networkRequestMetaData,fromAddress FROM NodeHistory WHERE networkId = ? AND nodeId = ? ORDER BY requestTime DESC",-1,&_sGetNodeHistory,(const char **)0) != SQLITE_OK) /* Rule */ @@ -1254,7 +1257,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 ? "\"" : ",\""); @@ -1269,6 +1272,32 @@ 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_int64(_sGetActiveNodesOnNetwork,2,(int64_t)(OSUtils::now() - ZT_NETCONF_NODE_ACTIVE_THRESHOLD)); + + responseBody.push_back('{'); + bool firstMember = true; + while (sqlite3_step(_sGetActiveNodesOnNetwork) == SQLITE_ROW) { + const char *nid = (const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,0); + if (nid) { + responseBody.append(firstMember ? "\"" : ",\""); + responseBody.append(nid); + responseBody.append("\":{\"count\":"); + responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,1)); + responseBody.append(",\"latestTime\":"); + responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,2)); + responseBody.push_back('}'); + firstMember = false; + } + } + 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()))); @@ -1288,7 +1317,7 @@ unsigned int SqliteNetworkController::_doCPGet( } // else 404 } else { - // get network info + sqlite3_reset(_sGetNetworkById); sqlite3_bind_text(_sGetNetworkById,1,nwids,16,SQLITE_STATIC); if (sqlite3_step(_sGetNetworkById) == SQLITE_ROW) { From 90801a94d3febd8e77a785a396b3223d4a7d31c3 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 4 Feb 2016 13:38:42 -0800 Subject: [PATCH 13/45] Track client version and tell whether active nodes support circuit test. --- controller/SqliteNetworkController.cpp | 47 +++++++++++++++----------- controller/schema.sql | 3 ++ controller/schema.sql.c | 3 ++ 3 files changed, 34 insertions(+), 19 deletions(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index 899186adb..5055adedc 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -161,6 +161,9 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c " 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" @@ -208,10 +211,10 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c /* 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,networkRequestMetaData,fromAddress) VALUES (?,?,?,?,?,?,?)",-1,&_sAddNodeHistoryEntry,(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,COUNT(nodeId),MAX(requestTime) FROM NodeHistory WHERE networkId = ? AND requestTime >= ? AND networkRequestAuthorized > 0 GROUP BY nodeId",-1,&_sGetActiveNodesOnNetwork,(const char **)0) != SQLITE_OK) - ||(sqlite3_prepare_v2(_db,"SELECT networkVisitCounter,networkRequestAuthorized,requestTime,networkRequestMetaData,fromAddress FROM NodeHistory WHERE networkId = ? AND nodeId = ? ORDER BY requestTime DESC",-1,&_sGetNodeHistory,(const char **)0) != SQLITE_OK) + ||(sqlite3_prepare_v2(_db,"SELECT nodeId,COUNT(nodeId),MAX(requestTime),MAX((((clientMajorVersion & 65535) << 32) | ((clientMinorVersion & 65535) << 16) | (clientRevision & 65535))) FROM NodeHistory WHERE networkId = ? AND requestTime >= ? AND networkRequestAuthorized > 0 GROUP BY nodeId",-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) @@ -260,9 +263,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 @@ -1048,7 +1051,7 @@ unsigned int SqliteNetworkController::handleControlPlaneHttpDELETE( void SqliteNetworkController::threadMain() throw() { - uint64_t lastBackupTime = 0; + uint64_t lastBackupTime = OSUtils::now(); while (_backupThreadRun) { if ((OSUtils::now() - lastBackupTime) >= ZT_NETCONF_BACKUP_PERIOD) { lastBackupTime = OSUtils::now(); @@ -1231,14 +1234,14 @@ unsigned int SqliteNetworkController::_doCPGet( 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,\"version\":" : ",\"authorized\":true,\"metaData\":"); - const char *md = (const char *)sqlite3_column_text(_sGetNodeHistory,3); - if (md) { - responseBody.push_back('"'); - responseBody.append(_jsonEscape(md)); - responseBody.append("\",\"fromAddr\":"); - } else responseBody.append("null,\"fromAddr\":"); - const char *fa = (const char *)sqlite3_column_text(_sGetNodeHistory,4); + 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)); @@ -1285,10 +1288,13 @@ unsigned int SqliteNetworkController::_doCPGet( if (nid) { responseBody.append(firstMember ? "\"" : ",\""); responseBody.append(nid); - responseBody.append("\":{\"count\":"); + responseBody.append("\":{\"cnt\":"); responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,1)); - responseBody.append(",\"latestTime\":"); + responseBody.append(",\"lt\":"); responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,2)); + if ((uint64_t)sqlite3_column_int64(_sGetActiveNodesOnNetwork,3) >= 0x0000000100010000ULL) + responseBody.append(",\"cts\":true"); + else responseBody.append(",\"cts\":false"); responseBody.push_back('}'); firstMember = false; } @@ -1738,10 +1744,13 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c 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_text(_sAddNodeHistoryEntry,6,mdstr.c_str(),-1,SQLITE_STATIC); + 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,7,fastr.c_str(),-1,SQLITE_STATIC); - else sqlite3_bind_null(_sAddNodeHistoryEntry,7); + 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; diff --git a/controller/schema.sql b/controller/schema.sql index c40e5cacd..aff088273 100644 --- a/controller/schema.sql +++ b/controller/schema.sql @@ -40,6 +40,9 @@ CREATE TABLE NodeHistory ( 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) ); diff --git a/controller/schema.sql.c b/controller/schema.sql.c index 45cc0d33c..4b524547e 100644 --- a/controller/schema.sql.c +++ b/controller/schema.sql.c @@ -41,6 +41,9 @@ " 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"\ From 13b39a0c3e11ae44277599dc01512d620197b407 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 4 Feb 2016 14:03:37 -0800 Subject: [PATCH 14/45] SQLite perf tuning --- controller/SqliteNetworkController.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index 5055adedc..fb565dcb5 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -140,6 +140,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; From 5dad73647df29e85f1fd1a8c8e4296de1edfe79d Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 4 Feb 2016 14:22:54 -0800 Subject: [PATCH 15/45] Lengthen backup period again --- controller/SqliteNetworkController.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index fb565dcb5..c17a66038 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -72,7 +72,7 @@ #define ZT_NETCONF_MIN_REQUEST_PERIOD 500 // 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 From 78c1d9006ae7339fcec224e9a3f367ab17b242e1 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 4 Feb 2016 14:39:43 -0800 Subject: [PATCH 16/45] flood protection fix --- controller/SqliteNetworkController.cpp | 15 ++++++--------- controller/SqliteNetworkController.hpp | 2 +- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index c17a66038..e8b1d49e7 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -67,9 +67,8 @@ // 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). -#define ZT_NETCONF_MIN_REQUEST_PERIOD 500 +// 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 300000 @@ -216,7 +215,7 @@ SqliteNetworkController::SqliteNetworkController(Node *node,const char *dbPath,c ||(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,COUNT(nodeId),MAX(requestTime),MAX((((clientMajorVersion & 65535) << 32) | ((clientMinorVersion & 65535) << 16) | (clientRevision & 65535))) FROM NodeHistory WHERE networkId = ? AND requestTime >= ? AND networkRequestAuthorized > 0 GROUP BY nodeId",-1,&_sGetActiveNodesOnNetwork,(const char **)0) != SQLITE_OK) + ||(sqlite3_prepare_v2(_db,"SELECT nodeId,MAX(requestTime),MAX((((clientMajorVersion & 65535) << 32) | ((clientMinorVersion & 65535) << 16) | (clientRevision & 65535))) FROM NodeHistory WHERE networkId = ? AND requestTime >= ? AND networkRequestAuthorized > 0 GROUP BY nodeId",-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 */ @@ -1291,11 +1290,9 @@ unsigned int SqliteNetworkController::_doCPGet( if (nid) { responseBody.append(firstMember ? "\"" : ",\""); responseBody.append(nid); - responseBody.append("\":{\"cnt\":"); + responseBody.append("\":{\"lt\":"); responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,1)); - responseBody.append(",\"lt\":"); - responseBody.append((const char *)sqlite3_column_text(_sGetActiveNodesOnNetwork,2)); - if ((uint64_t)sqlite3_column_int64(_sGetActiveNodesOnNetwork,3) >= 0x0000000100010000ULL) + if ((uint64_t)sqlite3_column_int64(_sGetActiveNodesOnNetwork,2) >= 0x0000000100010000ULL) responseBody.append(",\"cts\":true"); else responseBody.append(",\"cts\":false"); responseBody.push_back('}'); @@ -1633,7 +1630,7 @@ NetworkController::ResultCode SqliteNetworkController::_doNetworkConfigRequest(c // Check rate limit circuit breaker to prevent flooding { - uint64_t &lrt = _lastRequestTime[identity.address()]; + uint64_t &lrt = _lastRequestTime[std::pair(identity.address().toInt(),nwid)]; if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD) return NetworkController::NETCONF_QUERY_IGNORE; lrt = now; diff --git a/controller/SqliteNetworkController.hpp b/controller/SqliteNetworkController.hpp index 22441f110..fe9bbcb84 100644 --- a/controller/SqliteNetworkController.hpp +++ b/controller/SqliteNetworkController.hpp @@ -132,7 +132,7 @@ private: std::map< uint64_t,_CircuitTestEntry > _circuitTests; // Last request time by address, for rate limitation - std::map< Address,uint64_t > _lastRequestTime; + std::map< std::pair,uint64_t > _lastRequestTime; sqlite3 *_db; From dc3d899e70758613ff9473399e21d3766ec9e254 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 4 Feb 2016 16:09:26 -0800 Subject: [PATCH 17/45] Return test ID when we post a test. --- controller/SqliteNetworkController.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index e8b1d49e7..90a476ce6 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -608,6 +608,11 @@ unsigned int SqliteNetworkController::handleControlPlaneHttpPOST( _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 From 69b1da2e1d14f95629c5ae9442d6797a86667c61 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 4 Feb 2016 16:27:25 -0800 Subject: [PATCH 18/45] return 200 instead of 404 when test is fetched --- controller/SqliteNetworkController.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index 90a476ce6..804c763d8 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -1312,7 +1312,7 @@ unsigned int SqliteNetworkController::_doCPGet( } 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()) { + if ((cte != _circuitTests.end())&&(cte->second.test)) { responseBody = "["; responseBody.append(cte->second.jsonResults); @@ -1323,6 +1323,8 @@ unsigned int SqliteNetworkController::_doCPGet( ::free((void *)cte->second.test); _circuitTests.erase(cte); + return 200; + } // else 404 } // else 404 From a963810e021c4e76d7f4e8958ff07a44eb07ed69 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 8 Feb 2016 09:57:46 -0800 Subject: [PATCH 19/45] Tweak a few cluster params for higher perf / lower initial setup latency. --- node/Cluster.hpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/node/Cluster.hpp b/node/Cluster.hpp index e21d60201..dafbf4255 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 { From 63ec7e58d413aa4066764a9818c77c016cd9b8ff Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 8 Feb 2016 10:03:01 -0800 Subject: [PATCH 20/45] Make activity no longer a function of ping frequency, since this causes compatibility bugs when the latter was modified due to timer interactions with other versions. --- node/Constants.hpp | 7 ++++++- node/Path.hpp | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/node/Constants.hpp b/node/Constants.hpp index 4d6c9d077..356260e64 100644 --- a/node/Constants.hpp +++ b/node/Constants.hpp @@ -260,7 +260,12 @@ /** * 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 diff --git a/node/Path.hpp b/node/Path.hpp index 668728e00..be64f3341 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)); } /** From 4769dacf6102342ddd4519cfe8227bf6fc49fbcc Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Tue, 9 Feb 2016 16:54:47 -0800 Subject: [PATCH 21/45] Tweak needsOurMembershipCertificate timing to resolve a possible source of occasional dropped packets. --- node/Peer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/node/Peer.cpp b/node/Peer.cpp index 17f9b2efe..c3157f036 100644 --- a/node/Peer.cpp +++ b/node/Peer.cpp @@ -419,7 +419,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) From 10bb9919f15a7777905f3d43ca01325a229203c7 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 10 Feb 2016 09:32:42 -0800 Subject: [PATCH 22/45] Tweak certificate of membership revision/time tolerance to eliminate boundary packet loss issues occasionally seen in the wild. --- controller/SqliteNetworkController.cpp | 2 +- node/CertificateOfMembership.hpp | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index 804c763d8..352f212e4 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -2034,7 +2034,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 { diff --git a/node/CertificateOfMembership.hpp b/node/CertificateOfMembership.hpp index c6d59397f..44d892e70 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 three 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 * 3) + namespace ZeroTier { /** From 82348e1537442f9f167e4365f3e3024cf70b2b8d Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 10 Feb 2016 11:06:26 -0800 Subject: [PATCH 23/45] Temporarily blacklist he.net IPv6 tunnel addresses for paths: these usually have a very low MTU which causes packet loss and other issues. --- node/Path.hpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/node/Path.hpp b/node/Path.hpp index be64f3341..cb7622d32 100644 --- a/node/Path.hpp +++ b/node/Path.hpp @@ -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(reinterpret_cast(&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; From f9230eb97077f628186f8966190b2237fa4ff5d5 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 10 Feb 2016 16:18:45 -0800 Subject: [PATCH 24/45] Widen max delta for TS/revision just a bit more for now. --- node/CertificateOfMembership.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/node/CertificateOfMembership.hpp b/node/CertificateOfMembership.hpp index 44d892e70..9a2798833 100644 --- a/node/CertificateOfMembership.hpp +++ b/node/CertificateOfMembership.hpp @@ -37,11 +37,11 @@ * 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 three minutes, which + * 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 * 3) +#define ZT_NETWORK_COM_DEFAULT_REVISION_MAX_DELTA (ZT_NETWORK_AUTOCONF_DELAY * 5) namespace ZeroTier { From eadafd8de754336f8c06302305a26669762a365d Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 10 Feb 2016 17:51:42 -0800 Subject: [PATCH 25/45] Little fix to NAT-t alg --- node/Switch.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/node/Switch.cpp b/node/Switch.cpp index 4c91a8558..1ed1dfe61 100644 --- a/node/Switch.cpp +++ b/node/Switch.cpp @@ -490,10 +490,10 @@ unsigned long Switch::doTimerTasks(uint64_t now) // 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; + 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++); From 0c951b6e56db47f2be4850343ae3908d0ea83099 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 10 Feb 2016 18:41:39 -0800 Subject: [PATCH 26/45] More tweaks to new symmetric NAT buster, and stop using old iterative method since this supersedes it. --- node/Peer.cpp | 123 +++++++++++++++++++++++------------------ node/Peer.hpp | 6 +- node/SelfAwareness.cpp | 63 ++++++++++++++------- node/SelfAwareness.hpp | 7 +++ node/Switch.cpp | 49 ++++++++-------- 5 files changed, 148 insertions(+), 100 deletions(-) diff --git a/node/Peer.cpp b/node/Peer.cpp index c3157f036..b9d11292e 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 dps(RR->node->directPaths()); - if (dps.empty()) - return; - -#ifdef ZT_TRACE - { - std::string ps; - for(std::vector::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::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; - } - - 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; - } - - if (count) { - outp.setAt(ZT_PACKET_IDX_PAYLOAD,(uint16_t)count); - outp.armor(_key,true); - path->send(RR,outp.data(),outp.size(),now); - } + std::vector dps(RR->node->directPaths()); + std::vector sym(RR->sa->getSymmetricNatPredictions()); + for(unsigned long i=0,added=0;inode->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::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::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()); + + ++count; + ++p; + } + + 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) diff --git a/node/Peer.hpp b/node/Peer.hpp index 5796baf93..94c58ae89 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 db069046a..cf43a6441 100644 --- a/node/SelfAwareness.cpp +++ b/node/SelfAwareness.cpp @@ -20,6 +20,9 @@ #include #include +#include +#include + #include "Constants.hpp" #include "SelfAwareness.hpp" #include "RuntimeEnvironment.hpp" @@ -68,30 +71,14 @@ void SelfAwareness::iam(const Address &reporter,const InetAddress &reporterPhysi { 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)]; - 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,41 @@ void SelfAwareness::clean(uint64_t now) } } +std::vector SelfAwareness::getSymmetricNatPredictions() +{ + std::set surfaces; + + // Ideas based on: https://tools.ietf.org/html/draft-takeda-symmetric-nat-traversal-00 + + { + 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)) { + surfaces.insert(e->mySurface); + } + } + } + + if (surfaces.size() > 1) { + // More than one global IPv4 surface means this is a symmetric NAT + std::vector r; + for(std::set::iterator i(surfaces.begin());i!=surfaces.end();++i) { + InetAddress nextPort(*i); + unsigned int p = nextPort.port(); + if (p >= 65535) + p = 1025; + else ++p; + nextPort.setPort(p); + if (surfaces.count(nextPort) == 0) + r.push_back(nextPort); + } + return r; + } + + return std::vector(); +} + } // namespace ZeroTier diff --git a/node/SelfAwareness.hpp b/node/SelfAwareness.hpp index 2534d986a..73950a53e 100644 --- a/node/SelfAwareness.hpp +++ b/node/SelfAwareness.hpp @@ -56,6 +56,13 @@ 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 getSymmetricNatPredictions(); + private: struct PhySurfaceKey { diff --git a/node/Switch.cpp b/node/Switch.cpp index 1ed1dfe61..4e20300df 100644 --- a/node/Switch.cpp +++ b/node/Switch.cpp @@ -478,31 +478,31 @@ unsigned long Switch::doTimerTasks(uint64_t now) Mutex::Lock _l(_contactQueue_m); for(std::list::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 > 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; - } - ++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)); } @@ -813,12 +813,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); From 772551c45da254c221ae9237423c7adb3978190e Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 11 Feb 2016 10:39:39 -0800 Subject: [PATCH 27/45] Try +1 and +2 existing surfaces for symmetric NATs. --- node/SelfAwareness.cpp | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/node/SelfAwareness.cpp b/node/SelfAwareness.cpp index cf43a6441..dde77ee57 100644 --- a/node/SelfAwareness.cpp +++ b/node/SelfAwareness.cpp @@ -150,14 +150,24 @@ std::vector SelfAwareness::getSymmetricNatPredictions() // More than one global IPv4 surface means this is a symmetric NAT std::vector r; for(std::set::iterator i(surfaces.begin());i!=surfaces.end();++i) { - InetAddress nextPort(*i); - unsigned int p = nextPort.port(); - if (p >= 65535) + InetAddress ipp(*i); + unsigned int p = ipp.port(); + + // Try 1+ surface ports + if (p >= 0xffff) p = 1025; else ++p; - nextPort.setPort(p); - if (surfaces.count(nextPort) == 0) - r.push_back(nextPort); + ipp.setPort(p); + if ((surfaces.count(ipp) == 0)&&(std::find(r.begin(),r.end(),ipp) == r.end())) + r.push_back(ipp); + + // Try 2+ surface ports + if (p >= 0xffff) + p = 1025; + else ++p; + ipp.setPort(p); + if ((surfaces.count(ipp) == 0)&&(std::find(r.begin(),r.end(),ipp) == r.end())) + r.push_back(ipp); } return r; } From 69a438d64d527d37c588939ef3014949ec579b76 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Fri, 19 Feb 2016 09:10:31 -0800 Subject: [PATCH 28/45] Small tweak to active threshold. --- controller/SqliteNetworkController.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index 352f212e4..5283b5ae5 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -77,7 +77,7 @@ #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) +#define ZT_NETCONF_NODE_ACTIVE_THRESHOLD ((ZT_NETWORK_AUTOCONF_DELAY * 2) + 5000) namespace ZeroTier { From 2aa7138373b3d61bf5d6ec8026192ef82a3d6ec3 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 22 Feb 2016 09:47:50 -0800 Subject: [PATCH 29/45] Reduce direct ping delay back to 1m and make SelfAwareness aware of local received-on address to eliminate false symmetric classification. --- node/Constants.hpp | 2 +- node/IncomingPacket.cpp | 4 +-- node/SelfAwareness.cpp | 63 +++++++++++++++++++++++------------------ node/SelfAwareness.hpp | 8 ++++-- 4 files changed, 44 insertions(+), 33 deletions(-) diff --git a/node/Constants.hpp b/node/Constants.hpp index 356260e64..19ac3619d 100644 --- a/node/Constants.hpp +++ b/node/Constants.hpp @@ -255,7 +255,7 @@ /** * 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) diff --git a/node/IncomingPacket.cpp b/node/IncomingPacket.cpp index efb43d23f..66c956b30 100644 --- a/node/IncomingPacket.cpp +++ b/node/IncomingPacket.cpp @@ -282,7 +282,7 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,SharedPtr &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 &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: { diff --git a/node/SelfAwareness.cpp b/node/SelfAwareness.cpp index dde77ee57..c05028154 100644 --- a/node/SelfAwareness.cpp +++ b/node/SelfAwareness.cpp @@ -67,7 +67,7 @@ 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(); @@ -75,7 +75,7 @@ void SelfAwareness::iam(const Address &reporter,const InetAddress &reporterPhysi return; Mutex::Lock _l(_phy_m); - PhySurfaceEntry &entry = _phy[PhySurfaceKey(reporter,reporterPhysicalAddress,scope)]; + PhySurfaceEntry &entry = _phy[PhySurfaceKey(reporter,receivedOnLocalAddress,reporterPhysicalAddress,scope)]; 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 @@ -130,10 +130,22 @@ void SelfAwareness::clean(uint64_t now) std::vector SelfAwareness::getSymmetricNatPredictions() { - std::set surfaces; - - // Ideas based on: https://tools.ietf.org/html/draft-takeda-symmetric-nat-traversal-00 + /* 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 > surfaces; + bool symmetric = false; { Mutex::Lock _l(_phy_m); Hashtable< PhySurfaceKey,PhySurfaceEntry >::Iterator i(_phy); @@ -141,33 +153,30 @@ std::vector SelfAwareness::getSymmetricNatPredictions() PhySurfaceEntry *e = (PhySurfaceEntry *)0; while (i.next(k,e)) { if ((e->mySurface.ss_family == AF_INET)&&(e->mySurface.ipScope() == InetAddress::IP_SCOPE_GLOBAL)) { - surfaces.insert(e->mySurface); + std::set &s = surfaces[k->receivedOnLocalAddress]; + s.insert(e->mySurface); + symmetric = symmetric||(s.size() > 1); } } } - if (surfaces.size() > 1) { - // More than one global IPv4 surface means this is a symmetric NAT + // 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 r; - for(std::set::iterator i(surfaces.begin());i!=surfaces.end();++i) { - InetAddress ipp(*i); - unsigned int p = ipp.port(); - - // Try 1+ surface ports - if (p >= 0xffff) - p = 1025; - else ++p; - ipp.setPort(p); - if ((surfaces.count(ipp) == 0)&&(std::find(r.begin(),r.end(),ipp) == r.end())) - r.push_back(ipp); - - // Try 2+ surface ports - if (p >= 0xffff) - p = 1025; - else ++p; - ipp.setPort(p); - if ((surfaces.count(ipp) == 0)&&(std::find(r.begin(),r.end(),ipp) == r.end())) - r.push_back(ipp); + for(std::map< InetAddress,std::set >::iterator si(surfaces.begin());si!=surfaces.end();++si) { + for(std::set::iterator i(si->second.begin());i!=si->second.end();++i) { + InetAddress ipp(*i); + unsigned int p = ipp.port() + 1 + ((unsigned int)RR->node->prng() % 5); + 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; } diff --git a/node/SelfAwareness.hpp b/node/SelfAwareness.hpp index 73950a53e..06c264a91 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 @@ -67,14 +68,15 @@ 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 { From 43fff1a87ec86470f7f4fe5887d4bf444d1d1b9f Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 22 Feb 2016 12:59:26 -0800 Subject: [PATCH 30/45] Deprecate reporting of local clock in circuit tests since a small number of users might have security problems with this. --- node/IncomingPacket.cpp | 2 +- node/Packet.hpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/node/IncomingPacket.cpp b/node/IncomingPacket.cpp index 66c956b30..8a180380b 100644 --- a/node/IncomingPacket.cpp +++ b/node/IncomingPacket.cpp @@ -1078,7 +1078,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); diff --git a/node/Packet.hpp b/node/Packet.hpp index 2381397b6..7d1e5c684 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> From 9b59bcd995c85963b2a9fb06677ed3ac963990a9 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 22 Feb 2016 15:48:27 -0800 Subject: [PATCH 31/45] Clean controller circuit test memory. --- controller/SqliteNetworkController.cpp | 25 +++++++++++++++++++++---- controller/SqliteNetworkController.hpp | 4 ++-- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/controller/SqliteNetworkController.cpp b/controller/SqliteNetworkController.cpp index 5283b5ae5..b0a826c01 100644 --- a/controller/SqliteNetworkController.cpp +++ b/controller/SqliteNetworkController.cpp @@ -1059,7 +1059,27 @@ void SqliteNetworkController::threadMain() throw() { 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(); @@ -1104,6 +1124,7 @@ void SqliteNetworkController::threadMain() OSUtils::rm(backupPath2); ::rename(backupPath,backupPath2); } + Thread::sleep(250); } } @@ -1319,10 +1340,6 @@ unsigned int SqliteNetworkController::_doCPGet( responseBody.push_back(']'); responseContentType = "application/json"; - _node->circuitTestEnd(cte->second.test); - ::free((void *)cte->second.test); - _circuitTests.erase(cte); - return 200; } // else 404 diff --git a/controller/SqliteNetworkController.hpp b/controller/SqliteNetworkController.hpp index fe9bbcb84..11be9db47 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 { From 92f24d1988451fb99b24e89ab52dfa6ecae7e65f Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 22 Feb 2016 15:54:18 -0800 Subject: [PATCH 32/45] Make maximum size of a circuit test structure sane. --- include/ZeroTierOne.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/ZeroTierOne.h b/include/ZeroTierOne.h index 8a74eafa4..076e31fc2 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) From c7c61b4ac045c056336a732927b37293bc898f95 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Mon, 22 Feb 2016 16:01:35 -0800 Subject: [PATCH 33/45] Fix checking of path address validity. --- node/IncomingPacket.cpp | 4 ++-- node/Node.cpp | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/node/IncomingPacket.cpp b/node/IncomingPacket.cpp index 8a180380b..52eb76446 100644 --- a/node/IncomingPacket.cpp +++ b/node/IncomingPacket.cpp @@ -934,7 +934,7 @@ bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,const Sha switch(addrType) { case 4: { InetAddress a(field(ptr,4),4,at(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); @@ -945,7 +945,7 @@ bool IncomingPacket::_doPUSH_DIRECT_PATHS(const RuntimeEnvironment *RR,const Sha } break; case 6: { InetAddress a(field(ptr,16),16,at(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); diff --git a/node/Node.cpp b/node/Node.cpp index bdeca7013..2e208a426 100644 --- a/node/Node.cpp +++ b/node/Node.cpp @@ -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 > >::const_iterator i=_networks.begin();i!=_networks.end();++i) { From 7b5c1696eb337ce92b5b607257e2a64eec98dca4 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Tue, 23 Feb 2016 14:56:51 -0800 Subject: [PATCH 34/45] Fix a CIRCUIT_TEST bug in forwarding of tests along hop paths on private networks. Unfortunately this means full circuit testing for private nets will need an upgrade. :( --- node/IncomingPacket.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/node/IncomingPacket.cpp b/node/IncomingPacket.cpp index 52eb76446..e84462f54 100644 --- a/node/IncomingPacket.cpp +++ b/node/IncomingPacket.cpp @@ -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 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()); @@ -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(previousHopCredentialPos,(uint16_t)(size() - previousHopCredentialPos)); + outp.setAt(previousHopCredentialPos,(uint16_t)(outp.size() - (previousHopCredentialPos + 2))); } if (remainingHopsPtr < size()) outp.append(field(remainingHopsPtr,size() - remainingHopsPtr),size() - remainingHopsPtr); From 3fe60615dfa0de52bcd6304ce93aadebe3bdca93 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 24 Feb 2016 15:23:49 -0800 Subject: [PATCH 35/45] Make installers silent when run inside packages. --- ext/installfiles/linux/RPM/zerotier-one.spec.in | 4 ++-- ext/installfiles/linux/buildinstaller.sh | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ext/installfiles/linux/RPM/zerotier-one.spec.in b/ext/installfiles/linux/RPM/zerotier-one.spec.in index a5445ba53..1ec3d42a3 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/buildinstaller.sh b/ext/installfiles/linux/buildinstaller.sh index 1f6f89355..21f2f73ed 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 From a5e4e3fcac21ed26743f343b43baf7a12199c576 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Wed, 24 Feb 2016 17:24:36 -0800 Subject: [PATCH 36/45] Remove ui/ on Linux uninstall. --- ext/installfiles/linux/uninstall.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/installfiles/linux/uninstall.sh b/ext/installfiles/linux/uninstall.sh index bfc7ee6b5..d9495a18f 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..." From e5f82f545755f582fc576aa7c583689403d8fe8a Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 25 Feb 2016 10:08:30 -0800 Subject: [PATCH 37/45] cleanup --- examples/api/README.md | 26 ----------------------- examples/api/circuit-test-pingpong.json | 13 ------------ examples/api/public.json | 27 ------------------------ examples/docker/Dockerfile | 19 ----------------- examples/docker/README.md | 8 ------- examples/docker/main.sh | 25 ---------------------- examples/docker/maketestenv.sh | 11 ---------- ext/installfiles/linux/DEBIAN/control.in | 5 +++-- 8 files changed, 3 insertions(+), 131 deletions(-) delete mode 100644 examples/api/README.md delete mode 100644 examples/api/circuit-test-pingpong.json delete mode 100644 examples/api/public.json delete mode 100644 examples/docker/Dockerfile delete mode 100644 examples/docker/README.md delete mode 100644 examples/docker/main.sh delete mode 100755 examples/docker/maketestenv.sh diff --git a/examples/api/README.md b/examples/api/README.md deleted file mode 100644 index 50b1b65e5..000000000 --- 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 8fcc5d944..000000000 --- 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 4317bd3e2..000000000 --- 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 f1ce6bb50..000000000 --- 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 fbc93481c..000000000 --- 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 53fb65408..000000000 --- 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 275692e15..000000000 --- a/examples/docker/maketestenv.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash - -if [ -z "$1" -o -z "$2" ]; then - echo 'Usage: maketestenv.sh ' - exit 1 -fi - -newid=`../../zerotier-idtool generate` - -echo "ZEROTIER_IDENTITY_SECRET=$newid" >$1 -echo "ZEROTIER_NETWORK=$2" >>$1 diff --git a/ext/installfiles/linux/DEBIAN/control.in b/ext/installfiles/linux/DEBIAN/control.in index dab6587f5..d1b5a8c16 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. From 039790cf267cb67a5130fb82caf97998d8b0959e Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 25 Feb 2016 15:39:15 -0800 Subject: [PATCH 38/45] Upgrade LZ4 to hopefully fix wacky sporadic crash when built with g++ 5.3.1 on Debian/testing. --- ext/lz4/lz4.c | 643 +++++++++++++++++++++++++++++++------------------- ext/lz4/lz4.h | 214 ++++++++++------- 2 files changed, 525 insertions(+), 332 deletions(-) diff --git a/ext/lz4/lz4.c b/ext/lz4/lz4.c index 881d1af02..08cf6b5cd 100644 --- a/ext/lz4/lz4.c +++ b/ext/lz4/lz4.c @@ -34,7 +34,7 @@ /************************************** - Tuning parameters +* Tuning parameters **************************************/ /* * HEAPMODE : @@ -44,50 +44,15 @@ #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 @@ -97,15 +62,15 @@ #endif +/************************************** +* Includes +**************************************/ +#include "lz4.h" + + /************************************** * Compiler Options **************************************/ -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */ -/* "restrict" is a known keyword */ -#else -# define restrict /* Disable restrict */ -#endif - #ifdef _MSC_VER /* Visual Studio */ # define FORCE_INLINE static __forceinline # include @@ -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 /* 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 @@ -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; } @@ -422,13 +343,6 @@ static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1)); static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */ -/************************************** -* Local Utils -**************************************/ -int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; } -int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); } - - /************************************** * Local Structures and types **************************************/ @@ -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<> (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<= 255 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; } - else *op++ = (BYTE)(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<= 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) { -#if (HEAPMODE) - void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8); /* Aligned on 8-bytes boundaries */ -#else - U64 ctx[LZ4_STREAMSIZE_U64] = {0}; /* Ensure data is aligned on 8-bytes boundaries */ -#endif - int result; + 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) - result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue); + return LZ4_compress_generic(&ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); else - result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue); + 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_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<= 255 ; len-=255) *op++ = 255; + *op++ = (BYTE)len; + } + else *token = (BYTE)(litLength< 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<= 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(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ +#else + LZ4_stream_t ctxBody; + void* ctx = &ctxBody; +#endif + + 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 de43fc0a2..3e7400225 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_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_fast (const char* source, char* dest, int sourceSize, int maxDestSize, int acceleration); /* -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 -*/ -int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize); - - -/* -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) From f217ce7ff748b0aa4c60fdd93287fcf7792b5462 Mon Sep 17 00:00:00 2001 From: Adam Ierymenko Date: Thu, 25 Feb 2016 18:13:42 -0800 Subject: [PATCH 39/45] Upgrade http-parser. --- ext/http-parser/http_parser.c | 144 ++++++++++++++++++++++++++++------ ext/http-parser/http_parser.h | 60 +++++++++----- 2 files changed, 161 insertions(+), 43 deletions(-) diff --git a/ext/http-parser/http_parser.c b/ext/http-parser/http_parser.c index aa6310f74..98e0b9f24 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 99c533ae4..e33c0620a 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 -#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 #include 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, From bf3e31ece77bcbf82ab6fdd66eef7f1a64a862fb Mon Sep 17 00:00:00 2001 From: Kristof Imre Szabo Date: Sat, 27 Feb 2016 23:55:14 +0100 Subject: [PATCH 40/45] Initial commit of the standard zerotier RPM specification --- ext/installfiles/linux/RPM/README.md | 20 +++ ext/installfiles/linux/RPM/zerotier.spec | 194 +++++++++++++++++++++++ 2 files changed, 214 insertions(+) create mode 100644 ext/installfiles/linux/RPM/README.md create mode 100755 ext/installfiles/linux/RPM/zerotier.spec diff --git a/ext/installfiles/linux/RPM/README.md b/ext/installfiles/linux/RPM/README.md new file mode 100644 index 000000000..5647cddec --- /dev/null +++ b/ext/installfiles/linux/RPM/README.md @@ -0,0 +1,20 @@ +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 architecture. + +#zerotier.spec +This spec file is a "standard" RPM spec file which enables building an SRPM package from the ZeroTier sources. This makes possible to compile the software on different architectures in a standard way. The spec file supports two packages: the standard zerotier and the zerotier-controller too. It supports 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 enabled +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 this. + + + diff --git a/ext/installfiles/linux/RPM/zerotier.spec b/ext/installfiles/linux/RPM/zerotier.spec new file mode 100755 index 000000000..41230f0e3 --- /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 1.1.4-1 +- initial package From 8118630861af532732822ed6a84ea544f35e520d Mon Sep 17 00:00:00 2001 From: Kristof Imre Szabo Date: Sun, 28 Feb 2016 00:00:55 +0100 Subject: [PATCH 41/45] Formatting change --- ext/installfiles/linux/RPM/README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ext/installfiles/linux/RPM/README.md b/ext/installfiles/linux/RPM/README.md index 5647cddec..fab585604 100644 --- a/ext/installfiles/linux/RPM/README.md +++ b/ext/installfiles/linux/RPM/README.md @@ -6,14 +6,14 @@ This file contains the information to build an RPM from the bash based binary in #zerotier.spec This spec file is a "standard" RPM spec file which enables building an SRPM package from the ZeroTier sources. This makes possible to compile the software on different architectures in a standard way. The spec file supports two packages: the standard zerotier and the zerotier-controller too. It supports 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 enabled -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 +> `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 +####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 this. From b836228465b4c93641e745401b4f0b26e1aeee3f Mon Sep 17 00:00:00 2001 From: Kristof Imre Szabo Date: Sun, 28 Feb 2016 00:02:48 +0100 Subject: [PATCH 42/45] Formatting change --- ext/installfiles/linux/RPM/README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/ext/installfiles/linux/RPM/README.md b/ext/installfiles/linux/RPM/README.md index fab585604..47c6a6914 100644 --- a/ext/installfiles/linux/RPM/README.md +++ b/ext/installfiles/linux/RPM/README.md @@ -1,15 +1,19 @@ -This folder contains two spec files which enable building of various RPM packages for zerotier. +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 architecture. #zerotier.spec -This spec file is a "standard" RPM spec file which enables building an SRPM package from the ZeroTier sources. This makes possible to compile the software on different architectures in a standard way. The spec file supports two packages: the standard zerotier and the zerotier-controller too. It supports the build options exposed in the original Linux makefile: +This spec file is a "standard" RPM spec file which enables building an SRPM package from the ZeroTier sources. This makes possible to compile the software on different architectures in a standard way. The spec file supports two packages: the standard zerotier and the zerotier-controller too. 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 From 45c233c0e7505b3c6c2f1031a6266ff4829a5e80 Mon Sep 17 00:00:00 2001 From: Kristof Imre Szabo Date: Sun, 28 Feb 2016 00:04:18 +0100 Subject: [PATCH 43/45] Formatting change --- ext/installfiles/linux/RPM/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/installfiles/linux/RPM/README.md b/ext/installfiles/linux/RPM/README.md index 47c6a6914..32a301920 100644 --- a/ext/installfiles/linux/RPM/README.md +++ b/ext/installfiles/linux/RPM/README.md @@ -4,7 +4,7 @@ This folder contains two spec files which enable building of various RPM package 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 architecture. #zerotier.spec -This spec file is a "standard" RPM spec file which enables building an SRPM package from the ZeroTier sources. This makes possible to compile the software on different architectures in a standard way. The spec file supports two packages: the standard zerotier and the zerotier-controller too. It supports some of the build options exposed in the original Linux makefile: +This spec file is a “standard” RPM spec file which enables building an SRPM package from the ZeroTier sources. This makes possible to compile the software on different architectures in a standard way. The spec file supports two packages: the standard zerotier and the zerotier-controller too. 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 From f8d05eb6259fa8ee67b22fad5607fa57c5bba573 Mon Sep 17 00:00:00 2001 From: Kristof Imre Szabo Date: Sun, 28 Feb 2016 17:05:43 +0100 Subject: [PATCH 44/45] Spec description rephrased. --- ext/installfiles/linux/RPM/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ext/installfiles/linux/RPM/README.md b/ext/installfiles/linux/RPM/README.md index 32a301920..54bb7faa4 100644 --- a/ext/installfiles/linux/RPM/README.md +++ b/ext/installfiles/linux/RPM/README.md @@ -4,7 +4,7 @@ This folder contains two spec files which enable building of various RPM package 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 architecture. #zerotier.spec -This spec file is a “standard” RPM spec file which enables building an SRPM package from the ZeroTier sources. This makes possible to compile the software on different architectures in a standard way. The spec file supports two packages: the standard zerotier and the zerotier-controller too. It supports some of the build options exposed in the original Linux makefile: +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 @@ -18,7 +18,7 @@ This spec file is a “standard” RPM spec file which enables building an SRPM ####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 this. +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. From 6d1dc473686c7067cd89d24fd9d9945f429ed03a Mon Sep 17 00:00:00 2001 From: Kristof Imre Szabo Date: Sun, 28 Feb 2016 17:06:46 +0100 Subject: [PATCH 45/45] Typo fix. --- ext/installfiles/linux/RPM/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/installfiles/linux/RPM/README.md b/ext/installfiles/linux/RPM/README.md index 54bb7faa4..21ad0a1b9 100644 --- a/ext/installfiles/linux/RPM/README.md +++ b/ext/installfiles/linux/RPM/README.md @@ -1,7 +1,7 @@ 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 architecture. +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: