Merge pull request #1376 from loki-project/dev

0.8.0
pull/1388/head
Jason Rhinelander 4 years ago committed by GitHub
commit 98463b9c11
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,6 +1,6 @@
BasedOnStyle: Google
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: 'true'
AlignAfterOpenBracket: AlwaysBreak
AlignConsecutiveAssignments: 'false'
AlignConsecutiveDeclarations: 'false'
AlignEscapedNewlinesLeft: 'true'
AlignOperands: 'false'
@ -19,14 +19,22 @@ BreakBeforeTernaryOperators: 'true'
BreakConstructorInitializersBeforeComma: 'true'
Cpp11BracedListStyle: 'true'
KeepEmptyLinesAtTheStartOfBlocks: 'false'
Language: Cpp
NamespaceIndentation: All
PenaltyBreakString: '3'
SpaceBeforeParens: Never
SpacesInAngles: 'true'
SpaceBeforeParens: ControlStatements
SpacesInAngles: 'false'
SpacesInContainerLiterals: 'false'
SpacesInParentheses: 'false'
SpacesInSquareBrackets: 'false'
Standard: Cpp11
UseTab: Never
SortIncludes: false
SortIncludes: false
ColumnLimit: 100
# treat pointers and reference declarations as if part of the type
DerivePointerAlignment: false
PointerAlignment: Left
# when wrapping function calls/declarations, force each parameter to have its own line
BinPackParameters: 'false'
BinPackArguments: 'false'

@ -0,0 +1,243 @@
local default_deps_base='libsystemd-dev python3-dev libcurl4-openssl-dev libuv1-dev libunbound-dev nettle-dev libssl-dev libevent-dev libsqlite3-dev';
local default_deps_nocxx='libsodium-dev ' + default_deps_base; // libsodium-dev needs to be >= 1.0.18
local default_deps='g++ ' + default_deps_nocxx; // g++ sometimes needs replacement
local default_windows_deps='mingw-w64-binutils mingw-w64-gcc mingw-w64-crt mingw-w64-headers mingw-w64-winpthreads perl openssh zip bash'; // deps for windows cross compile
local submodules = {
name: 'submodules',
image: 'drone/git',
commands: ['git fetch --tags', 'git submodule update --init --recursive']
};
// Regular build on a debian-like system:
local debian_pipeline(name, image,
arch='amd64',
deps=default_deps,
build_type='Release',
lto=false,
werror=true,
cmake_extra='',
extra_cmds=[],
imaginary_repo=false,
allow_fail=false) = {
kind: 'pipeline',
type: 'docker',
name: name,
platform: { arch: arch },
trigger: { branch: { exclude: ['debian/*', 'ubuntu/*'] } },
steps: [
submodules,
{
name: 'build',
image: image,
[if allow_fail then "failure"]: "ignore",
environment: { SSH_KEY: { from_secret: "SSH_KEY" } },
commands: [
'echo "man-db man-db/auto-update boolean false" | debconf-set-selections',
'apt-get update',
'apt-get install -y eatmydata',
'eatmydata apt-get dist-upgrade -y',
] + (if imaginary_repo then [
'eatmydata apt-get install -y gpg curl lsb-release',
'echo deb https://deb.imaginary.stream $$(lsb_release -sc) main >/etc/apt/sources.list.d/imaginary.stream.list',
'curl -s https://deb.imaginary.stream/public.gpg | apt-key add -',
'eatmydata apt-get update'
] else []
) + [
'eatmydata apt-get install -y gdb cmake git ninja-build pkg-config ccache ' + deps,
'mkdir build',
'cd build',
'cmake .. -G Ninja -DCMAKE_CXX_FLAGS=-fdiagnostics-color=always -DCMAKE_BUILD_TYPE='+build_type+' ' +
(if werror then '-DWARNINGS_AS_ERRORS=ON ' else '') +
(if lto then '' else '-DWITH_LTO=OFF ') +
cmake_extra,
'ninja -v',
'../contrib/ci/drone-gdb.sh ./test/testAll --gtest_color=yes',
'../contrib/ci/drone-gdb.sh ./test/catchAll --use-colour yes',
] + extra_cmds,
}
],
};
// windows cross compile on alpine linux
local windows_cross_pipeline(name, image,
arch='amd64',
deps=default_windows_deps,
build_type='Release',
lto=false,
werror=false,
cmake_extra='',
toolchain='32',
extra_cmds=[],
allow_fail=false) = {
kind: 'pipeline',
type: 'docker',
name: name,
platform: { arch: arch },
trigger: { branch: { exclude: ['debian/*', 'ubuntu/*'] } },
steps: [
submodules,
{
name: 'build',
image: image,
[if allow_fail then "failure"]: "ignore",
environment: { SSH_KEY: { from_secret: "SSH_KEY" }, WINDOWS_BUILD_NAME: toolchain+"bit" },
commands: [
'apk update && apk upgrade',
'apk add cmake git ninja pkgconf ccache patch make ' + deps,
'git clone https://github.com/despair86/libuv.git win32-setup/libuv',
'mkdir build',
'cd build',
'cmake .. -G Ninja -DCMAKE_CROSSCOMPILE=ON -DCMAKE_EXE_LINKER_FLAGS=-fstack-protector -DLIBUV_ROOT=$PWD/../win32-setup/libuv -DCMAKE_CXX_FLAGS=-fdiagnostics-color=always -DCMAKE_TOOLCHAIN_FILE=../contrib/cross/mingw'+toolchain+'.cmake -DCMAKE_BUILD_TYPE='+build_type+' ' +
(if werror then '-DWARNINGS_AS_ERRORS=ON ' else '') +
(if lto then '' else '-DWITH_LTO=OFF ') +
"-DBUILD_STATIC_DEPS=ON -DDOWNLOAD_SODIUM=ON -DBUILD_PACKAGE=OFF -DBUILD_SHARED_LIBS=OFF -DBUILD_TESTING=ON -DNATIVE_BUILD=OFF -DSTATIC_LINK=ON" +
cmake_extra,
'ninja -v',
] + extra_cmds,
}
],
};
// Builds a snapshot .deb on a debian-like system by merging into the debian/* or ubuntu/* branch
local deb_builder(image, distro, distro_branch, arch='amd64', imaginary_repo=false) = {
kind: 'pipeline',
type: 'docker',
name: 'DEB (' + distro + (if arch == 'amd64' then '' else '/' + arch) + ')',
platform: { arch: arch },
environment: { distro_branch: distro_branch, distro: distro },
steps: [
submodules,
{
name: 'build',
image: image,
failure: 'ignore',
environment: { SSH_KEY: { from_secret: "SSH_KEY" } },
commands: [
'echo "man-db man-db/auto-update boolean false" | debconf-set-selections',
'apt-get update',
'apt-get install -y eatmydata',
'eatmydata apt-get install -y git devscripts equivs ccache git-buildpackage python3-dev' + (if imaginary_repo then ' gpg' else'')
] + (if imaginary_repo then [ // Some distros need the imaginary.stream repo for backported sodium, etc.
'echo deb https://deb.imaginary.stream $${distro} main >/etc/apt/sources.list.d/imaginary.stream.list',
'curl -s https://deb.imaginary.stream/public.gpg | apt-key add -',
'eatmydata apt-get update'
] else []) + [
|||
# Look for the debian branch in this repo first, try upstream if that fails.
if ! git checkout $${distro_branch}; then
git remote add --fetch upstream https://github.com/loki-project/loki-network.git &&
git checkout $${distro_branch}
fi
|||,
'git merge ${DRONE_COMMIT}',
'export DEBEMAIL="${DRONE_COMMIT_AUTHOR_EMAIL}" DEBFULLNAME="${DRONE_COMMIT_AUTHOR_NAME}"',
'gbp dch -S -s "HEAD^" --spawn-editor=never -U low',
'eatmydata mk-build-deps --install --remove --tool "apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends -y"',
'export DEB_BUILD_OPTIONS="parallel=$$(nproc)"',
'grep -q lib debian/lokinet-bin.install || echo "/usr/lib/lib*.so*" >>debian/lokinet-bin.install',
'debuild -e CCACHE_DIR -b',
'pwd',
'find ./contrib/ci',
'./contrib/ci/drone-debs-upload.sh ' + distro,
]
}
]
};
// Macos build
local mac_builder(name, build_type='Release', werror=true, cmake_extra='', extra_cmds=[], allow_fail=false) = {
kind: 'pipeline',
type: 'exec',
name: name,
platform: { os: 'darwin', arch: 'amd64' },
steps: [
{ name: 'submodules', commands: ['git fetch --tags', 'git submodule update --init --recursive'] },
{
name: 'build',
environment: { SSH_KEY: { from_secret: "SSH_KEY" } },
commands: [
// If you don't do this then the C compiler doesn't have an include path containing
// basic system headers. WTF apple:
'export SDKROOT="$(xcrun --sdk macosx --show-sdk-path)"',
'mkdir build',
'cd build',
'cmake .. -G Ninja -DCMAKE_CXX_FLAGS=-fcolor-diagnostics -DCMAKE_BUILD_TYPE='+build_type+' ' +
(if werror then '-DWARNINGS_AS_ERRORS=ON ' else '') + cmake_extra,
'ninja -v',
'./test/testAll --gtest_color=yes',
'./test/catchAll --use-colour yes',
] + extra_cmds,
}
]
};
[
{
name: 'lint check',
kind: 'pipeline',
type: 'docker',
steps: [{
name: 'build', image: 'debian:sid',
commands: [
'apt-get update', 'apt-get install -y eatmydata',
'eatmydata apt-get install -y git clang-format-9',
'./contrib/ci/drone-format-verify.sh']
}]
},
// Various debian builds
debian_pipeline("Debian sid (amd64)", "debian:sid", lto=true),
debian_pipeline("Debian sid/Debug (amd64)", "debian:sid", build_type='Debug', lto=true),
debian_pipeline("Debian sid/clang-10 (amd64)", "debian:sid", deps='clang-10 '+default_deps_nocxx,
cmake_extra='-DCMAKE_C_COMPILER=clang-10 -DCMAKE_CXX_COMPILER=clang++-10 ', lto=true),
debian_pipeline("Debian buster (i386)", "i386/debian:buster", cmake_extra='-DDOWNLOAD_SODIUM=ON'),
debian_pipeline("Ubuntu focal (amd64)", "ubuntu:focal"),
debian_pipeline("Ubuntu bionic (amd64)", "ubuntu:bionic", deps='g++-8 ' + default_deps_nocxx,
cmake_extra='-DCMAKE_C_COMPILER=gcc-8 -DCMAKE_CXX_COMPILER=g++-8', imaginary_repo=true),
// ARM builds (ARM64 and armhf)
debian_pipeline("Debian sid (ARM64)", "debian:sid", arch="arm64"),
debian_pipeline("Debian buster (armhf)", "arm32v7/debian:buster", arch="arm64", cmake_extra='-DDOWNLOAD_SODIUM=ON'),
// Windows builds (WOW64 and native)
windows_cross_pipeline("win32 on alpine (amd64)", "alpine:edge",
toolchain='64', extra_cmds=[
'../contrib/ci/drone-static-upload.sh'
]),
windows_cross_pipeline("win32 on alpine (i386)", "i386/alpine:edge",
toolchain='32', extra_cmds=[
'../contrib/ci/drone-static-upload.sh'
]),
// Static build (on bionic) which gets uploaded to builds.lokinet.dev:
debian_pipeline("Static (bionic amd64)", "ubuntu:bionic", deps='g++-8 python3-dev', lto=true,
cmake_extra='-DBUILD_STATIC_DEPS=ON -DBUILD_SHARED_LIBS=OFF -DSTATIC_LINK=ON -DCMAKE_C_COMPILER=gcc-8 -DCMAKE_CXX_COMPILER=g++-8 ' +
'-DDOWNLOAD_SODIUM=ON -DDOWNLOAD_CURL=ON -DDOWNLOAD_UV=ON -DWITH_SYSTEMD=OFF',
extra_cmds=[
'../contrib/ci/drone-check-static-libs.sh',
'../contrib/ci/drone-static-upload.sh'
]),
// integration tests
debian_pipeline("Router Hive", "ubuntu:focal", deps='python3-dev python3-pytest python3-pybind11 ' + default_deps,
cmake_extra='-DWITH_HIVE=ON'),
// Deb builds:
deb_builder("debian:sid", "sid", "debian/sid"),
deb_builder("debian:buster", "buster", "debian/buster", imaginary_repo=true),
deb_builder("ubuntu:focal", "focal", "ubuntu/focal"),
deb_builder("debian:sid", "sid", "debian/sid", arch='arm64'),
// Macos builds:
mac_builder('macOS (Release)'),
mac_builder('macOS (Debug)', build_type='Debug'),
mac_builder('macOS (Static)', cmake_extra='-DBUILD_STATIC_DEPS=ON -DBUILD_SHARED_LIBS=OFF -DSTATIC_LINK=ON -DDOWNLOAD_SODIUM=FORCE -DDOWNLOAD_CURL=FORCE -DDOWNLOAD_UV=FORCE',
extra_cmds=[
'../contrib/ci/drone-check-static-libs.sh',
'../contrib/ci/drone-static-upload.sh'
]),
]

1
.gitignore vendored

@ -7,6 +7,7 @@
*.so
build/
**/__pycache__/**
llarpd
*.test

@ -1,116 +0,0 @@
variables:
GIT_STRATEGY: fetch
GIT_SUBMODULE_STRATEGY: recursive
stages:
- build
- test
# disabled because gcc9 can't build net_if.hpp
#build:linux:
# image: alpine:latest
# tags:
# - linux
# stage: build
# before_script:
# - apk add --update g++ make cmake linux-headers libcap-dev libuv-dev curl-dev git
# script:
# - make STATIC_LINK=ON DOWNLOAD_SODIUM=ON
# artifacts:
# paths:
# - "lokinet"
# we'll just try our travis set up for now
build:linux_release:
image: ubuntu:xenial
tags:
- linux
stage: build
before_script:
- apt-get update && apt-get install -y apt-transport-https curl
- curl https://apt.kitware.com/keys/kitware-archive-latest.asc | apt-key add -
- echo 'deb https://apt.kitware.com/ubuntu/ xenial main' >/etc/apt/sources.list.d/kitware.list
- apt-get update && apt-get install -y build-essential ca-certificates cmake curl git libcap-dev pkg-config wget xz-utils
script:
- make static DOWNLOAD_SODIUM=ON
# alternatively: git describe --tag
- LOKINET_VERSION=$(./lokinet-static --version|sed s/lokinet-//)
- echo lokinet-linux-x64-v$LOKINET_VERSION
- mkdir lokinet-linux-x64-v$LOKINET_VERSION
- cp lokinet-bootstrap lokinet-linux-x64-v$LOKINET_VERSION
- cp build/daemon/lokinet lokinet-linux-x64-v$LOKINET_VERSION
- cp build/daemon/lokinetctl lokinet-linux-x64-v$LOKINET_VERSION
- cp docs/linux-setcap-readme.txt lokinet-linux-x64-v$LOKINET_VERSION
- tar cJf lokinet-linux-x64-v$LOKINET_VERSION.tar.xz lokinet-linux-x64-v$LOKINET_VERSION
- echo "lokinet-linux-x64-v$LOKINET_VERSION.tar.xz should be ready"
artifacts:
paths:
- lokinet-linux-x64-v*.tar.xz
build:linux_debug:
image: ubuntu:xenial
tags:
- linux
stage: build
before_script:
- apt-get update && apt-get install -y apt-transport-https curl
- curl https://apt.kitware.com/keys/kitware-archive-latest.asc | apt-key add -
- echo 'deb https://apt.kitware.com/ubuntu/ xenial main' >/etc/apt/sources.list.d/kitware.list
- apt-get update && apt-get install -y build-essential ca-certificates cmake curl git libcap-dev libcurl4-openssl-dev libuv1-dev ninja-build
script:
- DOWNLOAD_SODIUM=ON IS_NOTIFICATION=1 STATIC_LINK=OFF make
artifacts:
paths:
- build/daemon/lokinet
- build/daemon/lokinetctl
build:win32:
image: ubuntu:bionic
tags:
- linux
stage: build
before_script:
- apt-get update && apt-get install -y build-essential cmake nsis git g++-mingw-w64
script:
- DOWNLOAD_SODIUM=ON IS_NOTIFICATION=1 STATIC_LINK=ON WINDOWS_ARCH=64 make windows
artifacts:
paths:
- build/lokinet-*.exe
build:macos:
tags:
- osx
stage: build
script:
- IS_NOTIFICATION=1 STATIC_LINK=ON DOWNLOAD_SODIUM=ON make mac
artifacts:
paths:
- build/*.pkg
- build/daemon/lokinet
# needs libuv and libcurl
#build:freebsd:
# tags:
# - freebsd
# stage: build
# script:
# - gmake DOWNLOAD_SODIUM=ON
# artifacts:
# paths:
# - "lokinet"
# need windows runner on lokiproject
#build:windows:
# tags:
# - windows
# stage: build
# script:
#- make static CC=gcc CXX=g++
# can't use STATIC because LTO doesn't work on cross-compiled targets
# -DSTATIC_LINK_RUNTIME=ON -DLIBUV_ROOT=libuv
# - cmake .. -G Ninja -DCMAKE_TOOLCHAIN_FILE=../contrib/cross/mingw[32].cmake -DDOWNLOAD_SODIUM=ON
# artifacts:
# paths:
# - "lokinet.exe"

21
.gitmodules vendored

@ -13,9 +13,24 @@
[submodule "test/Catch2"]
path = test/Catch2
url = https://github.com/catchorg/Catch2
[submodule "external/optional-lite"]
path = external/optional-lite
url = https://github.com/martinmoene/optional-lite.git
[submodule "external/date"]
path = external/date
url = https://github.com/HowardHinnant/date.git
[submodule "external/pybind11"]
path = external/pybind11
url = https://github.com/pybind/pybind11
branch = stable
[submodule "external/clang-format-hooks"]
path = external/clang-format-hooks
url = https://github.com/barisione/clang-format-hooks/
[submodule "external/libuv"]
path = external/libuv
url = https://github.com/libuv/libuv
branch = v1.x
[submodule "external/loki-mq"]
path = external/loki-mq
url = https://github.com/loki-project/loki-mq
branch = dev
[submodule "external/sqlite_orm"]
path = external/sqlite_orm
url = https://github.com/fnc12/sqlite_orm

@ -1,225 +0,0 @@
language: cpp
dist: bionic
osx_image: xcode11.3
cache: ccache
matrix:
fast_finish: true
include:
- name: "lint check"
os: linux
compiler: gcc
env: MAKE_TARGET=format-verify PATH="/usr/lib/llvm-8/bin:$PATH"
addons:
apt:
sources:
- llvm-toolchain-bionic-8
packages:
- clang-format-8
- name: "make debug (linux/gcc)"
os: linux
compiler: gcc
env: BUILD_TYPE=Debug IS_NOTIFICATION=1
addons: &core_apt_addons
apt:
packages:
- build-essential
- cmake
- curl
- git
- libcap-dev
- libcurl4-openssl-dev
- libuv1-dev
- ninja-build
- libsodium-dev
- libsystemd-dev
- name: "make release (linux/gcc)"
os: linux
compiler: gcc
env: BUILD_TYPE=Release
addons: *core_apt_addons
- name: "make release (old linux/gcc)"
os: linux
dist: xenial
compiler: gcc
env: BUILD_TYPE=Release
addons: *core_apt_addons
- name: "make debug (linux/clang)"
os: linux
compiler: clang
env: BUILD_TYPE=Debug
addons: *core_apt_addons
- name: "make release (linux/clang)"
os: linux
compiler: clang
env: BUILD_TYPE=Release
addons: *core_apt_addons
- name: "make debug (macOS/clang)"
os: osx
env: BUILD_TYPE=Debug PATH="/usr/local/opt/ccache/libexec:$PATH"
- name: "make release (macOS/clang)"
os: osx
env: BUILD_TYPE=Release PATH="/usr/local/opt/ccache/libexec:$PATH"
- name: "make release (linux/gcc/arm64)"
arch: arm64
compiler: gcc
env: BUILD_TYPE=Release
addons: *core_apt_addons
- name: "make release (linux/gcc/s390x)"
arch: s390x
compiler: gcc
env: BUILD_TYPE=Release
addons: *core_apt_addons
- name: "make release (linux/gcc/ppc64le)"
arch: ppc64le
compiler: gcc
env: BUILD_TYPE=Release
addons: *core_apt_addons
# - name: "make iOS"
# os: osx
# env: MAKE_TARGET=ios PATH="/usr/local/opt/ccache/libexec:$PATH"
# - name: "make windows (macOS)"
# os: osx
# env: MAKE_TARGET=windows PATH="/usr/local/opt/ccache/libexec:$PATH"
# - name: "make windows-release (macOS)"
# os: osx
# env: MAKE_TARGET=windows-release PATH="/usr/local/opt/ccache/libexec:$PATH"
# - name: "make release (macOS beta/clang)"
# os: osx
# env: BUILD_TYPE=Release PATH="/usr/local/opt/ccache/libexec:$PATH"
# - name: "address sanitizer"
# os: osx
# env: BUILD_TYPE=Debug XSAN=address PATH="/usr/local/opt/ccache/libexec:$PATH" CC=/usr/local/opt/llvm/bin/clang CXX=/usr/local/opt/llvm/bin/clang++
# - name: "thread sanitizer"
# os: osx
# env: BUILD_TYPE=Debug XSAN=thread PATH="/usr/local/opt/ccache/libexec:$PATH" CC=/usr/local/opt/llvm/bin/clang CXX=/usr/local/opt/llvm/bin/clang++
# - name: "undefined sanitizer"
# os: osx
# env: BUILD_TYPE=Debug XSAN=undefined PATH="/usr/local/opt/ccache/libexec:$PATH" CC=/usr/local/opt/llvm/bin/clang CXX=/usr/local/opt/llvm/bin/clang++
# - name: "memory sanitizer"
# os: linux
# compiler: clang
# env: BUILD_TYPE=Debug XSAN=memory
# addons: *core_apt_addons
# - name: "router docker image"
# os: linux
# dist: xenial
# env: DOCKER_FILE=docker/router.Dockerfile
# services: docker
- name: "make windows docker image"
os: linux
dist: xenial
env: DOCKER_FILE=docker/alpine-windows.Dockerfile
services: docker
- name: "gcc trunk"
os: linux
dist: xenial
env: DOCKER_FILE=docker/gcc-trunk.Dockerfile
services: docker
- name: "native windows debug"
os: windows
env: BUILD_TYPE=Debug
- name: "native windows release"
os: windows
env: BUILD_TYPE=Release
- name: "windows installer"
os: linux
env: MAKE_TARGET=windows STATIC_LINK=ON DOWNLOAD_SODIUM=ON
allow_failures:
- name: "windows installer"
os: linux
env: MAKE_TARGET=windows STATIC_LINK=ON DOWNLOAD_SODIUM=ON
- name: "make windows docker image"
os: linux
dist: xenial
env: DOCKER_FILE=docker/alpine-windows.Dockerfile
services: docker
- name: "native windows debug"
os: windows
env: BUILD_TYPE=Debug
- name: "native windows release"
os: windows
env: BUILD_TYPE=Release
# - name: "native windows debug"
# os: windows
# env: BUILD_TYPE=Debug
# - name: "native windows release"
# os: windows
# env: BUILD_TYPE=Release
allow_failures:
- name: "make windows docker image"
- name: "native windows debug"
- name: "native windows release"
- name: "router docker image"
- name: "gcc trunk"
- arch: ppc64le
env:
global:
- NINJA=ninja
- STATIC_LINK=OFF
addons:
apt:
packages:
- binutils-gold
- build-essential
- clang-format
- cmake
- curl
- docker-ce
- nsis
- g++-mingw-w64
- g++-mingw-w64-x86-64
- gcc-mingw-w64-base
- git
- libcap-dev
- libcurl4-openssl-dev
- libuv1-dev
- mingw-w64 mingw-w64-common
- ninja-build
- libsodium-dev
homebrew:
update: true
packages:
- ccache
- cmake
- curl
- libuv
- make
- ninja
- libsodium
before_install:
- if [ "$TRAVIS_OS_NAME" == "windows" ]; then
choco install curl make ninja;
choco upgrade cmake.install;
export CC="/c/Program Files/LLVM/bin/clang-cl";
export CXX="/c/Program Files/LLVM/bin/clang-cl";
fi
script:
- if [ "$TRAVIS_OS_NAME" == "windows" ]; then
cmd.exe /C '"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvarsall.bat" amd64 && make test';
elif [[ ! -z $DOCKER_FILE ]]; then
docker build -f $DOCKER_FILE .;
else
make DOWNLOAD_SODIUM=ON ${MAKE_TARGET:-test};
fi
after_script:
- echo $TRAVIS_COMMIT_RANGE
- echo $TRAVIS_COMMIT_LOG
notifications:
webhooks:
urls: $WEBHOOK_URL
irc:
on_success: change
on_failure: change
channels:
- "chat.freenode.net#llarp"
nick: lokinet-ci
template:
- "%{result} | %{repository}#%{build_number} (%{commit} : %{author}) | Build details : %{build_url}"

@ -1,23 +1,35 @@
cmake_minimum_required(VERSION 3.10) # bionic's cmake version
set(CMAKE_OSX_DEPLOYMENT_TARGET 10.13) # Has to be set before `project()`, and ignored on non-macos
# Has to be set before `project()`, and ignored on non-macos:
set(CMAKE_OSX_DEPLOYMENT_TARGET 10.14 CACHE STRING "macOS deployment target (Apple clang only)")
find_program(CCACHE_PROGRAM ccache)
if(CCACHE_PROGRAM)
set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "${CCACHE_PROGRAM}")
foreach(lang C CXX)
if(NOT DEFINED CMAKE_${lang}_COMPILER_LAUNCHER AND NOT CMAKE_${lang}_COMPILER MATCHES ".*/ccache")
message(STATUS "Enabling ccache for ${lang}")
set(CMAKE_${lang}_COMPILER_LAUNCHER ${CCACHE_PROGRAM} CACHE STRING "")
endif()
endforeach()
endif()
set(PROJECT_NAME lokinet)
project(${PROJECT_NAME}
VERSION 0.7.1
VERSION 0.8.0
DESCRIPTION "lokinet - IP packet onion router"
LANGUAGES C CXX)
set(RELEASE_MOTTO "I'll remember that..." CACHE STRING "Release motto")
set(RELEASE_MOTTO "Proof of soon" CACHE STRING "Release motto")
add_definitions(-DLLARP_VERSION_MAJOR=${lokinet_VERSION_MAJOR})
add_definitions(-DLLARP_VERSION_MINOR=${lokinet_VERSION_MINOR})
add_definitions(-DLLARP_VERSION_PATCH=${lokinet_VERSION_PATCH})
if(RELEASE_MOTTO)
add_definitions(-DLLARP_RELEASE_MOTTO="${RELEASE_MOTTO}")
endif()
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
# Core options
@ -25,40 +37,55 @@ option(USE_AVX2 "enable avx2 code" OFF)
option(USE_NETNS "enable networking namespace support. Linux only" OFF)
option(NATIVE_BUILD "optimise for host system and FPU" ON)
option(EMBEDDED_CFG "optimise for older hardware or embedded systems" OFF)
if (WIN32)
option(STATIC_LINK_RUNTIME "link statically against compiler runtime, standard library and pthreads" OFF)
else()
option(STATIC_LINK "link statically against dependencies" OFF)
endif()
option(BUILD_SHARED_LIBS "build lokinet libraries as shared libraries instead of static" ON)
option(SHADOW "use shadow testing framework. linux only" OFF)
option(XSAN "use sanitiser, if your system has it" OFF)
option(JEMALLOC "use jemalloc. Not required on BSD" OFF)
option(DEBIAN "build for debian" OFF)
option(XSAN "use sanitiser, if your system has it (requires -DCMAKE_BUILD_TYPE=Debug)" OFF)
option(WITH_JEMALLOC "use jemalloc as allocator" OFF)
option(TESTNET "testnet build" OFF)
option(WITH_SHARED "build shared library" OFF)
option(WITH_COVERAGE "generate coverage data" OFF)
option(USE_SHELLHOOKS "enable shell hooks on compile time (dangerous)" OFF)
option(WARNINGS_AS_ERRORS "treat all warnings as errors. turn off for development, on for release" OFF)
option(TRACY_ROOT "include tracy profiler source" OFF)
option(WITH_TESTS "build unit tests" ON)
#option(WITH_SYSTEMD ...) defined below
option(WITH_HIVE "build simulation stubs" OFF)
option(BUILD_PACKAGE "builds extra components for making an installer (with 'make package')" OFF)
include(cmake/enable_lto.cmake)
option(BUILD_STATIC_DEPS "Download, build, and statically link against core dependencies" OFF)
option(STATIC_LINK "link statically against dependencies" ${BUILD_STATIC_DEPS})
if(BUILD_STATIC_DEPS AND NOT STATIC_LINK)
message(FATAL_ERROR "Option BUILD_STATIC_DEPS requires STATIC_LINK to be enabled as well")
endif()
if(BUILD_STATIC_DEPS)
include(StaticBuild)
endif()
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE RelWithDebInfo)
endif()
include(CheckCXXSourceCompiles)
include(CheckLibraryExists)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
include(cmake/target_link_libraries_system.cmake)
include(cmake/add_import_library.cmake)
include(cmake/add_log_tag.cmake)
include(cmake/libatomic.cmake)
if (STATIC_LINK AND STATIC_LINK_RUNTIME)
message(FATAL "Cannot set both STATIC_LINK and STATIC_LINK_RUNTIME")
endif()
include(cmake/link_dep_libs.cmake)
if (STATIC_LINK)
set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX})
message(STATUS "setting static library suffix search")
endif()
include(cmake/basic_definitions.cmake)
add_definitions(-D${CMAKE_SYSTEM_NAME})
if(MSVC_VERSION)
enable_language(ASM_MASM)
@ -66,18 +93,21 @@ if(MSVC_VERSION)
add_definitions(-D_WIN32_WINNT=0x0600 -DNOMINMAX -DSODIUM_STATIC)
else()
enable_language(ASM)
endif(MSVC_VERSION)
endif()
include(cmake/solaris.cmake)
include(cmake/win32.cmake)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
# No in-source building
include(MacroEnsureOutOfSourceBuild)
macro_ensure_out_of_source_build("${PROJECT_NAME} requires an out-of-source build. Create a build directory and run 'cmake ${CMAKE_SOURCE_DIR} [options]'.")
# Always build PIC
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
include(cmake/unix.cmake)
include(cmake/check_for_std_optional.cmake)
include(cmake/check_for_std_filesystem.cmake)
if(NOT WIN32)
if(IOS OR ANDROID)
@ -93,52 +123,69 @@ if(NOT WIN32)
endif()
endif()
set(CMAKE_CXX_STANDARD 14)
find_package(PkgConfig REQUIRED)
if(NOT TARGET sodium)
# Allow -D DOWNLOAD_SODIUM=FORCE to download without even checking for a local libsodium
option(DOWNLOAD_SODIUM "Allow libsodium to be downloaded and built locally if not found on the system" OFF)
if(NOT DOWNLOAD_SODIUM STREQUAL "FORCE" AND NOT BUILD_STATIC_DEPS)
pkg_check_modules(SODIUM libsodium>=1.0.18 IMPORTED_TARGET)
endif()
add_library(sodium INTERFACE)
if(SODIUM_FOUND AND NOT DOWNLOAD_SODIUM STREQUAL "FORCE" AND NOT BUILD_STATIC_DEPS)
target_link_libraries(sodium INTERFACE PkgConfig::SODIUM)
else()
if(NOT DOWNLOAD_SODIUM AND NOT BUILD_STATIC_DEPS)
message(FATAL_ERROR "Could not find libsodium >= 1.0.18; either install it on your system or use -DDOWNLOAD_SODIUM=ON to download and build an internal copy")
endif()
message(STATUS "Sodium >= 1.0.18 not found, but DOWNLOAD_SODIUM specified, so downloading it")
include(DownloadLibSodium)
target_link_libraries(sodium INTERFACE sodium_vendor)
endif()
# Need this target export so that loki-mq properly picks up sodium
export(TARGETS sodium NAMESPACE sodium:: FILE sodium-exports.cmake)
endif()
option(FORCE_LOKIMQ_SUBMODULE "force using lokimq submodule" OFF)
if(NOT FORCE_LOKIMQ_SUBMODULE)
pkg_check_modules(LOKIMQ liblokimq>=1.2)
endif()
if(LOKIMQ_FOUND)
add_library(lokimq INTERFACE)
link_dep_libs(lokimq INTERFACE "${LOKIMQ_LIBRARY_DIRS}" ${LOKIMQ_LIBRARIES})
target_include_directories(lokimq INTERFACE ${LOKIMQ_INCLUDE_DIRS})
add_library(lokimq::lokimq ALIAS lokimq)
message(STATUS "Found system liblokimq ${LOKIMQ_VERSION}")
else()
message(STATUS "using lokimq submodule")
add_subdirectory(${CMAKE_SOURCE_DIR}/external/loki-mq)
endif()
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
# this is messing with release builds
add_compile_options(-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0)
if (NOT ${CMAKE_SYSTEM_NAME} MATCHES "Linux" AND SHADOW)
if (NOT CMAKE_SYSTEM_NAME MATCHES "Linux" AND SHADOW)
message( FATAL_ERROR "shadow-framework is Linux only" )
endif(NOT ${CMAKE_SYSTEM_NAME} MATCHES "Linux" AND SHADOW)
if(NOT DEBIAN AND NOT MSVC_VERSION)
set(OPTIMIZE_FLAGS -O3)
set(DEBUG_FLAGS -O0 -g3)
endif()
if(XSAN)
set(DEBUG_FLAGS ${DEBUG_FLAGS} "-fsanitize=${XSAN}" -fno-omit-frame-pointer)
set(OPTIMIZE_FLAGS "-O0")
string(APPEND CMAKE_CXX_FLAGS_DEBUG " -fsanitize=${XSAN} -fno-omit-frame-pointer -fno-sanitize-recover")
foreach(type EXE MODULE SHARED STATIC)
string(APPEND CMAKE_${type}_LINKER_FLAGS_DEBUG " -fsanitize=${XSAN} -fno-omit-frame-pointer -fno-sanitize-recover")
endforeach()
message(STATUS "Doing a ${XSAN} sanitizer build")
endif(XSAN)
endif()
if(CMAKE_BUILD_TYPE MATCHES "[Dd][Ee][Bb][Uu][Gg]")
set(OPTIMIZE_FLAGS "")
add_definitions(-DLOKINET_DEBUG=1)
set(CRYPTO_FLAGS "")
add_compile_options( ${DEBUG_FLAGS} )
link_libraries( ${DEBUG_FLAGS} )
endif(CMAKE_BUILD_TYPE MATCHES "[Dd][Ee][Bb][Uu][Gg]")
# Add non-386 target-specific options here
if(NON_PC_TARGET)
add_definitions(-DRPI)
set(WITH_STATIC ON)
endif(NON_PC_TARGET)
endif()
if(WITH_SHELLHOOKS)
add_definitions(-DENABLE_SHELLHOOKS)
endif(WITH_SHELLHOOKS)
# Always build PIC
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
endif()
if(TRACY_ROOT)
include_directories(${TRACY_ROOT})
@ -158,64 +205,53 @@ if (NOT MSVC_VERSION)
add_compile_options(-Wno-unused-function -Wno-deprecated-declarations -Wno-unknown-pragmas)
endif()
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
# STREQUAL because AppleClang's libc++ doesn't yet support thread safety annotations
add_compile_options(-Wthread-safety)
endif()
include(cmake/coverage.cmake)
# these vars are set by the cmake toolchain spec
if (WOW64_CROSS_COMPILE OR WIN64_CROSS_COMPILE)
include(cmake/cross_compile.cmake)
endif(WOW64_CROSS_COMPILE OR WIN64_CROSS_COMPILE)
endif()
if(DEBIAN)
add_definitions(-DDEBIAN)
elseif(NATIVE_BUILD)
if(NATIVE_BUILD)
if(CMAKE_SYSTEM_PROCESSOR STREQUAL ppc64le)
set(CRYPTO_FLAGS -mcpu=native -mtune=native)
add_compile_options(-mcpu=native -mtune=native)
else()
set(CRYPTO_FLAGS -march=native -mtune=native)
add_compile_options(-march=native -mtune=native)
endif()
elseif(NOT NON_PC_TARGET)
if (USE_AVX2)
set(CRYPTO_FLAGS -march=haswell -mtune=haswell -mfpmath=sse)
add_compile_options(-march=haswell -mtune=haswell -mfpmath=sse)
else()
# Public binary releases
set(CRYPTO_FLAGS -march=nocona -mtune=haswell -mfpmath=sse)
add_compile_options(-march=nocona -mtune=haswell -mfpmath=sse)
endif()
endif()
if(EMBEDDED_CFG)
message(WARNING "This configuration is optimised for older hardware and/or constrained node operation, may result in poor performance on desktop systems")
message(WARNING "For deployment on such systems, all external code (currently, libuv) must also be compiled for the target!")
set(CRYPTO_FLAGS -march=i486 -mtune=i486)
add_compile_options(-march=i486 -mtune=i486)
endif()
add_compile_options(${OPTIMIZE_FLAGS} ${CRYPTO_FLAGS})
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
find_package(Threads REQUIRED)
include(cmake/static_link.cmake)
if(USE_NETNS)
add_definitions(-DNETNS=1)
else()
add_definitions(-DNETNS=0)
endif(USE_NETNS)
endif()
if(TESTNET)
add_definitions(-DTESTNET=1)
# 5 times slower than realtime
add_definitions(-DTESTNET_SPEED=5)
endif(TESTNET)
endif()
if(SHADOW)
include(cmake/shadow.cmake)
endif(SHADOW)
endif()
unset(GIT_VERSION)
unset(GIT_VERSION_REAL)
@ -223,34 +259,29 @@ unset(GIT_VERSION_REAL)
if(NOT GIT_VERSION)
exec_program("git" ${CMAKE_CURRENT_SOURCE_DIR} ARGS "rev-parse --short HEAD" OUTPUT_VARIABLE GIT_VERSION_UNSTRIP)
string(STRIP "${GIT_VERSION_UNSTRIP}" GIT_VERSION)
endif(NOT GIT_VERSION)
endif()
string(REGEX REPLACE "^fatal.*$" nogit GIT_VERSION_REAL "${GIT_VERSION}")
# HeapAlloc(2) on Windows was significantly revamped in 2009
# but the old algorithm isn't too bad either
# this is _the_ system allocator on BSD UNIX
# openbsd replaced it with a secure/randomised malloc not too
# long ago
if(JEMALLOC)
set(MALLOC_LIB jemalloc)
endif(JEMALLOC)
find_package(PkgConfig QUIET)
if(PKG_CONFIG_FOUND)
pkg_check_modules(SD libsystemd)
# Default WITH_SYSTEMD to true if we found it
option(WITH_SYSTEMD "enable systemd integration for sd_notify" ${SD_FOUND})
if(WITH_SYSTEMD)
if(NOT SD_FOUND)
message(FATAL_ERROR "libsystemd not found")
endif()
add_definitions(-DWITH_SYSTEMD)
include_directories(${SD_INCLUDE_DIRS})
set(SD_LIBS ${SD_LDFLAGS})
endif()
find_package(PkgConfig REQUIRED)
if (NOT BUILD_STATIC_DEPS)
pkg_check_modules(UNBOUND libunbound REQUIRED IMPORTED_TARGET)
add_library(libunbound INTERFACE)
target_link_libraries(libunbound INTERFACE PkgConfig::UNBOUND)
endif()
pkg_check_modules(SD libsystemd)
# Default WITH_SYSTEMD to true if we found it
option(WITH_SYSTEMD "enable systemd integration for sd_notify" ${SD_FOUND})
if(WITH_SYSTEMD AND (NOT ANDROID))
if(NOT SD_FOUND)
message(FATAL_ERROR "libsystemd not found")
endif()
add_definitions(-DWITH_SYSTEMD)
include_directories(${SD_INCLUDE_DIRS})
set(SD_LIBS ${SD_LDFLAGS})
endif()
option(SUBMODULE_CHECK "Enables checking that vendored library submodules are up to date" ON)
@ -273,11 +304,19 @@ if(SUBMODULE_CHECK)
check_submodule(external/googletest)
check_submodule(external/cxxopts)
check_submodule(external/ghc-filesystem)
check_submodule(external/optional-lite)
check_submodule(external/date)
check_submodule(external/pybind11)
check_submodule(external/sqlite_orm)
if (NOT WIN32) # we grab libuv for windows separately in win32-setup/libuv. see note in cmake/win32.cmake.
check_submodule(external/libuv)
endif()
check_submodule(external/loki-mq)
endif()
endif()
if(WITH_HIVE)
add_subdirectory(external/pybind11 EXCLUDE_FROM_ALL)
endif()
if(WITH_TESTS)
add_subdirectory(external/googletest EXCLUDE_FROM_ALL)
endif()
@ -285,33 +324,61 @@ endif()
set(JSON_BuildTests OFF CACHE INTERNAL "")
add_subdirectory(external/nlohmann EXCLUDE_FROM_ALL)
add_subdirectory(external/cxxopts EXCLUDE_FROM_ALL)
add_subdirectory(external/ghc-filesystem)
add_subdirectory(external/optional-lite EXCLUDE_FROM_ALL)
add_subdirectory(external/date EXCLUDE_FROM_ALL)
include_directories(SYSTEM external/sqlite_orm/include)
add_subdirectory(vendor)
if(ANDROID)
list(APPEND LIBS log)
add_definitions(-DANDROID)
set(ANDROID_PLATFORM_SRC android/ifaddrs.c)
endif(ANDROID)
endif()
set(LIBS ${MALLOC_LIB} ${LIBUV_LIBRARY} ${SD_LIBS})
if(TRACY_ROOT)
list(APPEND LIBS -ldl)
endif()
if(WITH_HIVE)
add_definitions(-DLOKINET_HIVE=1)
endif()
add_subdirectory(crypto)
add_subdirectory(llarp)
add_subdirectory(libabyss)
add_subdirectory(daemon)
if(WITH_HIVE)
add_subdirectory(pybind)
endif()
if (NOT SHADOW)
if(WITH_TESTS)
if(WITH_TESTS OR WITH_HIVE)
add_subdirectory(test)
endif()
if(ANDROID)
add_subdirectory(jni)
endif(ANDROID)
endif()
endif()
add_subdirectory(docs)
# uninstall target
if(NOT TARGET uninstall)
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
IMMEDIATE @ONLY)
add_custom_target(uninstall
COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake)
endif()
if(BUILD_PACKAGE)
include(cmake/installer.cmake)
endif()
if(BUILD_PACKAGE)

2482
Doxyfile

File diff suppressed because it is too large Load Diff

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

@ -1,370 +0,0 @@
REPO := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
NO_GIT := $(shell test -e $(REPO)/.git/ || echo 1)
ifeq ($(NO_GIT),1)
all: release
else
GIT_BRANCH ?= $(shell test -e $(REPO)/.git/ && git rev-parse --abbrev-ref HEAD)
ifeq ($(GIT_BRANCH),master)
all: release
else
all: test
endif
endif
BUILD_ROOT = $(REPO)/build
DESTDIR ?=
CC ?= cc
CXX ?= c++
BUILD_TYPE ?= Debug
PYTHON ?= python
PYTHON3 ?= python3
FORMAT ?= clang-format-8
SETCAP ?= which setcap && setcap cap_net_admin,cap_net_bind_service=+eip
SHADOW_ROOT ?= $(HOME)/.shadow
SHADOW_BIN=$(SHADOW_ROOT)/bin/shadow
SHADOW_CONFIG=$(REPO)/shadow.config.xml
SHADOW_PLUGIN=$(BUILD_ROOT)/libshadow-plugin-lokinet-shared.so
SHADOW_LOG=$(REPO)/shadow.log.txt
SHADOW_SRC ?= $(HOME)/local/shadow
SHADOW_PARSE ?= $(PYTHON) $(SHADOW_SRC)/src/tools/parse-shadow.py - -m 0 --packet-data
SHADOW_PLOT ?= $(PYTHON) $(SHADOW_SRC)/src/tools/plot-shadow.py -d $(REPO) LokiNET -c $(SHADOW_CONFIG) -r 10000 -e '.*'
SHADOW_OPTS ?=
LIBUV_VERSION ?= v1.30.1
LIBUV_PREFIX = $(BUILD_ROOT)/libuv
LIBCURL_PREFIX = $(BUILD_ROOT)/curl
LIBCURL_VERSION = 7.67.0
LIBCURL_URL = https://github.com/curl/curl/releases/download/curl-7_67_0/curl-7.67.0.tar.xz
LIBCURL_SHA256 = f5d2e7320379338c3952dcc7566a140abb49edb575f9f99272455785c40e536c
TESTNET_ROOT=/tmp/lokinet_testnet_tmp
TESTNET_CONF=$(TESTNET_ROOT)/supervisor.conf
TESTNET_LOG=$(TESTNET_ROOT)/testnet.log
TESTNET_VENV=$(TESTNET_ROOT)/v
TESTNET_EXE=$(REPO)/lokinet-testnet
TESTNET_CLIENTS ?= 50
TESTNET_SERVERS ?= 50
TESTNET_DEBUG ?= 0
TESTNET_IFNAME ?= lo
TESTNET_BASEPORT ?= 1900
TESTNET_IP ?= 127.0.0.1
TESTNET_NETID ?= loopback
ANDROID_NDK ?= $(HOME)/Android/Ndk
ANDROID_SDK ?= $(HOME)/Android/Sdk
ANDROID_ABI ?= armeabi-v7a
ANDROID_API_LEVEL ?= 24
ANDROID_DIR=$(REPO)/android
JNI_DIR=$(ANDROID_DIR)/jni
ANDROID_MK=$(JNI_DIR)/Android.mk
ANDROID_PROPS=$(ANDROID_DIR)/gradle.properties
ANDROID_LOCAL_PROPS=$(ANDROID_DIR)/local.properties
GRADLE ?= gradle
JAVA_HOME ?= /usr/lib/jvm/default-java
TOOLCHAIN ?=
# 64 for 64bit windows, 32 for 32bit windows
# defaults to 64 bit for now
WINDOWS_ARCH ?= 64
# native avx2 code
AVX2 ?= OFF
# statically link everything
STATIC_LINK ?= OFF
# statically link dependencies
STATIC ?= OFF
# enable network namespace isolation
NETNS ?= OFF
# enable shell hooks callbacks
SHELL_HOOKS ?= OFF
# cross compile?
CROSS ?= OFF
# build liblokinet-shared.so
SHARED_LIB ?= OFF
# enable generating coverage
COVERAGE ?= OFF
# allow downloading libsodium if >= 1.0.18 not installed
DOWNLOAD_SODIUM ?= OFF
COVERAGE_OUTDIR ?= "$(TMPDIR)/lokinet-coverage"
# tracy profiler
TRACY_ROOT ?=
# enable sanitizer
XSAN ?= False
# cmake generator type
CMAKE_GEN ?= Unix Makefiles
ifdef NINJA
MAKE = $(NINJA)
CMAKE_GEN = Ninja
endif
SCAN_BUILD ?= scan-build
UNAME = $(shell which uname)
COMMON_CMAKE_OPTIONS = -DSTATIC_LINK_RUNTIME=$(STATIC_LINK) -DUSE_NETNS=$(NETNS) -DUSE_AVX2=$(AVX2) -DWITH_SHARED=$(SHARED_LIB) -DDOWNLOAD_SODIUM=$(DOWNLOAD_SODIUM) -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DXSAN=$(XSAN)
ifeq ($(shell $(UNAME)),SunOS)
CONFIG_CMD = $(shell gecho -n "cd '$(BUILD_ROOT)' && " ; gecho -n "cmake -G'$(CMAKE_GEN)' -DCMAKE_CROSSCOMPILING=$(CROSS) -DUSE_SHELLHOOKS=$(SHELL_HOOKS) $(COMMON_CMAKE_OPTIONS) '$(REPO)'")
CONFIG_CMD_WINDOWS = $(shell gecho -n "cd '$(BUILD_ROOT)' && " ; gecho -n "cmake -G'$(CMAKE_GEN)' -DCMAKE_CROSSCOMPILING=ON -DUSE_SHELLHOOKS=$(SHELL_HOOKS) $(COMMON_CMAKE_OPTIONS) '$(REPO)'")
ANALYZE_CONFIG_CMD = $(shell gecho -n "cd '$(BUILD_ROOT)' && " ; gecho -n "$(SCAN_BUILD) cmake -G'$(CMAKE_GEN)' -DCMAKE_CROSSCOMPILING=$(CROSS) $(COMMON_CMAKE_OPTIONS) '$(REPO)'")
COVERAGE_CONFIG_CMD = $(shell gecho -n "cd '$(BUILD_ROOT)' && " ; gecho -n "cmake -G'$(CMAKE_GEN)' -DCMAKE_CROSSCOMPILING=$(CROSS) -DWITH_COVERAGE=yes $(COMMON_CMAKE_OPTIONS) '$(REPO)'")
else
CONFIG_CMD = $(shell /bin/echo -n "cd '$(BUILD_ROOT)' && " ; /bin/echo -n "cmake -G'$(CMAKE_GEN)' -DCMAKE_CROSSCOMPILING=$(CROSS) -DUSE_SHELLHOOKS=$(SHELL_HOOKS) -DTRACY_ROOT=$(TRACY_ROOT) $(COMMON_CMAKE_OPTIONS) '$(REPO)'")
CONFIG_CMD_WINDOWS = $(shell /bin/echo -n "cd '$(BUILD_ROOT)' && " ; /bin/echo -n "cmake -G'$(CMAKE_GEN)' -DCMAKE_CROSSCOMPILING=ON -DUSE_SHELLHOOKS=$(SHELL_HOOKS) $(COMMON_CMAKE_OPTIONS)")
ANALYZE_CONFIG_CMD = $(shell /bin/echo -n "cd '$(BUILD_ROOT)' && " ; /bin/echo -n "$(SCAN_BUILD) cmake -G'$(CMAKE_GEN)' -DCMAKE_CROSSCOMPILING=$(CROSS) $(COMMON_CMAKE_OPTIONS) '$(REPO)'")
COVERAGE_CONFIG_CMD = $(shell /bin/echo -n "cd '$(BUILD_ROOT)' && " ; /bin/echo -n "cmake -G'$(CMAKE_GEN)' -DCMAKE_CROSSCOMPILING=$(CROSS) -DWITH_COVERAGE=yes $(COMMON_CMAKE_OPTIONS) '$(REPO)'")
endif
TARGETS = $(REPO)/lokinet
SIGS = $(TARGETS:=.sig)
EXE = $(BUILD_ROOT)/daemon/lokinet
TEST_EXE = $(BUILD_ROOT)/test/testAll
ABYSS_EXE = $(BUILD_ROOT)/abyss-main
LINT_FILES = $(wildcard llarp/*.cpp)
LINT_CHECK = $(LINT_FILES:.cpp=.cpp-check)
clean: android-clean
rm -f $(TARGETS)
rm -rf $(BUILD_ROOT)
rm -f $(SHADOW_PLUGIN) $(SHADOW_CONFIG)
rm -f *.sig
rm -f *.a *.so
android-clean:
rm -rf $(ANDROID_DIR)/.externalNativeBuild
debug-configure:
mkdir -p '$(BUILD_ROOT)'
(test x$(TOOLCHAIN) = x && $(CONFIG_CMD) -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) -DCMAKE_C_FLAGS='$(CFLAGS)' -DCMAKE_CXX_FLAGS='$(CXXFLAGS)') || (test x$(TOOLCHAIN) != x && $(CONFIG_CMD) -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) -DCMAKE_C_FLAGS='$(CFLAGS)' -DCMAKE_CXX_FLAGS='$(CXXFLAGS)' -DCMAKE_TOOLCHAIN_FILE=$(TOOLCHAIN) )
release-configure: clean
mkdir -p '$(BUILD_ROOT)'
$(CONFIG_CMD) -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_FLAGS='$(CFLAGS)' -DCMAKE_CXX_FLAGS='$(CXXFLAGS)'
debug: debug-configure
$(MAKE) -C $(BUILD_ROOT)
cp $(EXE) $(REPO)/lokinet
release-compile: release-configure
$(MAKE) -C $(BUILD_ROOT)
strip $(EXE)
$(TARGETS): release-compile
release: $(TARGETS)
make -C '$(BUILD_ROOT)' check
shadow-configure: clean
mkdir -p $(BUILD_ROOT)
$(CONFIG_CMD) -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) -DSHADOW=ON
shadow-build: shadow-configure
$(MAKE) -C $(BUILD_ROOT)
shadow-run: shadow-build
$(PYTHON3) $(REPO)/contrib/shadow/genconf.py $(SHADOW_CONFIG)
cp $(SHADOW_PLUGIN) $(REPO)/libshadow-plugin-lokinet.so
$(SHADOW_BIN) $(SHADOW_OPTS) $(SHADOW_CONFIG) | $(SHADOW_PARSE)
shadow-plot: shadow-run
$(SHADOW_PLOT)
shadow: shadow-plot
testnet-clean: clean
rm -rf $(TESTNET_ROOT)
testnet-configure: testnet-clean
mkdir -p $(BUILD_ROOT)
$(CONFIG_CMD) -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) -DTESTNET=1
testnet-build: testnet-configure
$(MAKE) -C $(BUILD_ROOT)
$(TESTNET_VENV):
$(PYTHON3) -m venv $(TESTNET_VENV) --system-site-packages
$(TESTNET_VENV)/bin/pip install -r $(REPO)/contrib/testnet/requirements.txt
testnet: $(TESTNET_VENV)
cp $(EXE) $(TESTNET_EXE)
mkdir -p $(TESTNET_ROOT)
$(PYTHON3) $(REPO)/contrib/testnet/genconf.py --bin=$(TESTNET_EXE) --svc=$(TESTNET_SERVERS) --clients=$(TESTNET_CLIENTS) --dir=$(TESTNET_ROOT) --out $(TESTNET_CONF) --ifname=$(TESTNET_IFNAME) --baseport=$(TESTNET_BASEPORT) --ip=$(TESTNET_IP) --netid=$(TESTNET_NETID) --lokid='$(TESTNET_VENV)/bin/python $(REPO)/contrib/testnet/lokid.py'
LLARP_DEBUG=$(TESTNET_DEBUG) supervisord -n -d $(TESTNET_ROOT) -l $(TESTNET_LOG) -c $(TESTNET_CONF)
gtest: debug
test x$(CROSS) = xOFF && $(MAKE) -C $(BUILD_ROOT) rungtest || test x$(CROSS) = xON
catch: debug
test x$(CROSS) = xOFF && $(MAKE) -C $(BUILD_ROOT) catch || test x$(CROSS) = xON
check: debug
test x$(CROSS) = xOFF && $(MAKE) -C $(BUILD_ROOT) check || test x$(CROSS) = xON
test: check
static-configure: $(LIBUV_PREFIX) $(LIBCURL_PREFIX)
(test x$(TOOLCHAIN) = x && $(CONFIG_CMD) -DCMAKE_BUILD_TYPE=Release -DSTATIC_LINK=ON -DCMAKE_C_FLAGS='$(CFLAGS)' -DCMAKE_CXX_FLAGS='$(CXXFLAGS)' -DLIBUV_ROOT='$(LIBUV_PREFIX)' -DLIBCURL_ROOT='$(LIBCURL_PREFIX)' -DNATIVE_BUILD=OFF ) || (test x$(TOOLCHAIN) != x && $(CONFIG_CMD) -DCMAKE_BUILD_TYPE=Release -DSTATIC_LINK=ON -DCMAKE_C_FLAGS='$(CFLAGS)' -DCMAKE_CXX_FLAGS='$(CXXFLAGS)' -DLIBUV_ROOT='$(LIBUV_PREFIX)' -DLIBCURL_ROOT='$(LIBCURL_PREFIX)' -DCMAKE_TOOLCHAIN_FILE=$(TOOLCHAIN) -DNATIVE_BUILD=OFF )
static: static-configure
$(MAKE) -C '$(BUILD_ROOT)'
cp $(EXE) $(REPO)/lokinet-static
$(LIBCURL_PREFIX):
mkdir -p '$(BUILD_ROOT)'
wget '$(LIBCURL_URL)' -O '$(BUILD_ROOT)/curl.tar.xz'
bash -c 'sha256sum -c <<<"$(LIBCURL_SHA256) $(BUILD_ROOT)/curl.tar.xz"'
tar -xJf '$(BUILD_ROOT)/curl.tar.xz' -C '$(BUILD_ROOT)'
mv '$(BUILD_ROOT)/curl-$(LIBCURL_VERSION)' '$(LIBCURL_PREFIX)'
$(LIBUV_PREFIX):
mkdir -p $(BUILD_ROOT)
git clone -b "$(LIBUV_VERSION)" https://github.com/libuv/libuv "$(LIBUV_PREFIX)"
ios:
cmake -S ui-ios -B build -G Xcode -DCMAKE_TOOLCHAIN_FILE=$(shell pwd)/ui-ios/ios-toolchain.cmake -DCMAKE_SYSTEM_NAME=iOS "-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64" -DCMAKE_OSX_DEPLOYMENT_TARGET=12.2 -DCMAKE_XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH=NO -DCMAKE_IOS_INSTALL_COMBINED=YES
cmake --build build
android-gradle-prepare: $(LIBUV_PREFIX)
rm -f $(ANDROID_PROPS)
rm -f $(ANDROID_LOCAL_PROPS)
echo "#auto generated don't modify kthnx" >> $(ANDROID_PROPS)
echo "libuvsrc=$(LIBUV_PREFIX)" >> $(ANDROID_PROPS)
echo "lokinetCMake=$(REPO)/CMakeLists.txt" >> $(ANDROID_PROPS)
echo "org.gradle.parallel=true" >> $(ANDROID_PROPS)
echo "org.gradle.jvmargs=-Xmx1536M" >> $(ANDROID_PROPS)
echo "#auto generated don't modify kthnx" >> $(ANDROID_LOCAL_PROPS)
echo "sdk.dir=$(ANDROID_SDK)" >> $(ANDROID_LOCAL_PROPS)
echo "ndk.dir=$(ANDROID_NDK)" >> $(ANDROID_LOCAL_PROPS)
android-gradle: android-gradle-prepare
cd $(ANDROID_DIR) && JAVA_HOME=$(JAVA_HOME) $(GRADLE) clean assemble
android: android-gradle
cp -f $(ANDROID_DIR)/build/outputs/apk/*.apk $(REPO)
windows-debug-configure: $(LIBUV_PREFIX)
mkdir -p '$(BUILD_ROOT)'
$(CONFIG_CMD_WINDOWS) -DCMAKE_TOOLCHAIN_FILE='$(REPO)/contrib/cross/mingw$(WINDOWS_ARCH).cmake' -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) -DCMAKE_ASM_FLAGS='$(ASFLAGS)' -DCMAKE_C_FLAGS='$(CFLAGS)' -DCMAKE_CXX_FLAGS='$(CXXFLAGS)' -DLIBUV_ROOT=$'(LIBUV_PREFIX)' '$(REPO)'
windows-debug: windows-debug-configure
$(MAKE) -C '$(BUILD_ROOT)'
cp '$(BUILD_ROOT)/daemon/lokinet.exe' '$(REPO)/lokinet.exe'
windows-release-configure: $(LIBUV_PREFIX)
mkdir -p '$(BUILD_ROOT)'
$(CONFIG_CMD_WINDOWS) -DNATIVE_BUILD=OFF -DCMAKE_BUILD_TYPE=Release -DBUILD_PACKAGE=ON -DCMAKE_TOOLCHAIN_FILE='$(REPO)/contrib/cross/mingw$(WINDOWS_ARCH).cmake' -DCMAKE_ASM_FLAGS='$(ASFLAGS)' -DCMAKE_C_FLAGS='$(CFLAGS)' -DCMAKE_CXX_FLAGS='$(CXXFLAGS)' -DLIBUV_ROOT='$(LIBUV_PREFIX)' -DWITH_TESTS=OFF '$(REPO)'
windows-release: windows-release-configure
$(MAKE) -C '$(BUILD_ROOT)'
cd '$(BUILD_ROOT)' && cpack -D CPACK_MONOLITHIC_INSTALL=1 -G NSIS ..
windows: windows-release
mac-release-configure: $(LIBUV_PREFIX)
mkdir -p '$(BUILD_ROOT)'
$(CONFIG_CMD) -DNATIVE_BUILD=OFF -DCMAKE_BUILD_TYPE=Release -DBUILD_PACKAGE=ON -DCMAKE_ASM_FLAGS='$(ASFLAGS)' -DCMAKE_C_FLAGS='$(CFLAGS)' -DCMAKE_CXX_FLAGS='$(CXXFLAGS)' -DLIBUV_ROOT='$(LIBUV_PREFIX)' -DWITH_TESTS=OFF '$(REPO)'
mac-release: mac-release-configure
$(MAKE) -C '$(BUILD_ROOT)'
mac: mac-release
$(MAKE) -C '$(BUILD_ROOT)' package
abyss: debug
$(ABYSS_EXE)
format:
$(FORMAT) -i $$(find jni daemon llarp include libabyss | grep -E '\.[h,c](pp)?$$')
format-verify: format
(type $(FORMAT))
$(FORMAT) --version
git diff --quiet || (echo 'Please run make format!!' && git --no-pager diff ; exit 1)
analyze-config: clean
mkdir -p '$(BUILD_ROOT)'
$(ANALYZE_CONFIG_CMD)
analyze: analyze-config
$(SCAN_BUILD) $(MAKE) -C $(BUILD_ROOT)
coverage-config: clean
mkdir -p '$(BUILD_ROOT)'
$(COVERAGE_CONFIG_CMD)
coverage: coverage-config
$(MAKE) -C $(BUILD_ROOT)
test x$(CROSS) = xOFF && $(MAKE) -C $(BUILD_ROOT) check || true # continue even if tests fail
mkdir -p "$(COVERAGE_OUTDIR)"
ifeq ($(CLANG),OFF)
gcovr -r . --branches --html --html-details -o "$(COVERAGE_OUTDIR)/lokinet.html"
else
llvm-profdata merge default.profraw -output $(BUILD_ROOT)/profdata
llvm-cov show -format=html -output-dir="$(COVERAGE_OUTDIR)" -instr-profile "$(BUILD_ROOT)/profdata" "$(BUILD_ROOT)/testAll" $(shell find ./llarp -type f)
endif
lint: $(LINT_CHECK)
%.cpp-check: %.cpp
clang-tidy $^ -- -I$(REPO)/include -I$(REPO)/crypto/include -I$(REPO)/llarp -I$(REPO)/vendor/cppbackport-master/lib
docker-kubernetes:
docker build -f docker/loki-svc-kubernetes.Dockerfile .
install-pylokinet:
cd $(REPO)/contrib/py/pylokinet && $(PYTHON3) setup.py install
kubernetes-install: install install-pylokinet
docker-debian:
docker build -f docker/debian.Dockerfile .
docker-fedora:
docker build -f docker/fedora.Dockerfile .
debian-configure:
mkdir -p '$(BUILD_ROOT)'
$(CONFIG_CMD) -DDEBIAN=ON -DCMAKE_BUILD_TYPE=Release
debian: debian-configure
$(MAKE) -C '$(BUILD_ROOT)'
cp $(EXE) lokinet
debian-test:
test x$(CROSS) = xOFF && $(MAKE) -C $(BUILD_ROOT) check || test x$(CROSS) = xON
install:
DESTDIR=$(DESTDIR) $(MAKE) -C '$(BUILD_ROOT)' install
.PHONY: debian-install

@ -3,11 +3,7 @@
package="network.loki.lokinet"
android:installLocation="auto"
android:versionCode="1"
android:versionName="0.3.2">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="28" />
android:versionName="0.8.0">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" /> <!-- normal perm, per https://developer.android.com/guide/topics/permissions/normal-permissions.html -->

@ -2,9 +2,10 @@ buildscript {
repositories {
mavenCentral()
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'com.android.tools.build:gradle:4.0.1'
}
}
@ -16,31 +17,33 @@ repositories {
maven {
url 'https://maven.google.com'
}
google()
}
android {
compileSdkVersion 28
buildToolsVersion "28.0.1"
defaultConfig {
applicationId "network.loki.lokinet"
targetSdkVersion 28
minSdkVersion 23
versionCode 1
versionName "0.4.0"
ndk {
abiFilters 'armeabi'
}
versionName '0.8.0'
externalNativeBuild {
cmake {
targets "lokinetandroid"
arguments "-DANDROID=ON", "-DANDROID_STL=c++_static", "-DANDROID_ARM_NEON=TRUE", "-DLIBUV_ROOT=" + libuvsrc, "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_MODE=arm"
cppFlags "-fexceptions -std=c++14 -frtti"
// targets "lokinet-android"
arguments "-DWITH_LTO=OFF", "-DCXXOPTS_BUILD_TESTS=OFF","-DWITH_TESTS=OFF", "-DCMAKE_CROSSCOMPILING=ON", "-DNATIVE_BUILD=OFF", "-DANDROID=ON", "-DANDROID_STL=c++_static", "-DBUILD_STATIC_DEPS=ON", "-DBUILD_SHARED_LIBS=OFF", "-DSTATIC_LINK=ON", "-DDOWNLOAD_UV=FORCE", "-DANDROID_ARM_MODE=arm"
cppFlags "-std=c++17"
abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
// abiFilters 'armeabi-v7a'
// abiFilters 'arm64-v8a', 'x86_64', 'armeabi-v7a'
}
}
packagingOptions{
doNotStrip "*/armeabi/*.so"
doNotStrip "*/armeabi-v7a/*.so"
doNotStrip "*/x86/*.so"
}
externalNativeBuild {
cmake {
path "../CMakeLists.txt"
}
}
sourceSets {
@ -63,13 +66,16 @@ android {
minifyEnabled true
//signingConfig signingConfigs.jeff
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
debuggable false
}
}
externalNativeBuild {
cmake {
path lokinetCMake
debug {
// jniDebuggable true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}

@ -0,0 +1,33 @@
# lokinet android
this directory contains basic stuff for lokinet on android.
## Prerequsites
To build you need the following:
* Gradle (6.x)
* Android SDK (latest version)
* Android NDK (latest version)
## Building
Next set up the path to Android SDK and NDK in `local.properties`
```
sdk.dir=/path/to/android/sdk
ndk.dir=/path/to/android/ndk
```
Then build:
$ gradle assemble
This fetches a large amount (several dozen Gigabytes) of files from some
server somewhere dumping it on your filesystem to make the thing do the
building, then proceeds to peg all your cores for several dozen minutes
while it does the required incantations to build 2 apks.
The build outputs apks to to subdirectories in `build/outputs/apk/`
one called `debug` for debug builds and one called `release` for release builds.

@ -42,7 +42,7 @@ public class LokiNetActivity extends Activity {
super.onCreate(savedInstanceState);
textView = new TextView(this);
setContentView(textView);
System.loadLibrary("lokinetandroid");
System.loadLibrary("lokinet-android");
}

@ -1,6 +0,0 @@
int
main(__attribute__((unused)) int argc, __attribute__((unused)) char* argv[])
{
return 0;
}

@ -0,0 +1,57 @@
set(LIBCURL_PREFIX ${CMAKE_BINARY_DIR}/libcurl)
set(LIBCURL_URL https://github.com/curl/curl/releases/download/curl-7_67_0/curl-7.67.0.tar.xz)
set(LIBCURL_HASH SHA256=f5d2e7320379338c3952dcc7566a140abb49edb575f9f99272455785c40e536c)
if(CURL_TARBALL_URL)
# make a build time override of the tarball url so we can fetch it if the original link goes away
set(LIBCURL_URL ${CURL_TARBALL_URL})
endif()
file(MAKE_DIRECTORY ${LIBCURL_PREFIX}/include)
include(ExternalProject)
include(ProcessorCount)
ProcessorCount(PROCESSOR_COUNT)
if(PROCESSOR_COUNT EQUAL 0)
set(PROCESSOR_COUNT 1)
endif()
set(libcurl_cc ${CMAKE_C_COMPILER})
if(CCACHE_PROGRAM)
set(libcurl_cc "${CCACHE_PROGRAM} ${libcurl_cc}")
endif()
set(CURL_CONFIGURE ./configure --prefix=${LIBCURL_PREFIX}
--without-ssl --without-nss --without-gnutls --without-mbedtls --without-wolfssl --without-mesalink
--without-bearssl --without-ca-bundle --without-libidn2 --without-zlib --without-nghttp2 --without-nghttp3
--without-quiche --without-zsh-functions-dir --without-fish-functions-dir
--without-librtmp --without-ca-fallback --without-ca-path --without-brotli --without-libpsl
--disable-manual --disable-dict --disable-file --disable-ftp --disable-gopher --disable-imap --disable-ldap --disable-ldaps
--disable-pop3 --disable-rtsp --disable-smtp --disable-telnet --disable-tftp
--enable-static --disable-shared CC=${libcurl_cc})
if (CMAKE_C_COMPILER_ARG1)
set(CURL_CONFIGURE ${CURL_CONFIGURE} CPPFLAGS=${CMAKE_C_COMPILER_ARG1})
endif()
if (CROSS_TARGET)
set(CURL_CONFIGURE ${CURL_CONFIGURE} --target=${CROSS_TARGET} --host=${CROSS_TARGET})
endif()
ExternalProject_Add(libcurl_external
BUILD_IN_SOURCE ON
PREFIX ${LIBCURL_PREFIX}
URL ${LIBCURL_URL}
URL_HASH ${LIBCURL_HASH}
CONFIGURE_COMMAND ${CURL_CONFIGURE}
BUILD_COMMAND make -j${PROCESSOR_COUNT}
BUILD_BYPRODUCTS ${LIBCURL_PREFIX}/lib/libcurl.a ${LIBCURL_PREFIX}/include
)
add_library(curl_vendor STATIC IMPORTED GLOBAL)
add_dependencies(curl_vendor curl_external)
set_target_properties(curl_vendor PROPERTIES
IMPORTED_LOCATION ${LIBCURL_PREFIX}/lib/libcurl.a
INTERFACE_INCLUDE_DIRECTORIES ${LIBCURL_PREFIX}/include
)

@ -12,15 +12,22 @@ file(MAKE_DIRECTORY ${LIBSODIUM_PREFIX}/include)
include(ExternalProject)
include(ProcessorCount)
ProcessorCount(PROCESSOR_COUNT)
if(PROCESSOR_COUNT EQUAL 0)
set(PROCESSOR_COUNT 1)
endif()
set(sodium_cc ${CMAKE_C_COMPILER})
if(CCACHE_PROGRAM)
set(sodium_cc "${CCACHE_PROGRAM} ${sodium_cc}")
endif()
set(SODIUM_CONFIGURE ./configure --prefix=${LIBSODIUM_PREFIX} --enable-static --disable-shared --with-pic --quiet CC=${sodium_cc})
if (CMAKE_C_COMPILER_ARG1)
set(SODIUM_CONFIGURE ./configure --prefix=${LIBSODIUM_PREFIX} --enable-static --disable-shared CC=${CMAKE_C_COMPILER} CPPFLAGS=${CMAKE_C_COMPILER_ARG1})
else()
set(SODIUM_CONFIGURE ./configure --prefix=${LIBSODIUM_PREFIX} --enable-static --disable-shared CC=${CMAKE_C_COMPILER})
set(SODIUM_CONFIGURE ${SODIUM_CONFIGURE} CPPFLAGS=${CMAKE_C_COMPILER_ARG1})
endif()
if (LIBSODIUM_CROSS_TARGET)
set(SODIUM_CONFIGURE ${SODIUM_CONFIGURE} --target=${LIBSODIUM_CROSS_TARGET} --host=${LIBSODIUM_CROSS_TARGET})
if (CROSS_TARGET)
set(SODIUM_CONFIGURE ${SODIUM_CONFIGURE} --target=${CROSS_TARGET} --host=${CROSS_TARGET})
endif()
@ -30,6 +37,7 @@ ExternalProject_Add(libsodium_external
URL ${LIBSODIUM_URL}
URL_HASH ${LIBSODIUM_HASH}
CONFIGURE_COMMAND ${SODIUM_CONFIGURE}
PATCH_COMMAND patch -p1 -d <SOURCE_DIR> < ${CMAKE_SOURCE_DIR}/win32-setup/libsodium-1.0.18-win32.patch
BUILD_COMMAND make -j${PROCESSOR_COUNT}
INSTALL_COMMAND ${MAKE}
BUILD_BYPRODUCTS ${LIBSODIUM_PREFIX}/lib/libsodium.a ${LIBSODIUM_PREFIX}/include

@ -0,0 +1,57 @@
#
# Find the JEMALLOC client includes and library
#
# This module defines
# JEMALLOC_INCLUDE_DIR, where to find jemalloc.h
# JEMALLOC_LIBRARIES, the libraries to link against
# JEMALLOC_FOUND, if false, you cannot build anything that requires JEMALLOC
# also defined, but not for general use are
# JEMALLOC_LIBRARY, where to find the JEMALLOC library.
set( JEMALLOC_FOUND 0 )
if ( UNIX )
FIND_PATH( JEMALLOC_INCLUDE_DIR
NAMES
jemalloc/jemalloc.h
PATHS
/usr/include
/usr/include/jemalloc
/usr/local/include
/usr/local/include/jemalloc
$ENV{JEMALLOC_ROOT}
$ENV{JEMALLOC_ROOT}/include
DOC
"Specify include-directories that might contain jemalloc.h here."
)
FIND_LIBRARY( JEMALLOC_LIBRARY
NAMES
jemalloc libjemalloc JEMALLOC
PATHS
/usr/lib
/usr/lib/jemalloc
/usr/local/lib
/usr/local/lib/jemalloc
/usr/local/jemalloc/lib
$ENV{JEMALLOC_ROOT}/lib
$ENV{JEMALLOC_ROOT}
DOC "Specify library-locations that might contain the jemalloc library here."
)
if ( JEMALLOC_LIBRARY )
if ( JEMALLOC_INCLUDE_DIR )
set( JEMALLOC_FOUND 1 )
message( STATUS "Found JEMALLOC library: ${JEMALLOC_LIBRARY}")
message( STATUS "Found JEMALLOC headers: ${JEMALLOC_INCLUDE_DIR}")
else ( JEMALLOC_INCLUDE_DIR )
message(FATAL_ERROR "Could not find jemalloc headers! Please install jemalloc libraries and headers")
endif ( JEMALLOC_INCLUDE_DIR )
endif ( JEMALLOC_LIBRARY )
add_library(jemalloc SHARED IMPORTED)
set_target_properties(jemalloc PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${JEMALLOC_INCLUDE_DUR}"
IMPORTED_LOCATION "${JEMALLOC_LIBRARY}")
mark_as_advanced( JEMALLOC_FOUND JEMALLOC_LIBRARY JEMALLOC_EXTRA_LIBRARIES JEMALLOC_INCLUDE_DIR )
endif (UNIX)

@ -1,288 +0,0 @@
# Written in 2016 by Henrik Steffen Gaßmann <henrik@gassmann.onl>
#
# To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to the
# public domain worldwide. This software is distributed without any warranty.
#
# You should have received a copy of the CC0 Public Domain Dedication
# along with this software. If not, see
#
# http://creativecommons.org/publicdomain/zero/1.0/
#
########################################################################
# Tries to find the local libsodium installation.
#
# On Windows the sodium_DIR environment variable is used as a default
# hint which can be overridden by setting the corresponding cmake variable.
#
# Once done the following variables will be defined:
#
# sodium_FOUND
# sodium_INCLUDE_DIR
# sodium_LIBRARY_DEBUG
# sodium_LIBRARY_RELEASE
#
#
# Furthermore an imported "sodium" target is created.
#
if (CMAKE_C_COMPILER_ID STREQUAL "GNU"
OR CMAKE_C_COMPILER_ID STREQUAL "Clang")
set(_GCC_COMPATIBLE 1)
endif()
# static library option
if (NOT DEFINED sodium_USE_STATIC_LIBS)
option(sodium_USE_STATIC_LIBS "enable to statically link against sodium" OFF)
endif()
if(NOT (sodium_USE_STATIC_LIBS EQUAL sodium_USE_STATIC_LIBS_LAST))
unset(sodium_LIBRARY CACHE)
unset(sodium_LIBRARY_DEBUG CACHE)
unset(sodium_LIBRARY_RELEASE CACHE)
unset(sodium_DLL_DEBUG CACHE)
unset(sodium_DLL_RELEASE CACHE)
set(sodium_USE_STATIC_LIBS_LAST ${sodium_USE_STATIC_LIBS} CACHE INTERNAL "internal change tracking variable")
endif()
########################################################################
# UNIX
if (UNIX)
# import pkg-config
find_package(PkgConfig QUIET)
if (PKG_CONFIG_FOUND)
pkg_check_modules(sodium_PKG QUIET libsodium>=${Sodium_FIND_VERSION})
endif()
if(sodium_USE_STATIC_LIBS)
foreach(_libname ${sodium_PKG_STATIC_LIBRARIES})
if (NOT _libname MATCHES "^lib.*\\.a$") # ignore strings already ending with .a
list(INSERT sodium_PKG_STATIC_LIBRARIES 0 "lib${_libname}.a")
endif()
endforeach()
list(REMOVE_DUPLICATES sodium_PKG_STATIC_LIBRARIES)
# if pkgconfig for libsodium doesn't provide
# static lib info, then override PKG_STATIC here..
if (sodium_PKG_STATIC_LIBRARIES STREQUAL "")
set(sodium_PKG_STATIC_LIBRARIES libsodium.a)
endif()
set(XPREFIX sodium_PKG_STATIC)
else()
if (sodium_PKG_LIBRARIES STREQUAL "")
set(sodium_PKG_LIBRARIES sodium)
endif()
set(XPREFIX sodium_PKG)
endif()
find_path(sodium_INCLUDE_DIR sodium.h
HINTS ${${XPREFIX}_INCLUDE_DIRS} /usr/local/include
)
find_library(sodium_LIBRARY_DEBUG NAMES ${${XPREFIX}_LIBRARIES}
HINTS ${${XPREFIX}_LIBRARY_DIRS} /usr/local/lib
)
find_library(sodium_LIBRARY_RELEASE NAMES ${${XPREFIX}_LIBRARIES}
HINTS ${${XPREFIX}_LIBRARY_DIRS} /usr/local/lib
)
########################################################################
# Windows
elseif (WIN32)
set(sodium_DIR "$ENV{sodium_DIR}" CACHE FILEPATH "sodium install directory")
mark_as_advanced(sodium_DIR)
find_path(sodium_INCLUDE_DIR sodium.h
HINTS ${sodium_DIR}
PATH_SUFFIXES include
)
if (MSVC)
# detect target architecture
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/arch.c" [=[
#if defined _M_IX86
#error ARCH_VALUE x86_32
#elif defined _M_X64
#error ARCH_VALUE x86_64
#endif
#error ARCH_VALUE unknown
]=])
try_compile(_UNUSED_VAR "${CMAKE_CURRENT_BINARY_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/arch.c"
OUTPUT_VARIABLE _COMPILATION_LOG
)
string(REGEX REPLACE ".*ARCH_VALUE ([a-zA-Z0-9_]+).*" "\\1" _TARGET_ARCH "${_COMPILATION_LOG}")
# construct library path
if (_TARGET_ARCH STREQUAL "x86_32")
string(APPEND _PLATFORM_PATH "Win32")
elseif(_TARGET_ARCH STREQUAL "x86_64")
string(APPEND _PLATFORM_PATH "x64")
else()
message(FATAL_ERROR "the ${_TARGET_ARCH} architecture is not supported by Findsodium.cmake.")
endif()
string(APPEND _PLATFORM_PATH "/$$CONFIG$$")
if (MSVC_VERSION LESS 1900)
math(EXPR _VS_VERSION "${MSVC_VERSION} / 10 - 60")
else()
math(EXPR _VS_VERSION "${MSVC_VERSION} / 10 - 50")
endif()
string(APPEND _PLATFORM_PATH "/v${_VS_VERSION}")
if (sodium_USE_STATIC_LIBS)
string(APPEND _PLATFORM_PATH "/static")
else()
string(APPEND _PLATFORM_PATH "/dynamic")
endif()
string(REPLACE "$$CONFIG$$" "Debug" _DEBUG_PATH_SUFFIX "${_PLATFORM_PATH}")
string(REPLACE "$$CONFIG$$" "Release" _RELEASE_PATH_SUFFIX "${_PLATFORM_PATH}")
find_library(sodium_LIBRARY_DEBUG libsodium.lib
HINTS ${sodium_DIR}
PATH_SUFFIXES ${_DEBUG_PATH_SUFFIX}
)
find_library(sodium_LIBRARY_RELEASE libsodium.lib
HINTS ${sodium_DIR}
PATH_SUFFIXES ${_RELEASE_PATH_SUFFIX}
)
if (NOT sodium_USE_STATIC_LIBS)
set(CMAKE_FIND_LIBRARY_SUFFIXES_BCK ${CMAKE_FIND_LIBRARY_SUFFIXES})
set(CMAKE_FIND_LIBRARY_SUFFIXES ".dll")
find_library(sodium_DLL_DEBUG libsodium
HINTS ${sodium_DIR}
PATH_SUFFIXES ${_DEBUG_PATH_SUFFIX}
)
find_library(sodium_DLL_RELEASE libsodium
HINTS ${sodium_DIR}
PATH_SUFFIXES ${_RELEASE_PATH_SUFFIX}
)
set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES_BCK})
endif()
elseif(_GCC_COMPATIBLE)
if (sodium_USE_STATIC_LIBS)
find_library(sodium_LIBRARY_DEBUG libsodium.a
HINTS ${sodium_DIR}
PATH_SUFFIXES lib
)
find_library(sodium_LIBRARY_RELEASE libsodium.a
HINTS ${sodium_DIR}
PATH_SUFFIXES lib
)
else()
find_library(sodium_LIBRARY_DEBUG libsodium.dll.a
HINTS ${sodium_DIR}
PATH_SUFFIXES lib
)
find_library(sodium_LIBRARY_RELEASE libsodium.dll.a
HINTS ${sodium_DIR}
PATH_SUFFIXES lib
)
file(GLOB _DLL
LIST_DIRECTORIES false
RELATIVE "${sodium_DIR}/bin"
"${sodium_DIR}/bin/libsodium*.dll"
)
find_library(sodium_DLL_DEBUG ${_DLL} libsodium
HINTS ${sodium_DIR}
PATH_SUFFIXES bin
)
find_library(sodium_DLL_RELEASE ${_DLL} libsodium
HINTS ${sodium_DIR}
PATH_SUFFIXES bin
)
endif()
else()
message(FATAL_ERROR "this platform is not supported by FindSodium.cmake")
endif()
########################################################################
# unsupported
else()
message(FATAL_ERROR "this platform is not supported by FindSodium.cmake")
endif()
########################################################################
# common stuff
# extract sodium version
if (sodium_INCLUDE_DIR)
set(_VERSION_HEADER "${sodium_INCLUDE_DIR}/sodium/version.h")
if (EXISTS "${_VERSION_HEADER}")
file(READ "${_VERSION_HEADER}" _VERSION_HEADER_CONTENT)
string(REGEX REPLACE ".*#[ \t]*define[ \t]*SODIUM_VERSION_STRING[ \t]*\"([^\n]*)\".*" "\\1"
sodium_VERSION "${_VERSION_HEADER_CONTENT}")
set(sodium_VERSION "${sodium_VERSION}" PARENT_SCOPE)
endif()
endif()
# communicate results
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(sodium
REQUIRED_VARS
sodium_LIBRARY_RELEASE
sodium_LIBRARY_DEBUG
sodium_INCLUDE_DIR
VERSION_VAR
sodium_VERSION
)
# mark file paths as advanced
mark_as_advanced(sodium_INCLUDE_DIR)
mark_as_advanced(sodium_LIBRARY_DEBUG)
mark_as_advanced(sodium_LIBRARY_RELEASE)
if (WIN32)
mark_as_advanced(sodium_DLL_DEBUG)
mark_as_advanced(sodium_DLL_RELEASE)
endif()
# create imported target
if(sodium_USE_STATIC_LIBS)
set(_LIB_TYPE STATIC)
else()
set(_LIB_TYPE SHARED)
endif()
add_library(sodium ${_LIB_TYPE} IMPORTED)
set_target_properties(sodium PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${sodium_INCLUDE_DIR}"
IMPORTED_LINK_INTERFACE_LANGUAGES "C"
)
if (sodium_USE_STATIC_LIBS)
set_target_properties(sodium PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "SODIUM_STATIC"
IMPORTED_LOCATION "${sodium_LIBRARY_RELEASE}"
IMPORTED_LOCATION_DEBUG "${sodium_LIBRARY_DEBUG}"
)
else()
if (UNIX)
set_target_properties(sodium PROPERTIES
IMPORTED_LOCATION "${sodium_LIBRARY_RELEASE}"
IMPORTED_LOCATION_DEBUG "${sodium_LIBRARY_DEBUG}"
)
elseif (WIN32)
set_target_properties(sodium PROPERTIES
IMPORTED_IMPLIB "${sodium_LIBRARY_RELEASE}"
IMPORTED_IMPLIB_DEBUG "${sodium_LIBRARY_DEBUG}"
)
if (NOT (sodium_DLL_DEBUG MATCHES ".*-NOTFOUND"))
set_target_properties(sodium PROPERTIES
IMPORTED_LOCATION_DEBUG "${sodium_DLL_DEBUG}"
)
endif()
if (NOT (sodium_DLL_RELEASE MATCHES ".*-NOTFOUND"))
set_target_properties(sodium PROPERTIES
IMPORTED_LOCATION_RELWITHDEBINFO "${sodium_DLL_RELEASE}"
IMPORTED_LOCATION_MINSIZEREL "${sodium_DLL_RELEASE}"
IMPORTED_LOCATION_RELEASE "${sodium_DLL_RELEASE}"
)
endif()
endif()
endif()

@ -30,14 +30,13 @@
# Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
# Check what commit we're on
execute_process(COMMAND "${GIT}" rev-parse --short=9 HEAD RESULT_VARIABLE RET OUTPUT_VARIABLE COMMIT OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND "${GIT}" rev-parse --short HEAD RESULT_VARIABLE RET OUTPUT_VARIABLE COMMIT OUTPUT_STRIP_TRAILING_WHITESPACE)
if(RET)
# Something went wrong, set the version tag to -unknown
message(WARNING "Cannot determine current commit. Make sure that you are building either from a Git working tree or from a source archive.")
set(VERSIONTAG "unknown")
else()
string(SUBSTRING ${COMMIT} 0 9 COMMIT)
message(STATUS "You are currently on commit ${COMMIT}")
# Get all the tags

@ -0,0 +1,275 @@
# cmake bits to do a full static build, downloading and building all dependencies.
# Most of these are CACHE STRINGs so that you can override them using -DWHATEVER during cmake
# invocation to override.
set(LOCAL_MIRROR "" CACHE STRING "local mirror path/URL for lib downloads")
set(OPENSSL_VERSION 1.1.1g CACHE STRING "openssl version")
set(OPENSSL_MIRROR ${LOCAL_MIRROR} https://www.openssl.org/source CACHE STRING "openssl download mirror(s)")
set(OPENSSL_SOURCE openssl-${OPENSSL_VERSION}.tar.gz)
set(OPENSSL_HASH SHA256=ddb04774f1e32f0c49751e21b67216ac87852ceb056b75209af2443400636d46
CACHE STRING "openssl source hash")
set(EXPAT_VERSION 2.2.9 CACHE STRING "expat version")
string(REPLACE "." "_" EXPAT_TAG "R_${EXPAT_VERSION}")
set(EXPAT_MIRROR ${LOCAL_MIRROR} https://github.com/libexpat/libexpat/releases/download/${EXPAT_TAG}
CACHE STRING "expat download mirror(s)")
set(EXPAT_SOURCE expat-${EXPAT_VERSION}.tar.xz)
set(EXPAT_HASH SHA512=e082874efcc4b00709e2c0192c88fb15dfc4f33fc3a2b09e619b010ea93baaf7e7572683f738463db0ce2350cab3de48a0c38af6b74d1c4f5a9e311f499edab0
CACHE STRING "expat source hash")
set(UNBOUND_VERSION 1.11.0 CACHE STRING "unbound version")
set(UNBOUND_MIRROR ${LOCAL_MIRROR} https://nlnetlabs.nl/downloads/unbound CACHE STRING "unbound download mirror(s)")
set(UNBOUND_SOURCE unbound-${UNBOUND_VERSION}.tar.gz)
set(UNBOUND_HASH SHA256=9f2f0798f76eb8f30feaeda7e442ceed479bc54db0e3ac19c052d68685e51ef7
CACHE STRING "unbound source hash")
set(SQLITE3_VERSION 3330000 CACHE STRING "sqlite3 version")
set(SQLITE3_MIRROR ${LOCAL_MIRROR} https://www.sqlite.org/2020
CACHE STRING "sqlite3 download mirror(s)")
set(SQLITE3_SOURCE sqlite-autoconf-${SQLITE3_VERSION}.tar.gz)
set(SQLITE3_HASH SHA512=c0d79d4012a01f12128ab5044b887576a130663245b85befcc0ab82ad3a315dd1e7f54b6301f842410c9c21b73237432c44a1d7c2fe0e0709435fec1f1a20a11
CACHE STRING "sqlite3 source hash")
set(SODIUM_VERSION 1.0.18 CACHE STRING "libsodium version")
set(SODIUM_MIRROR ${LOCAL_MIRROR}
https://download.libsodium.org/libsodium/releases
https://github.com/jedisct1/libsodium/releases/download/${SODIUM_VERSION}-RELEASE
CACHE STRING "libsodium mirror(s)")
set(SODIUM_SOURCE libsodium-${SODIUM_VERSION}.tar.gz)
set(SODIUM_HASH SHA512=17e8638e46d8f6f7d024fe5559eccf2b8baf23e143fadd472a7d29d228b186d86686a5e6920385fe2020729119a5f12f989c3a782afbd05a8db4819bb18666ef
CACHE STRING "libsodium source hash")
set(ZMQ_VERSION 4.3.3 CACHE STRING "libzmq version")
set(ZMQ_MIRROR ${LOCAL_MIRROR} https://github.com/zeromq/libzmq/releases/download/v${ZMQ_VERSION}
CACHE STRING "libzmq mirror(s)")
set(ZMQ_SOURCE zeromq-${ZMQ_VERSION}.tar.gz)
set(ZMQ_HASH SHA512=4c18d784085179c5b1fcb753a93813095a12c8d34970f2e1bfca6499be6c9d67769c71c68b7ca54ff181b20390043170e89733c22f76ff1ea46494814f7095b1
CACHE STRING "libzmq source hash")
include(ExternalProject)
set(DEPS_DESTDIR ${CMAKE_BINARY_DIR}/static-deps)
set(DEPS_SOURCEDIR ${CMAKE_BINARY_DIR}/static-deps-sources)
include_directories(BEFORE SYSTEM ${DEPS_DESTDIR}/include)
file(MAKE_DIRECTORY ${DEPS_DESTDIR}/include)
set(deps_cc "${CMAKE_C_COMPILER}")
set(deps_cxx "${CMAKE_CXX_COMPILER}")
if(CMAKE_C_COMPILER_LAUNCHER)
set(deps_cc "${CMAKE_C_COMPILER_LAUNCHER} ${deps_cc}")
endif()
if(CMAKE_CXX_COMPILER_LAUNCHER)
set(deps_cxx "${CMAKE_CXX_COMPILER_LAUNCHER} ${deps_cxx}")
endif()
function(expand_urls output source_file)
set(expanded)
foreach(mirror ${ARGN})
list(APPEND expanded "${mirror}/${source_file}")
endforeach()
set(${output} "${expanded}" PARENT_SCOPE)
endfunction()
function(add_static_target target ext_target libname)
add_library(${target} STATIC IMPORTED GLOBAL)
add_dependencies(${target} ${ext_target})
set_target_properties(${target} PROPERTIES
IMPORTED_LOCATION ${DEPS_DESTDIR}/lib/${libname}
)
endfunction()
if(WITH_LTO)
set(flto "-flto")
else()
set(flto "")
endif()
set(cross_host "")
set(cross_rc "")
if(CMAKE_CROSSCOMPILING)
set(cross_host "--host=${ARCH_TRIPLET}")
if (ARCH_TRIPLET MATCHES mingw AND CMAKE_RC_COMPILER)
set(cross_rc "WINDRES=${CMAKE_RC_COMPILER}")
endif()
endif()
if(ANDROID)
set(android_toolchain_suffix linux-android)
set(android_compiler_suffix linux-android23)
if(CMAKE_ANDROID_ARCH_ABI MATCHES x86_64)
set(android_machine x86_64)
set(cross_host "--host=x86_64-linux-android")
set(android_compiler_prefix x86_64)
set(android_compiler_suffix linux-android23)
set(android_toolchain_prefix x86_64)
set(android_toolchain_suffix linux-android)
elseif(CMAKE_ANDROID_ARCH_ABI MATCHES x86)
set(android_machine i686)
set(cross_host "--host=i686-linux-android")
set(android_compiler_prefix i686)
set(android_compiler_suffix linux-android23)
set(android_toolchain_prefix i686)
set(android_toolchain_suffix linux-android)
elseif(CMAKE_ANDROID_ARCH_ABI MATCHES armeabi-v7a)
set(android_machine armv7)
set(cross_host "--host=armv7a-linux-androideabi")
set(android_compiler_prefix armv7a)
set(android_compiler_suffix linux-androideabi23)
set(android_toolchain_prefix arm)
set(android_toolchain_suffix linux-androideabi)
elseif(CMAKE_ANDROID_ARCH_ABI MATCHES arm64-v8a)
set(android_machine aarch64)
set(cross_host "--host=aarch64-linux-android")
set(android_compiler_prefix aarch64)
set(android_compiler_suffix linux-android23)
set(android_toolchain_prefix aarch64)
set(android_toolchain_suffix linux-android)
else()
message(FATAL_ERROR "unknown android arch: ${CMAKE_ANDROID_ARCH_ABI}")
endif()
set(deps_cc "${CMAKE_ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/bin/${android_compiler_prefix}-${android_compiler_suffix}-clang")
set(deps_cxx "${CMAKE_ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/bin/${android_compiler_prefix}-${android_compiler_suffix}-clang++")
set(deps_ld "${CMAKE_ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/bin/${android_compiler_prefix}-${android_toolchain_suffix}-ld")
set(deps_ranlib "${CMAKE_ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/bin/${android_toolchain_prefix}-${android_toolchain_suffix}-ranlib")
set(deps_ar "${CMAKE_ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/bin/${android_toolchain_prefix}-${android_toolchain_suffix}-ar")
endif()
# Builds a target; takes the target name (e.g. "readline") and builds it in an external project with
# target name suffixed with `_external`. Its upper-case value is used to get the download details
# (from the variables set above). The following options are supported and passed through to
# ExternalProject_Add if specified. If omitted, these defaults are used:
set(build_def_DEPENDS "")
set(build_def_PATCH_COMMAND "")
set(build_def_CONFIGURE_COMMAND ./configure ${cross_host} --disable-shared --prefix=${DEPS_DESTDIR} --with-pic
"CC=${deps_cc}" "CXX=${deps_cxx}" "CFLAGS=-O2 ${flto}" "CXXFLAGS=-O2 ${flto}" ${cross_rc})
set(build_def_BUILD_COMMAND make)
set(build_def_INSTALL_COMMAND make install)
set(build_def_BUILD_BYPRODUCTS ${DEPS_DESTDIR}/lib/lib___TARGET___.a ${DEPS_DESTDIR}/include/___TARGET___.h)
function(build_external target)
set(options DEPENDS PATCH_COMMAND CONFIGURE_COMMAND BUILD_COMMAND INSTALL_COMMAND BUILD_BYPRODUCTS)
cmake_parse_arguments(PARSE_ARGV 1 arg "" "" "${options}")
foreach(o ${options})
if(NOT DEFINED arg_${o})
set(arg_${o} ${build_def_${o}})
endif()
endforeach()
string(REPLACE ___TARGET___ ${target} arg_BUILD_BYPRODUCTS "${arg_BUILD_BYPRODUCTS}")
string(TOUPPER "${target}" prefix)
expand_urls(urls ${${prefix}_SOURCE} ${${prefix}_MIRROR})
ExternalProject_Add("${target}_external"
DEPENDS ${arg_DEPENDS}
BUILD_IN_SOURCE ON
PREFIX ${DEPS_SOURCEDIR}
URL ${urls}
URL_HASH ${${prefix}_HASH}
DOWNLOAD_NO_PROGRESS ON
PATCH_COMMAND ${arg_PATCH_COMMAND}
CONFIGURE_COMMAND ${arg_CONFIGURE_COMMAND}
BUILD_COMMAND ${arg_BUILD_COMMAND}
INSTALL_COMMAND ${arg_INSTALL_COMMAND}
BUILD_BYPRODUCTS ${arg_BUILD_BYPRODUCTS}
)
endfunction()
set(openssl_system_env "")
if(CMAKE_CROSSCOMPILING)
if(ARCH_TRIPLET STREQUAL x86_64-w64-mingw32)
set(openssl_system_env SYSTEM=MINGW64 RC=${CMAKE_RC_COMPILER} AR=${ARCH_TRIPLET}-ar RANLIB=${ARCH_TRIPLET}-ranlib)
elseif(ARCH_TRIPLET STREQUAL i686-w64-mingw32)
set(openssl_system_env SYSTEM=MINGW32 RC=${CMAKE_RC_COMPILER} AR=${ARCH_TRIPLET}-ar RANLIB=${ARCH_TRIPLET}-ranlib)
elseif(ANDROID)
set(openssl_system_env SYSTEM=Linux MACHINE=${android_machine} LD=${deps_ld} RANLIB=${deps_ranlib} AR=${deps_ar})
set(openssl_extra_opts no-asm)
endif()
endif()
build_external(openssl
CONFIGURE_COMMAND ${CMAKE_COMMAND} -E env CC=${deps_cc} ${openssl_system_env} ./config
--prefix=${DEPS_DESTDIR} ${openssl_extra_opts} no-shared no-capieng no-dso no-dtls1 no-ec_nistp_64_gcc_128 no-gost
no-heartbeats no-md2 no-rc5 no-rdrand no-rfc3779 no-sctp no-ssl-trace no-ssl2 no-ssl3
no-static-engine no-tests no-weak-ssl-ciphers no-zlib no-zlib-dynamic "CFLAGS=-O2 ${flto}"
INSTALL_COMMAND make install_sw
BUILD_BYPRODUCTS
${DEPS_DESTDIR}/lib/libssl.a ${DEPS_DESTDIR}/lib/libcrypto.a
${DEPS_DESTDIR}/include/openssl/ssl.h ${DEPS_DESTDIR}/include/openssl/crypto.h
)
add_static_target(OpenSSL::SSL openssl_external libssl.a)
add_static_target(OpenSSL::Crypto openssl_external libcrypto.a)
if(WIN32)
target_link_libraries(OpenSSL::Crypto INTERFACE "ws2_32;crypt32;iphlpapi")
endif()
set(OPENSSL_INCLUDE_DIR ${DEPS_DESTDIR}/include)
set(OPENSSL_VERSION 1.1.1)
build_external(expat
CONFIGURE_COMMAND ./configure ${cross_host} --prefix=${DEPS_DESTDIR} --enable-static
--disable-shared --with-pic --without-examples --without-tests --without-docbook --without-xmlwf
"CC=${deps_cc}" "CFLAGS=-O2 ${flto}"
)
add_static_target(expat expat_external libexpat.a)
build_external(unbound
DEPENDS openssl_external expat_external
CONFIGURE_COMMAND ./configure ${cross_host} ${cross_rc} --prefix=${DEPS_DESTDIR} --disable-shared
--enable-static --with-libunbound-only --with-pic
--$<IF:$<BOOL:${WITH_LTO}>,enable,disable>-flto --with-ssl=${DEPS_DESTDIR}
--with-libexpat=${DEPS_DESTDIR}
"CC=${deps_cc}" "CFLAGS=-O2 ${flto}"
)
add_static_target(libunbound unbound_external libunbound.a)
if(NOT WIN32)
set_target_properties(libunbound PROPERTIES INTERFACE_LINK_LIBRARIES "OpenSSL::SSL;OpenSSL::Crypto")
else()
set_target_properties(libunbound PROPERTIES INTERFACE_LINK_LIBRARIES "OpenSSL::SSL;OpenSSL::Crypto;ws2_32;crypt32;iphlpapi")
endif()
build_external(sodium CONFIGURE_COMMAND ./configure ${cross_host} ${cross_rc} --prefix=${DEPS_DESTDIR} --disable-shared
--enable-static --with-pic "CC=${deps_cc}" "CFLAGS=-O2 ${flto}")
add_static_target(sodium sodium_external libsodium.a)
build_external(sqlite3)
add_static_target(sqlite3 sqlite3_external libsqlite3.a)
if(ZMQ_VERSION VERSION_LESS 4.3.4 AND CMAKE_CROSSCOMPILING AND ARCH_TRIPLET MATCHES mingw)
set(zmq_patch
PATCH_COMMAND patch -p1 -i ${PROJECT_SOURCE_DIR}/contrib/cross/patches/libzmq-mingw-closesocket.patch)
endif()
build_external(zmq
DEPENDS sodium_external
${zmq_patch}
CONFIGURE_COMMAND ./configure ${cross_host} --prefix=${DEPS_DESTDIR} --enable-static --disable-shared
--disable-curve-keygen --enable-curve --disable-drafts --disable-libunwind --with-libsodium
--without-pgm --without-norm --without-vmci --without-docs --with-pic --disable-Werror
"CC=${deps_cc}" "CXX=${deps_cxx}" "CFLAGS=-O2 -fstack-protector ${flto}" "CXXFLAGS=-O2 -fstack-protector ${flto}"
"sodium_CFLAGS=-I${DEPS_DESTDIR}/include" "sodium_LIBS=-L${DEPS_DESTDIR}/lib -lsodium"
)
add_static_target(libzmq zmq_external libzmq.a)
set(libzmq_link_libs "sodium")
if(CMAKE_CROSSCOMPILING AND ARCH_TRIPLET MATCHES mingw)
list(APPEND libzmq_link_libs iphlpapi)
endif()
set_target_properties(libzmq PROPERTIES
INTERFACE_LINK_LIBRARIES "${libzmq_link_libs}"
INTERFACE_COMPILE_DEFINITIONS "ZMQ_STATIC")

@ -1,8 +1,6 @@
function(add_log_tag target)
if(TARGET ${target})
get_target_property(TARGET_SRCS ${target} SOURCES)
foreach(F ${TARGET_SRCS})
set_source_files_properties(${F} PROPERTIES COMPILE_FLAGS -DLOG_TAG=\\\"${F}\\\")
endforeach(F)
endif()
get_target_property(TARGET_SRCS ${target} SOURCES)
foreach(F ${TARGET_SRCS})
set_property(SOURCE ${F} APPEND PROPERTY COMPILE_DEFINITIONS LOG_TAG=\"${F}\")
endforeach()
endfunction()

@ -1,20 +0,0 @@
# Basic definitions
set(LIB lokinet)
set(SHARED_LIB ${LIB}-shared)
set(STATIC_LIB ${LIB}-static)
set(CRYPTOGRAPHY_LIB ${LIB}-cryptography)
set(UTIL_LIB ${LIB}-util)
set(PLATFORM_LIB ${LIB}-platform)
set(ANDROID_LIB ${LIB}android)
set(ABYSS libabyss)
set(ABYSS_LIB abyss)
set(ABYSS_EXE ${ABYSS_LIB}-main)
get_filename_component(TT_ROOT "${CMAKE_CURRENT_LIST_DIR}/../vendor/libtuntap-master" ABSOLUTE)
add_definitions(-D${CMAKE_SYSTEM_NAME})
get_filename_component(CORE_INCLUDE "${CMAKE_CURRENT_SOURCE_DIR}/include" ABSOLUTE)
get_filename_component(ABYSS_INCLUDE "${CMAKE_CURRENT_SOURCE_DIR}/${ABYSS}/include" ABSOLUTE)
set(LIBTUNTAP_SRC
${TT_ROOT}/tuntap.cpp
${TT_ROOT}/tuntap_log.cpp)

@ -0,0 +1,50 @@
# Figure out if we need -lstdc++fs or -lc++fs and add it to the `filesystem` interface, if needed
# (otherwise just leave it an empty interface library; linking to it will do nothing). The former
# is needed for gcc before v9, and the latter with libc++ before llvm v9. But this gets more
# complicated than just using the compiler, because clang on linux by default uses libstdc++, so
# we'll just give up and see what works.
add_library(filesystem INTERFACE)
set(filesystem_code [[
#include <filesystem>
int main() {
auto cwd = std::filesystem::current_path();
return !cwd.string().empty();
}
]])
if(CMAKE_CXX_COMPILER STREQUAL "AppleClang" AND CMAKE_OSX_DEPLOYMENT_TARGET)
# It seems that check_cxx_source_compiles doesn't respect the CMAKE_OSX_DEPLOYMENT_TARGET, so this
# check would pass on Catalina (10.15) and then later compilation would fail because you aren't
# allowed to use <filesystem> when the deployment target is anything before 10.15.
set(CMAKE_REQUIRED_FLAGS -mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET})
endif()
check_cxx_source_compiles("${filesystem_code}" filesystem_compiled)
if(filesystem_compiled)
message(STATUS "No extra link flag needed for std::filesystem")
set(filesystem_is_good 1)
else()
foreach(fslib stdc++fs c++fs)
set(CMAKE_REQUIRED_LIBRARIES -l${fslib})
check_cxx_source_compiles("${filesystem_code}" filesystem_compiled_${fslib})
if (filesystem_compiled_${fslib})
message(STATUS "Using -l${fslib} for std::filesystem support")
target_link_libraries(filesystem INTERFACE ${fslib})
set(filesystem_is_good 1)
break()
endif()
endforeach()
endif()
unset(CMAKE_REQUIRED_LIBRARIES)
if(filesystem_is_good EQUAL 1)
message(STATUS "we have std::filesystem")
else()
# Probably broken AF macos
message(STATUS "std::filesystem is not available, apparently this compiler isn't C++17 compliant; falling back to ghc::filesystem")
add_subdirectory(external/ghc-filesystem)
target_link_libraries(filesystem INTERFACE ghc_filesystem)
target_compile_definitions(filesystem INTERFACE USE_GHC_FILESYSTEM)
endif()

@ -0,0 +1,18 @@
# check for std::optional because macos is broke af sometimes
set(std_optional_code [[
#include <optional>
int main() {
std::optional<int> maybe;
maybe = 1;
return *maybe == 1;
}
]])
check_cxx_source_compiles("${std_optional_code}" was_compiled)
if(was_compiled)
message(STATUS "we have std::optional")
else()
message(FATAL_ERROR "we dont have std::optional your compiler is broke af")
endif()

@ -0,0 +1,21 @@
if(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt")
message(FATAL_ERROR "Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt")
endif()
file(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files)
string(REGEX REPLACE "\n" ";" files "${files}")
foreach(file ${files})
message(STATUS "Uninstalling $ENV{DESTDIR}${file}")
if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
exec_program(
"@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
OUTPUT_VARIABLE rm_out
RETURN_VALUE rm_retval
)
if(NOT "${rm_retval}" STREQUAL 0)
message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}")
endif()
else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
message(STATUS "File $ENV{DESTDIR}${file} does not exist.")
endif()
endforeach()

@ -0,0 +1,20 @@
# -flto
include(CheckIPOSupported)
option(WITH_LTO "enable lto on compile time" ON)
if(WITH_LTO)
check_ipo_supported(RESULT IPO_ENABLED OUTPUT ipo_error)
if(IPO_ENABLED)
message(STATUS "LTO enabled")
else()
message(WARNING "LTO not supported by compiler: ${ipo_error}")
endif()
else()
message(STATUS "LTO disabled")
set(IPO_ENABLED OFF)
endif()
function(enable_lto)
if(IPO_ENABLED)
set_target_properties(${ARGN} PROPERTIES INTERPROCEDURAL_OPTIMIZATION ON)
endif()
endfunction()

@ -0,0 +1,13 @@
# Properly links a target to a list of library names by finding the given libraries. Takes:
# - a target
# - a linktype (e.g. INTERFACE, PUBLIC, PRIVATE)
# - a library search path (or "" for defaults)
# - any number of library names
function(link_dep_libs target linktype libdirs)
foreach(lib ${ARGN})
find_library(link_lib-${lib} NAMES ${lib} PATHS ${libdirs})
if(link_lib-${lib})
target_link_libraries(${target} ${linktype} ${link_lib-${lib}})
endif()
endforeach()
endfunction()

@ -1,38 +1,7 @@
if(NOT STATIC_LINK)
return()
endif()
# not supported on Solaris - system libraries are not available as archives
# LTO is supported only for native builds
if(SOLARIS)
link_libraries( -static-libstdc++ -static-libgcc )
return()
endif()
if(NOT CMAKE_CROSSCOMPILING)
add_compile_options(-static -flto)
else()
add_compile_options(-static)
endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
if(APPLE)
link_libraries( -flto)
if(STATIC_LINK)
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
link_libraries( -static-libstdc++ )
else()
link_libraries( -static -static-libstdc++ -pthread -flto )
link_libraries( -static-libstdc++ -static-libgcc )
endif()
return()
endif()
if(NOT CMAKE_CROSSCOMPILING)
set(CMAKE_AR "gcc-ar")
set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> qcs <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_C_ARCHIVE_FINISH "true")
set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> qcs <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_CXX_ARCHIVE_FINISH "true")
link_libraries( -flto -static-libstdc++ -static-libgcc -static ${CMAKE_CXX_FLAGS} ${CRYPTO_FLAGS} )
else()
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libstdc++ -static-libgcc -static" )
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
endif()

@ -1,83 +1,59 @@
if(NOT UNIX)
return()
if(NOT ANDROID)
if(NOT UNIX)
return()
endif()
endif()
include(CheckCXXSourceCompiles)
include(CheckLibraryExists)
# can't have UNIX defined
# can't have the include paths for libuv either?
if(NOT IOS AND NOT ANDROID AND NOT WIN32)
if(LIBCURL_ROOT)
option(HTTP_ONLY "" ON)
option(SSL_ENABLED "" OFF)
option(BUILD_SHARED_LIBS "" OFF)
option(ENABLE_IPV6 "" OFF)
option(CMAKE_USE_OPENSSL "" OFF)
option(CURL_CA_PATH "" OFF)
set(CURL_CA_PATH none)
message(STATUS "using local curl: ${LIBCURL_ROOT}")
add_subdirectory(${LIBCURL_ROOT})
set(CURL_INCLUDE_DIRS ${LIBCURL_ROOT}/include)
set(CURL_LIBRARIES libcurl)
set(CURL_FOUND TRUE)
else()
include(FindCURL)
if(WITH_JEMALLOC)
find_package(Jemalloc REQUIRED)
if(NOT JEMALLOC_FOUND)
message(FATAL_ERROR "did not find jemalloc")
endif()
add_definitions(-DUSE_JEMALLOC)
message(STATUS "using jemalloc")
endif()
add_definitions(-DUNIX)
add_definitions(-DPOSIX)
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix.c)
if (STATIC_LINK_RUNTIME OR STATIC_LINK)
set(LIBUV_USE_STATIC ON)
endif()
if(LIBUV_ROOT)
option(DOWNLOAD_UV "statically compile in libuv" OFF)
# Allow -DDOWNLOAD_UV=FORCE to download without even checking for a local libuv
if(NOT DOWNLOAD_UV STREQUAL "FORCE")
find_package(LibUV 1.28.0)
endif()
if(LibUV_FOUND)
message(STATUS "using system libuv")
elseif(DOWNLOAD_UV)
message(STATUS "using libuv submodule")
set(LIBUV_ROOT ${CMAKE_SOURCE_DIR}/external/libuv)
add_subdirectory(${LIBUV_ROOT})
set(LIBUV_INCLUDE_DIRS ${LIBUV_ROOT}/include)
set(LIBUV_LIBRARY uv_a)
add_definitions(-D_LARGEFILE_SOURCE)
add_definitions(-D_FILE_OFFSET_BITS=64)
elseif(NOT LIBUV_IN_SOURCE)
find_package(LibUV 1.28.0 REQUIRED)
if(NOT ANDROID)
add_definitions(-D_LARGEFILE_SOURCE)
add_definitions(-D_FILE_OFFSET_BITS=64)
endif()
endif()
include_directories(${LIBUV_INCLUDE_DIRS})
if(EMBEDDED_CFG OR ${CMAKE_SYSTEM_NAME} MATCHES "Linux")
link_libatomic()
endif()
if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-linux.c)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "Android")
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-linux.c)
elseif (${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD")
if (${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD")
add_definitions(-D_BSD_SOURCE)
add_definitions(-D_GNU_SOURCE)
add_definitions(-D_XOPEN_SOURCE=700)
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-openbsd.c ${TT_ROOT}/tuntap-unix-bsd.c)
elseif (${CMAKE_SYSTEM_NAME} MATCHES "NetBSD")
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-netbsd.c ${TT_ROOT}/tuntap-unix-bsd.c)
elseif (${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD" OR ${CMAKE_SYSTEM_NAME} MATCHES "DragonFly")
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-freebsd.c ${TT_ROOT}/tuntap-unix-bsd.c)
elseif (${CMAKE_SYSTEM_NAME} MATCHES "Darwin" OR ${CMAKE_SYSTEM_NAME} MATCHES "iOS")
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-darwin.c ${TT_ROOT}/tuntap-unix-bsd.c)
elseif (${CMAKE_SYSTEM_NAME} MATCHES "SunOS")
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-unix-sunos.c)
# Apple C++ screws up name decorations in stdc++fs, causing link to fail
# Samsung does not build c++experimental or c++fs in their Apple libc++ pkgsrc build
if (LIBUV_USE_STATIC)
link_libraries(-lkstat -lsendfile)
endif()
else()
message(FATAL_ERROR "Your operating system - ${CMAKE_SYSTEM_NAME} is not supported yet")
endif()
set(EXE_LIBS ${STATIC_LIB})
if(RELEASE_MOTTO)
add_definitions(-DLLARP_RELEASE_MOTTO="${RELEASE_MOTTO}")
endif()

@ -14,36 +14,36 @@ if(NOT MSVC_VERSION)
# to .r[o]data section one after the other!
add_compile_options(-fno-ident -Wa,-mbig-obj)
link_libraries( -lws2_32 -lshlwapi -ldbghelp -luser32 -liphlpapi -lpsapi -luserenv )
if (CMAKE_C_COMPILER_AR AND STATIC_LINK_RUNTIME)
set(CMAKE_AR ${CMAKE_C_COMPILER_AR})
set(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> qcs <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_C_ARCHIVE_FINISH "true")
set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> qcs <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_CXX_ARCHIVE_FINISH "true")
link_libraries( -static-libstdc++ -static-libgcc -static ${CMAKE_CXX_FLAGS} ${CRYPTO_FLAGS} )
endif()
# zmq requires windows xp or higher
add_definitions(-DWINVER=0x0501 -D_WIN32_WINNT=0x0501)
endif()
if(EMBEDDED_CFG)
link_libatomic()
endif()
list(APPEND LIBTUNTAP_SRC ${TT_ROOT}/tuntap-windows.c)
get_filename_component(EV_SRC "llarp/ev/ev_libuv.cpp" ABSOLUTE)
add_definitions(-DWIN32_LEAN_AND_MEAN -DWIN32)
set(EXE_LIBS ${STATIC_LIB} ws2_32 iphlpapi)
if(RELEASE_MOTTO)
add_definitions(-DLLARP_RELEASE_MOTTO="${RELEASE_MOTTO}")
endif()
if (NOT STATIC_LINK_RUNTIME AND NOT MSVC)
if (NOT STATIC_LINK AND NOT MSVC)
message("must ship compiler runtime libraries with this build: libwinpthread-1.dll, libgcc_s_dw2-1.dll, and libstdc++-6.dll")
message("for release builds, turn on STATIC_LINK_RUNTIME in cmake options")
message("for release builds, turn on STATIC_LINK in cmake options")
endif()
if (STATIC_LINK_RUNTIME)
# win32 is the last platform for which we grab libuv manually
# if you want to use the included submodule do
# cmake .. -G Ninja -DLIBUV_ROOT=../external/libuv.
# otherwise grab mine (github.com/despair86/libuv.git) if you need to run on older hardware
# and clone to win32-setup/libuv
# then
# cmake .. -G Ninja -DLIBUV_ROOT=../win32-setup/libuv
# it is literally upward compatible with current windows 10
if (STATIC_LINK)
set(LIBUV_USE_STATIC ON)
if (WOW64_CROSS_COMPILE)
link_libraries( -static-libstdc++ -static-libgcc -static -Wl,--image-base=0x10000,--large-address-aware,--dynamicbase,--pic-executable,-e,_mainCRTStartup,--subsystem,console:5.00 )
else()
link_libraries( -static-libstdc++ -static-libgcc -static -Wl,--image-base=0x10000,--dynamicbase,--pic-executable,-e,mainCRTStartup )
endif()
endif()
if(LIBUV_ROOT)

@ -0,0 +1,13 @@
Place in `/etc/NetworkManager/dnsmasq.d/lokinet.conf`.
To make use of this, first install dnsmasq.
Then enable NetworkManager dnsmasq backend by editing `/etc/NetworkManager/NetworkManager.conf` to something like:
```
[main]
dns=dnsmasq
```
If NetworkManager is currently running, restart it for changes to take effect:
```
sudo systemctl restart NetworkManager
```

@ -0,0 +1 @@
server=/loki/snode/127.3.2.1

@ -0,0 +1,27 @@
#!/usr/bin/env bash
# Script used with Drone CI to check that a statically build lokinet only links against the expected
# base system libraries. Expects to be run with pwd of the build directory.
set -o errexit
bad=
if [ "$DRONE_STAGE_OS" == "darwin" ]; then
if otool -L daemon/lokinet | grep -Ev '^daemon/lokinet:|^\t(/usr/lib/libSystem\.|/usr/lib/libc\+\+\.|/System/Library/Frameworks/CoreFoundation)'; then
bad=1
fi
elif [ "$DRONE_STAGE_OS" == "linux" ]; then
if ldd daemon/lokinet | grep -Ev '(linux-vdso|ld-linux-x86-64|lib(pthread|dl|rt|stdc\+\+|gcc_s|c|m))\.so'; then
bad=1
fi
else
echo -e "\n\n\n\n\e[31;1mDon't know how to check linked libs on $DRONE_STAGE_OS\e[0m\n\n\n"
exit 1
fi
if [ -n "$bad" ]; then
echo -e "\n\n\n\n\e[31;1mlokinet links to unexpected libraries\e[0m\n\n\n"
exit 1
fi
echo -e "\n\n\n\n\e[32;1mNo unexpected linked libraries found\e[0m\n\n\n"

@ -0,0 +1,50 @@
#!/bin/bash
# Script used with Drone CI to upload debs from the deb building pipelines (because specifying all
# this in .drone.jsonnet is too painful). This is expected to run from the base project dir after
# having build with debuild (which will leave the debs in ..).
set -o errexit
distro="$1"
if [ -z "$distro" ]; then
echo "Bad usage: need distro name as first argument"
exit 1
fi
if [ -z "$SSH_KEY" ]; then
echo -e "\n\n\n\e[31;1mUnable to upload debs: SSH_KEY not set\e[0m"
# Just warn but don't fail, so that this doesn't trigger a build failure for untrusted builds
exit 0
fi
echo "$SSH_KEY" >~/ssh_key
set -o xtrace # Don't start tracing until *after* we write the ssh key
chmod 600 ~/ssh_key
upload_to="builds.lokinet.dev/debs/${DRONE_REPO// /_}@${DRONE_BRANCH// /_}/$(date --date=@$DRONE_BUILD_CREATED +%Y%m%dT%H%M%SZ)-${DRONE_COMMIT:0:9}/$distro/$DRONE_STAGE_ARCH"
# sftp doesn't have any equivalent to mkdir -p, so we have to split the above up into a chain of
# -mkdir a/, -mkdir a/b/, -mkdir a/b/c/, ... commands. The leading `-` allows the command to fail
# without error.
upload_dirs=(${upload_to//\// })
mkdirs=
dir_tmp=""
for p in "${upload_dirs[@]}"; do
dir_tmp="$dir_tmp$p/"
mkdirs="$mkdirs
-mkdir $dir_tmp"
done
sftp -i ~/ssh_key -b - -o StrictHostKeyChecking=off drone@builds.lokinet.dev <<SFTP
$mkdirs
put ../*.*deb $upload_to
SFTP
set +o xtrace
echo -e "\n\n\n\n\e[32;1mUploaded debs to https://${upload_to}/\e[0m\n\n\n"

@ -0,0 +1,5 @@
#!/usr/bin/env bash
test "x$IGNORE" != "x" && exit 0
repo=$(readlink -e $(dirname $0)/../../)
clang-format-9 -i $(find $repo/jni $repo/daemon $repo/llarp $repo/include $repo/pybind | grep -E '\.[hc](pp)?$')
git --no-pager diff --exit-code --color || (echo -ne '\n\n\e[31;1mLint check failed; please run ./contrib/format.sh\e[0m\n\n' ; exit 1)

@ -0,0 +1,5 @@
#!/usr/bin/env bash
rm -f crash.out.txt exit.out.txt
gdb -q -x $(readlink -e $(dirname $0))/gdb-filter.py --args $@
test -e crash.out.txt && cat crash.out.txt
exit $(cat exit.out.txt)

@ -0,0 +1,6 @@
#!/usr/bin/env bash
export PYTHONPATH=pybind
rm -f crash.out.txt exit.out.txt
gdb -q -x $(readlink -e $(dirname $0))/gdb-filter.py --args /usr/bin/python3 -m pytest ../test/
test -e crash.out.txt && cat crash.out.txt
exit $(cat exit.out.txt)

@ -0,0 +1,71 @@
#!/usr/bin/env bash
# Script used with Drone CI to upload build artifacts (because specifying all this in
# .drone.jsonnet is too painful).
set -o errexit
if [ -z "$SSH_KEY" ]; then
echo -e "\n\n\n\e[31;1mUnable to upload artifact: SSH_KEY not set\e[0m"
# Just warn but don't fail, so that this doesn't trigger a build failure for untrusted builds
exit 0
fi
echo "$SSH_KEY" >ssh_key
set -o xtrace # Don't start tracing until *after* we write the ssh key
chmod 600 ssh_key
os="$DRONE_STAGE_OS-$DRONE_STAGE_ARCH"
if [ -n "$WINDOWS_BUILD_NAME" ]; then
os="windows-$WINDOWS_BUILD_NAME"
fi
if [ -n "$DRONE_TAG" ]; then
# For a tag build use something like `lokinet-linux-amd64-v1.2.3`
base="lokinet-$os-$DRONE_TAG"
else
# Otherwise build a length name from the datetime and commit hash, such as:
# lokinet-linux-amd64-20200522T212342Z-04d7dcc54
base="lokinet-$os-$(date --date=@$DRONE_BUILD_CREATED +%Y%m%dT%H%M%SZ)-${DRONE_COMMIT:0:9}"
fi
mkdir -v "$base"
if [ -e daemon/lokinet.exe ]; then
cp -av daemon/lokinet.exe daemon/lokinet-vpn.exe ../lokinet-bootstrap.ps1 "$base"
# zipit up yo
archive="$base.zip"
zip -r "$archive" "$base"
else
cp -av daemon/lokinet daemon/lokinet-vpn ../lokinet-bootstrap "$base"
# tar dat shiz up yo
archive="$base.tar.xz"
tar cJvf "$archive" "$base"
fi
upload_to="builds.lokinet.dev/${DRONE_REPO// /_}/${DRONE_BRANCH// /_}"
# sftp doesn't have any equivalent to mkdir -p, so we have to split the above up into a chain of
# -mkdir a/, -mkdir a/b/, -mkdir a/b/c/, ... commands. The leading `-` allows the command to fail
# without error.
upload_dirs=(${upload_to//\// })
mkdirs=
dir_tmp=""
for p in "${upload_dirs[@]}"; do
dir_tmp="$dir_tmp$p/"
mkdirs="$mkdirs
-mkdir $dir_tmp"
done
sftp -i ssh_key -b - -o StrictHostKeyChecking=off drone@builds.lokinet.dev <<SFTP
$mkdirs
put $archive $upload_to
SFTP
set +o xtrace
echo -e "\n\n\n\n\e[32;1mUploaded to https://${upload_to}/${archive}\e[0m\n\n\n"

@ -0,0 +1,36 @@
def exit_handler (event):
"""
write exit code of the program running in gdb to a file called exit.out.txt
"""
code = 1
if hasattr(event, "exit_code"):
code = event.exit_code
with open("exit.out.txt", 'w') as f:
f.write("{}".format(code))
def gdb_execmany(*cmds):
"""
run multiple gdb commands
"""
for cmd in cmds:
gdb.execute(cmd)
def crash_handler (event):
"""
handle a crash from the program running in gdb
"""
if isinstance(event, gdb.SignalEvent):
log_file_name = "crash.out.txt"
# poop out log file for stack trace of all threads
gdb_execmany("set logging file {}".format(log_file_name), "set logging on", "set logging redirect on", "thread apply all bt full")
# quit gdb
gdb.execute("q")
# set up event handlers to catch shit
gdb.events.stop.connect(crash_handler)
gdb.events.exited.connect(exit_handler)
# run settings setup
gdb_execmany("set confirm off", "set pagination off", "set print thread-events off")
# run program and exit
gdb_execmany("r", "q")

@ -1,3 +0,0 @@
#!/bin/sh
rm -fr loki*/tmp-nodes
rm loki*/profile.dat

@ -1,9 +0,0 @@
#!/bin/sh
# copy a lokinet binary into this cluster
cp ../../lokinet .
# generate default config file
./lokinet -g -r lokinet.ini
# make seed node
./makenode.sh 1
# establish bootstrap
ln -s loki1/self.signed bootstrap.signed

@ -1,7 +0,0 @@
mkdir loki$1
cd loki$1
ln -s ../lokinet lokinet$1
cp ../lokinet.ini .
nano lokinet.ini
cd ..
echo "killall -9 lokinet$1" >> ../stop.sh

@ -1,16 +0,0 @@
#!/bin/bash
set +x
cd loki1
nohup ./lokinet1 $PWD/lokinet.ini &
# seed node needs some time to write RC to make sure it's not expired on load for the rest
sleep 1
cd ../loki2
nohup ./lokinet2 $PWD/lokinet.ini &
cd ../loki3
nohup ./lokinet3 $PWD/lokinet.ini &
cd ../loki4
nohup ./lokinet4 $PWD/lokinet.ini &
cd ../loki5
nohup ./lokinet5 $PWD/lokinet.ini &
cd ..
tail -f loki*/nohup.out

@ -1,7 +0,0 @@
#!/bin/sh
killall -9 lokinet1
killall -9 lokinet2
killall -9 lokinet3
killall -9 lokinet4
killall -9 lokinet5
killall -9 lokinet6

@ -0,0 +1,12 @@
set(CMAKE_SYSTEM_NAME Linux)
set(TOOLCHAIN_PREFIX aarch64-linux-gnu)
#set(TOOLCHAIN_SUFFIX)
set(CMAKE_FIND_ROOT_PATH /usr/${TOOLCHAIN_PREFIX})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc${TOOLCHAIN_SUFFIX})
set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++${TOOLCHAIN_SUFFIX})

@ -1,8 +1,7 @@
set(CMAKE_SYSTEM_NAME Windows)
set(TOOLCHAIN_PREFIX i686-w64-mingw32)
set(TOOLCHAIN_SUFFIX "-posix")
set(WOW64_CROSS_COMPILE ON)
set(LIBSODIUM_CROSS_TARGET i686-w64-mingw32)
set(CROSS_TARGET i686-w64-mingw32)
set(TOOLCHAIN_PATHS
/usr/${TOOLCHAIN_PREFIX}

@ -1,8 +1,7 @@
set(CMAKE_SYSTEM_NAME Windows)
set(TOOLCHAIN_PREFIX x86_64-w64-mingw32)
set(TOOLCHAIN_SUFFIX "-posix")
set(WIN64_CROSS_COMPILE ON)
set(LIBSODIUM_CROSS_TARGET x86_64-w64-mingw32)
set(CROSS_TARGET x86_64-w64-mingw32)
set(TOOLCHAIN_PATHS
/usr/${TOOLCHAIN_PREFIX}

@ -1,4 +1,4 @@
set(CMAKE_SYSTEM_VERSION 6.0)
set(CMAKE_SYSTEM_VERSION 5.0)
# target environment on the build host system
# second one is for non-root installs
@ -20,7 +20,8 @@ if($ENV{COMPILER} MATCHES "clang")
else()
set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc${TOOLCHAIN_SUFFIX})
set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++${TOOLCHAIN_SUFFIX})
add_compile_options("-Wa,-mbig-obj")
endif()
set(CMAKE_RC_COMPILER ${TOOLCHAIN_PREFIX}-windres)
set(CMAKE_CROSSCOMPILE ON)
set(ARCH_TRIPLET ${CROSS_TARGET})

@ -0,0 +1,12 @@
diff --git a/tests/testutil.hpp b/tests/testutil.hpp
index c6f5e4de..6a1c8bb8 100644
--- a/tests/testutil.hpp
+++ b/tests/testutil.hpp
@@ -102,7 +102,6 @@ const uint8_t zmtp_ready_sub[27] = {
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdexcept>
-#define close closesocket
typedef int socket_size_t;
inline const char *as_setsockopt_opt_t (const void *opt)
{

@ -0,0 +1,5 @@
#!/usr/bin/env bash
# TODO: readlink -e is a GNU-ism
cd "$(readlink -e $(dirname $0)/../)"
clang-format-9 -i $(find jni daemon llarp include pybind | grep -E '\.[hc](pp)?$') &> /dev/null

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

@ -0,0 +1,61 @@
#!/usr/bin/python3
import sys
base32z_dict = 'ybndrfg8ejkmcpqxot1uwisza345h769'
base32z_map = {base32z_dict[i]: i for i in range(len(base32z_dict))}
def lokinet_snode_addr(pk_hex):
"""Returns the lokinet snode address from a hex ed25519 pubkey"""
assert(len(pk_hex) == 64)
bits = 0
val = 0
result = ''
for x in pk_hex:
bits += 4
val = (val << 4) + int(x, 16)
if bits >= 5:
bits -= 5
v = val >> bits
val &= (1 << bits) - 1
result += base32z_dict[v]
result += base32z_dict[val << (5 - bits)]
return result + ".snode"
def hex_from_snode(b32z):
"""undoes what the above does; b32z should have '.snode' already stripped off"""
assert(len(b32z) == 52)
val = 0
bits = 0
for x in b32z:
val = (val << 5) | base32z_map[x] # Arbitrary precision integers FTW
# `val` is now a 260 bit value (52 * 5 bits per char); but we only use the first bit of the last
# value (which is why lokinet addresses always end with y or o)
assert(b32z[-1] in 'yo')
val >>= 4
return "{:64x}".format(val)
reverse = False
if len(sys.argv) >= 2 and sys.argv[1] == '-r':
reverse = True
del sys.argv[1]
if len(sys.argv) < 2 or (
any(len(x) not in (52, 58) for x in sys.argv[1:])
if reverse else
any(len(x) != 64 for x in sys.argv[1:])
):
print("Usage: {} PUBKEY [PUBKEY ...] -- converts ed25519 pubkeys to .snode addresses".format(sys.argv[0]))
print("Usage: {} -r SNODE [SNODE ...] -- converts snode addresses to ed25519 pubkeys".format(sys.argv[0]))
sys.exit(1)
if reverse:
for key in sys.argv[1:]:
print("{}.snode -> {}".format(key[0:52], hex_from_snode(key[0:52])))
else:
for key in sys.argv[1:]:
print("{} -> {}".format(key, lokinet_snode_addr(key)))

@ -1,80 +0,0 @@
apiVersion: v1
kind: Service
metadata:
name: loki-network
labels:
app: loki-network
spec:
type: NodePort
ports:
- protocol: UDP
port: 1090
name: udp-1
targetPort: 1090
- protocol: UDP
port: 1190
name: udp-2
targetPort: 1190
selector:
app: loki-network
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
annotations:
description: loki-network lokinet
keel.sh/pollSchedule: "@every 1m"
keel.sh/notify: deployments # chat channels to sent notification to
generation: 1
labels:
app: loki-network
keel.sh/policy: force # update policy (available: patch, minor, major, all, force)
keel.sh/trigger: poll # enable active repository checking (webhooks and GCR would still work)
keel.sh/approvals: "0" # required approvals to update
keel.sh/match-tag: "true" # only makes a difference when used with 'force' policy, will only update if tag matches :dev->:dev, :prod->:prod
name: loki-network
spec:
progressDeadlineSeconds: 600
replicas: 3
revisionHistoryLimit: 20
selector:
matchLabels:
app: loki-network
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
annotations:
description: loki-network lokinet
creationTimestamp: null
labels:
app: loki-network
name: loki-network
spec:
containers:
- image: 092763672147.dkr.ecr.us-east-1.amazonaws.com/loki/loki-network:latest
imagePullPolicy: Always
name: loki-network
securityContext:
privileged: true
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
ports:
- protocol: UDP
containerPort: 1090
name: udp-1
- protocol: UDP
containerPort: 1190
name: udp-2
dnsPolicy: "None"
dnsConfig:
nameservers:
- 127.0.0.1
- 1.1.1.1
restartPolicy: Always
schedulerName: default-scheduler
terminationGracePeriodSeconds: 30
status: {}

@ -1,11 +0,0 @@
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: lokid-lokinet
namespace: kube-system
labels:
k8s-app: fluentd-logging
spec:
selector:
matchLabels:
name:

@ -1,30 +0,0 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: loki-deployment
labels:
app: loki-svc-node
spec:
replicas: 2
selector:
matchLabels:
app: loki-svc-node
template:
metadata:
labels:
app: loki-svc-node
spec:
containers:
- name: loki-svc-node
image: jaaff/loki-svc-kubernetes
ports:
- protocol: TCP
port: 22022
targetPort: 22022
- protocol: TCP
port: 22023
targetPort: 22023
- protocol: UDP
port: 1090
targetPort: 1090

@ -1,13 +0,0 @@
kind: Service
apiVersion: v1
metadata:
name: lokinet
labels:
app: lokinet
spec:
selector:
app: lokinet
ports:
- protocol: UDP
port: 1090
targetPort: 1090

@ -1,7 +0,0 @@
# kuberentes cluster
this contains stuff for kuberenetes
usage:
$

@ -6,7 +6,6 @@ sleep 5 # Give it some time to shut down before we bring launchd into this
launchctl stop network.loki.lokinet.daemon
launchctl unload /Library/LaunchDaemons/network.loki.lokinet.daemon.plist
rm -rf /Library/LaunchDaemons/network.loki.lokinet.daemon.plist
rm -rf /Applications/LokinetGUI.app
rm -rf /var/lib/lokinet

@ -1,26 +0,0 @@
# Building / Running
after building lokinet
```
cd contrib/node-monitor
npm install
sudo node monitor_client.js
```
and wait 30 minutes for final score
# Scoring
Lokinet gets a point for everything it does correctly.
Currently:
- succesful ping to snode (1 per second after a snode is discovered)
- session with snode established
- got a router from exploration
- Handling DHT S or R message
- a path is built
- obtained an exit via
- granted exit
- IntroSet publish confirmed
- utp.session.sendq. has a min zero count (no blocked buffers on routers)

@ -1,61 +0,0 @@
function iniToJSON(data) {
const lines = data.split(/\n/)
var section = 'unknown'
var config = {}
for (var i in lines) {
var line = lines[i].trim()
if (line.match(/#/)) {
var parts = line.split(/#/)
line = parts[0].trim()
}
// done reducing
if (!line) continue
// check for section
if (line[0] == '[' && line[line.length - 1] == ']') {
section = line.substring(1, line.length - 1)
//console.log('found section', section)
continue
}
// key value pair
if (line.match(/=/)) {
var parts = line.split(/=/)
var key = parts.shift().trim()
var value = parts.join('=').trim()
if (value === 'true') value = true
if (value === 'false') value = false
//console.log('key/pair ['+section+']', key, '=', value)
if (config[section] === undefined) config[section] = {}
config[section][key] = value
continue
}
console.error('config [' + section + '] not section or key/value pair', line)
}
return config
}
function jsonToINI(json) {
var config = ''
for (var section in json) {
config += "\n" + '[' + section + ']' + "\n"
var keys = json[section]
for (var key in keys) {
//console.log('key', key, 'value', keys[key])
// if keys[key] is an array, then we need to send the same key each time
if (keys[key] !== undefined && keys[key].constructor.name == 'Array') {
for (var i in keys[key]) {
var v = keys[key][i]
config += key + '=' + v + "\n"
}
} else {
config += key + '=' + keys[key] + "\n"
}
}
}
return config
}
module.exports = {
iniToJSON: iniToJSON,
jsonToINI: jsonToINI,
}

File diff suppressed because it is too large Load Diff

@ -1,323 +0,0 @@
const lokinet = require('./lokinet') // currently using the 0.5 api
const fs = require('fs')
const ping = require("net-ping")
// horrible library that shells out to use ping...
//const ping = require('ping')
// score successful actions
// while we monitor snode and loki addresses
var session = ping.createSession()
// probably should nuke profiles.dat each round to level the playing field
if (fs.existsSync('profiles.dat')) {
console.log('cleaning router profiles')
fs.unlinkSync('profiles.dat')
}
//
// start config
//
// FIXME: take in a binary_path as an option...
var lokinet_config = {
binary_path: '../../lokinet',
// clients will default to i2p.rocks
// bootstrap_url : 'http://206.81.100.174/n-st-1.signed',
// rpc_ip : '127.0.0.1',
// rpc_port : 28082,
// auto_config_test_host: 'www.google.com',
// auto_config_test_port: 80,
// testnet : true,
// verbose : true,
}
score_time = null
score_total = 0
var lokinet_version = 'unknown'
var known_snodes = []
var snodes_stats = {}
function addSnode(snode) {
var idx = known_snodes.indexOf(snode)
if (idx == -1) {
known_snodes.push(snode)
function lookupSnode(snode) {
lokinet.lookup(snode, function (records) {
console.log(snode, 'mapped to', records)
// if no response or not found, retry
if (records === undefined || records === null) {
// failure retry
setTimeout(function () {
console.log('retry lookup for', snode)
lookupSnode(snode)
}, 5000)
return
}
if (!records) {
console.log('records is false', records)
return
}
if (!records.length) {
console.log('record is empty array')
return
}
var ip = records[0]
// reset stats
snodes_stats[snode] = {
onlines: 0,
offlines: 0,
}
// trigger monitor update?
setInterval(function () {
/*
ping.sys.probe(ip, function(isAlive){
if (isAlive) {
//console.log(snode, ip, 'is online')
snodes_stats[snode].onlines++
score_total++
} else {
console.log(snode, ip, 'is offline')
snodes_stats[snode].offlines++
}
})
*/
session.pingHost(ip, function (err, target) {
if (err) {
console.warn(target, 'ping err', err);
console.log(snode, ip, 'is offline')
snodes_stats[snode].offlines++
} else {
//console.log (target + ": Alive")
//console.log(snode, ip, 'is online')
snodes_stats[snode].onlines++
score_total++
}
})
}, 1000)
})
}
lookupSnode(snode)
}
}
setInterval(function () {
// can be known but not mapped yet...
console.log('snode score card,', known_snodes.length, 'known routers')
for (var snode in snodes_stats) {
var stats = snodes_stats[snode]
var total = stats.onlines + stats.offlines
var onlinePer = (stats.onlines / total) * 100
console.log(snode, stats, onlinePer + '%')
}
}, 30 * 1000)
lokinet.onMessage = function (data) {
console.log(`monitor: ${data}`)
var lines = data.split(/\n/)
for (var i in lines) {
var tline = lines[i].trim()
// lokinet-0.4.0-59e6a4bc (dev build)
if (tline.match('lokinet-0.')) {
var parts = tline.split('lokinet-0.')
lokinet_version = parts[1]
console.log('VERSION', parts[1])
}
if (tline.match('Using config file:')) {
// get bootstrap info
var parts = tline.split('Using config file: ')
console.log('CONFIGFILE', parts[1])
}
if (tline.match('Added bootstrap node')) {
// get bootstrap info
var parts = tline.split('Added bootstrap node ')
addSnode(parts[1])
console.log('BOOTSTRAP', parts[1])
}
if (tline.match('Set Up networking for')) {
// get interface info
var parts = tline.split('Set Up networking for ')
// default:9j4uido1ai7ucirbncbqii1395e8ccd6cjomo9cccp3ztx1ukwio.loki
console.log('INTERFACE', parts[1])
}
//
if (tline.match('session with ')) {
// potential node
var parts = tline.split('session with ')
if (parts.length) {
var one = parts[1].replace(' established', '')
var two = one.split('.snode') // snode\u001b[0;0m
var snode = two[0] + '.snode'
addSnode(snode)
console.log('SESSION', snode)
score_total++
} else {
console.log('unknown session line', tline)
}
}
if (tline.match(' routers from exploration')) {
var parts = tline.split('\tgot ')
if (parts.length > 1) {
var routers = parts[1].replace(' routers from exploration', '')
console.log('ROUTERS', routers)
if (routers && routers != '0') {
score_total++
}
} else {
console.log('unknown exploration line', tline)
}
}
// ?
if (tline.match('Handle DHT message S relayed=0')) {
score_total++
}
// relay DHT packet
if (tline.match('Handle DHT message R relayed=0')) {
score_total++
}
//
if (tline.match(' is built, took ')) {
// path TX=8826efd28bede66c59782af9894eed08 RX=a994770a8c6d61700b8ca65e4a3adea3 on OBContext:default:3y3ch3m6c8xgmutxwe8fger6n963hn3mkn6tk14j67w1zdxj1n1y.loki-icxqqcpd3sfkjbqifn53h7rmusqa1fyxwqyfrrcgkd37xcikwa7y.loki is built, took 2321 ms
var parts = tline.split('path TX=')
if (parts.length > 1) {
var two = parts[1].split(' RX=')
if (two.length > 1) {
var tx = two[0]
var three = two[1].split(' on OBContext:')
if (three.length > 1) {
var rx = three[0]
var four = three[1].split(' is built, took ')
if (four.length > 1) {
var context = four[0]
var ms = four[1]
console.log('PATH BUILT', tx, rx, context, ms)
}
}
}
}
score_total++
}
// happen right after the built, took
//TX=53e833fcbad1395647f198201d4931e5 RX=b4768bc4b91b86b51b513319f443f538 on default:dnhi78pwrn6cd5yz83i83816nqudwym57s5x4bp3j4g5kbeigw5y.loki built latency=291
if (tline.match(' is built latency ')) {
// path latency info
}
//[WRN] (166) Tue Apr 30 15:26:25 2019 PDT path/pathbuilder.cpp:319 SNode::8ti485iig9q1wd6k9qr6dqmswrqp9hceohcrtwwa7pn6wcxx9wdy.snode failed to select hop 3
// not a sure but snode extract
if (tline.match('.snode failed to select hop')) {
var parts = tline.split('SNode::')
//console.log('failed to select hop parts', parts)
if (parts.length > 1) {
var two = parts[1].split(' failed to select hop ')
if (two.length) {
var hops = two[1]
//console.log('hopSelectionFailure', snode, hops)
}
}
}
//obtained an exit via nc9y88xsr7cqmpytc6tbo5dbf5c9fa3is5dezmdwxwgfkuhemg3o.snode
if (tline.match('obtained an exit via ')) {
var parts = tline.split('obtained an exit via ')
if (parts.length > 1) {
var two = parts[1].split('.snode')
var snode = two[0] + '.snode'
addSnode(snode)
}
score_total++
}
//TX=219222f0f390e40ce47745af292001f2 RX=671c259dd9590173019694fc10433b63 on SNode::nc9y88xsr7cqmpytc6tbo5dbf5c9fa3is5dezmdwxwgfkuhemg3o.snode nc9y88xsr7cqmpytc6tbo5dbf5c9fa3is5dezmdwxwgfkuhemg3o.snode Granted exit
if (tline.match('Granted exit')) {
var one = tline.split('TX=')
if (one.length > 1) {
var two = one[1].split(' RX=')
if (two.length > 1) {
var three = two[1].split(' on SNode::')
if (three.length > 1) {
var tx = two[0]
var rx = three[0]
console.log('EXIT', tx, rx, 'rest', three[1])
}
}
}
score_total++
}
//service/endpoint.cpp:652 default:kzow69uftho8ukm8g4kf88y5zka84azfrmfx5okkmrg7ucdz5d1o.loki IntroSet publish confirmed
if (tline.match('IntroSet publish confirmed')) {
score_total++
}
}
}
lokinet.onError = function (data) {
console.log(`monitorerr: ${data}`)
// start on 2019-04-30T15:40:55.540314745-07:00 X Records
// buffer until
// end on \n\n
var lines = data.toString().split(/\n/)
for (var i in lines) {
var tline = lines[i].trim()
if (tline.match('utp.session.sendq.')) {
//console.log('sendq')
var one = tline.split('utp.session.sendq.')
// parts[1] = 8ti485iig9q1wd6k9qr6dqmswrqp9hceohcrtwwa7pn6wcxx9wdy.snode [
// count = 282, total = 3, min = 0, max = 1 ]
if (one.length > 1) {
var two = one[1].split(' [ ')
if (two.length > 1) {
var snode = two[0]
var three = two[1].split(', ')
if (three.length > 3) {
var count = three[0]
var total = three[1]
var min = three[2]
if (min == 'min = 0') {
//console.log('no bloat')
// not sure if this is related to our version or not...
score_total++
}
var max = three[3]
console.log('UTPSENDQ', snode, count, total, min, max)
}
}
}
}
}
}
//
// end config
//
function checkIP(cb) {
lokinet.getLokiNetIP(function (ip) {
if (ip === undefined) {
checkIP(cb)
return
}
//console.log('lokinet interface ip', ip)
cb(ip)
})
}
lokinet.startClient(lokinet_config, function () {
// lokinet isn't necessarily running at this point
console.log('Starting monitor')
score_time = Date.now()
checkIP(function (ip) {
console.log('lokinet interface ip', ip)
lokinet.findLokiNetDNS(function (servers) {
console.log('monitor detected DNS Servers', servers)
})
setInterval(function () {
console.log('score', score_total, 'time', ((Date.now() - score_time) / 1000))
}, 30000)
// maybe run until a specific time and quit for comparison
// 1200s (two 10min sessions)
setTimeout(function () {
console.log(lokinet_config.binary_path, 'version', lokinet_version, 'final score', score_total)
process.exit()
}, 3 * 600 * 1000) // 3x 10m sessions worth
})
})

@ -1,29 +0,0 @@
{
"name": "lokinet-monitor",
"version": "0.0.1",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"nan": {
"version": "2.10.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.10.0.tgz",
"integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA=="
},
"net-ping": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/net-ping/-/net-ping-1.2.3.tgz",
"integrity": "sha512-ZKxj/kVPKL2RIsV9nR6I8nMT8Pi3k6ciTBKxD/6gd5lga9qcNmlyqNv+dbXqYGBvHsmG9yIpsfajr8X054x2fQ==",
"requires": {
"raw-socket": "*"
}
},
"raw-socket": {
"version": "1.6.4",
"resolved": "https://registry.npmjs.org/raw-socket/-/raw-socket-1.6.4.tgz",
"integrity": "sha512-ab/By3tp0gTDzwEJxgKUv+uIma0JFVnJElNMKNAqNiET+GQ2VAfR6eUVfnm0yRG/vxGu8gO2BYWhR30sQOTebg==",
"requires": {
"nan": "2.10.*"
}
}
}
}

@ -1,25 +0,0 @@
{
"name": "lokinet-monitor",
"version": "0.0.1",
"description": "Lokinet monitor",
"main": "monitor_client.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/loki-project/loki-network.git"
},
"keywords": [
"lokinet"
],
"author": "Ryan Tharp",
"license": "ISC",
"bugs": {
"url": "https://github.com/loki-project/loki-network/issues"
},
"homepage": "https://github.com/loki-project/loki-network#readme",
"dependencies": {
"net-ping": "^1.2.3"
}
}

@ -1,3 +0,0 @@
node_modules
build
*.log

@ -1,15 +0,0 @@
{
"targets": [
{
"target_name": "lokinet",
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"sources": [ "lokinet.cc" ],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
}
]
}

@ -1,62 +0,0 @@
#include <napi.h>
#include <llarp.hpp>
struct Lokinet : public Napi::ObjectWrap< Lokinet >
{
llarp::Context ctx;
static Napi::Object
Init(Napi::Env env, Napi::Object exports)
{
Napi::HandleScope scope(env);
Napi::Function func =
DefineClass(env, "Lokinet",
{InstanceMethod("configure", &Lokinet::Configure),
InstanceMethod("run", &Lokient::Run),
InstanceMethod("kill", &Lokinet::Kill)});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
exports.Set("Lokinet", func);
return exports;
};
Napi::Value
Configure(const Napi::CallbackInfo& info)
{
if(info.Length() != 1 || !info[0].IsString())
{
Napi::TypeError::New(env, "String expected").ThrowAsJavaScriptException();
}
bool result = ctx.LoadConfig(info[0].As< std::string >());
if(result)
{
result &= ctx.Setup() == 0;
}
return Napi::Value(info.Env(), result);
}
Napi::Value
Run(const Napi::CallbackInfo& info)
{
bool result = ctx.Run() == 0;
return Napi::Value(info.Env(), result);
}
Napi::Value
Kill(const Napi::CallbackInfo& info)
{
bool result = ctx.Stop();
return Napi::Value(info.Env(), result);
}
};
Napi::Object
InitAll(Napi::Env env, Napi::Object exports)
{
return Lokinet::Init(env, exports);
}
NODE_API_MODULE(addon, InitAll)

@ -1,2 +0,0 @@
var lokinet = require("bindings")("lokinet");
console.log(lokinet);

@ -1,158 +1,187 @@
#!/usr/bin/env python3
import requests
import curses
import json
import sys
import time
import curses
import math
import traceback
import zmq
class Monitor:
_speedSamples = 8
_globalspeed = []
_sample_size = 12
def __init__(self, url):
self.txrate = 0
self.rxrate = 0
self.data = dict()
self.win = curses.initscr()
self._url = url
while len(self._globalspeed) < self._speedSamples:
self._globalspeed.append((0, 0))
def __del__(self):
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
self._rpc_context = zmq.Context()
self._rpc_socket = self._rpc_context.socket(zmq.DEALER)
self._rpc_socket.setsockopt(zmq.CONNECT_TIMEOUT, 5000)
self._rpc_socket.setsockopt(zmq.HANDSHAKE_IVL, 5000)
self._rpc_socket.connect(url)
self._speed_samples = [(0,0,0,0)] * self._sample_size
self._run = True
def rpc(self, method):
self._rpc_socket.send_multipart([method.encode(), b'lokinetmon'+method.encode()])
if not self._rpc_socket.poll(timeout=50):
return
reply = self._rpc_socket.recv_multipart()
if len(reply) >= 3 and reply[0:2] == [b'REPLY', b'lokinetmon'+method.encode()]:
return reply[2].decode()
def _close(self):
self._rpc_socket.close(linger=0)
self._run = False
curses.endwin()
def on_timer(self, event):
"""called on timer event"""
self.update_data()
def jsonrpc(self, meth, params):
r = requests.post(
self._url,
headers={"Content-Type": "application/json"},
json={
"jsonrpc": "2.0",
"id": "0",
"method": "{}".format(meth),
"params": params,
},
)
return r.json()
def update_data(self):
"""update data from lokinet"""
try:
j = self.jsonrpc("llarp.admin.dumpstate", {})
self.data = j["result"]
except Exception as ex:
self.data = json.loads(self.rpc("llarp.status"))
except:
self.data = None
return self.data is not None and self._run
def _render_path(self, y, path, name):
def _render_path(self, y_pos, path, name):
"""render a path at current position"""
self.win.move(y, 1)
self.win.move(y_pos, 1)
self.win.addstr("({}) ".format(name))
y += 1
self.win.move(y, 1)
y += 1
self.win.addstr("[tx:\t{}]\t[rx:\t{}]".format(self.speedOf(path['txRateCurrent']), self.speedOf(path['rxRateCurrent'])))
self.win.move(y, 1)
y += 1
y_pos += 1
self.win.move(y_pos, 1)
y_pos += 1
self.win.addstr("[tx:\t{}]\t[rx:\t{}]".format(
self.speed_of(path['txRateCurrent']), self.speed_of(path['rxRateCurrent'])))
self.win.move(y_pos, 1)
y_pos += 1
self.win.addstr("me -> ")
for hop in path["hops"]:
self.win.addstr(" {} ->".format(hop["router"][:4]))
self.win.addstr(" [{} ms latency]".format(path["intro"]["latency"]))
self.win.addstr(" [{} until expire]".format(self.timeTo(path["expiresAt"])))
self.win.addstr(" [{} until expire]".format(self.time_to(path["expiresAt"])))
if path["expiresSoon"]:
self.win.addstr("(expiring)")
elif path["expired"]:
self.win.addstr("(expired)")
return y
return y_pos
def timeTo(self, ts):
@staticmethod
def time_to(timestamp):
""" return time until timestamp in seconds formatted"""
now = time.time() * 1000
return "{} seconds".format(int((ts - now) / 1000))
return "{} seconds".format(int((timestamp - now) / 1000))
def speedOf(self, rate):
@staticmethod
def speed_of(rate):
"""turn int speed into string formatted"""
units = ["B", "KB", "MB", "GB"]
units = ["b", "Kb", "Mb", "Gb"]
idx = 0
rate *= 8
while rate > 1000 and idx < len(units):
rate /= 1000.0
idx += 1
return "{} {}ps".format("%.2f" % rate, units[idx])
def display_service(self, y, name, status):
def get_all_paths(self):
""" yield all paths in current data """
for key in self.data['services']:
status = self.data['services'][key]
for path in (status['paths'] or []):
yield path
for sess in (status['remoteSessions'] or []):
for path in sess['paths']:
yield path
for sess in (status['snodeSessions'] or []):
for path in sess['paths']:
yield path
def display_service(self, y_pos, name, status):
"""display a service at current position"""
self.win.move(y, 1)
self.win.move(y_pos, 1)
self.win.addstr("service [{}]".format(name))
build = status["buildStats"]
ratio = build["success"] / (build["attempts"] or 1)
y += 1
self.win.move(y, 1)
y_pos += 1
self.win.move(y_pos, 1)
self.win.addstr("build success: {} %".format(int(100 * ratio)))
y += 1
self.win.move(y, 1)
y_pos += 1
self.win.move(y_pos, 1)
paths = status["paths"]
self.win.addstr("paths: {}".format(len(paths)))
for path in paths:
y = self._render_path(y, path, "inbound")
y_pos = self._render_path(y_pos, path, "inbound")
for session in (status["remoteSessions"] or []):
for path in session["paths"]:
y = self._render_path(
y, path, "[active] {}".format(session["currentConvoTag"])
y_pos = self._render_path(
y_pos, path, "[active] {}".format(session["currentConvoTag"])
)
for session in (status["snodeSessions"] or []):
for path in session["paths"]:
y = self._render_path(y, path, "[snode]")
return y
y_pos = self._render_path(y_pos, path, "[snode]")
return y_pos
# for k in status:
# self.win.move(y + 1, 1)
# y += 1
# self.win.addstr('{}: {}'.format(k, json.dumps(status[k])))
def display_links(self, y, data):
def display_links(self, y_pos, data):
""" display links section """
self.txrate = 0
self.rxrate = 0
for link in data["outbound"]:
y += 1
self.win.move(y, 1)
y_pos += 1
self.win.move(y_pos, 1)
self.win.addstr("outbound sessions:")
y = self.display_link(y, link)
y_pos = self.display_link(y_pos, link)
for link in data["inbound"]:
y += 1
self.win.move(y, 1)
y_pos += 1
self.win.move(y_pos, 1)
self.win.addstr("inbound sessions:")
y = self.display_link(y, link)
y += 2
self.win.move(y, 1)
y_pos = self.display_link(y_pos, link)
y_pos += 2
self.win.move(y_pos, 1)
self.win.addstr(
"global speed:\t\t[{}\ttx]\t[{}\trx]".format(
self.speedOf(self.txrate), self.speedOf(self.rxrate)
"throughput:\t\t[{}\ttx]\t[{}\trx]".format(
self.speed_of(self.txrate), self.speed_of(self.rxrate)
)
)
bloat_tx, bloat_rx = self.calculate_bloat(self.data['links']['outbound'])
y_pos += 1
self.win.move(y_pos, 1)
self.win.addstr("goodput:\t\t[{}\ttx]\t[{}\trx]".format(
self.speed_of(self.txrate-bloat_tx), self.speed_of(self.rxrate-bloat_rx)))
y_pos += 1
self.win.move(y_pos, 1)
self.win.addstr("overhead:\t\t[{}\ttx]\t[{}\trx]".format(
self.speed_of(bloat_tx), self.speed_of(bloat_rx)))
self._speed_samples.append((self.txrate, self.rxrate, bloat_tx, bloat_rx))
while len(self._speed_samples) > self._sample_size:
self._speed_samples.pop(0)
return self.display_speedgraph(y_pos + 2)
self._globalspeed.append((self.txrate, self.rxrate))
while len(self._globalspeed) > self._speedSamples:
self._globalspeed.pop(0)
return self.display_speedgraph(y + 2, self._globalspeed)
def display_speedgraph(self, y, samps, maxsz=20):
""" display global speed graph """
@staticmethod
def _scale(_x, _n):
while _n > 0:
_x /= 2
_n -= 1
return int(_x)
def scale(x, n):
while n > 0:
x /= 2
n -= 1
return int(x)
txmax, rxmax = 1000, 1000
for tx, rx in samps:
if tx > txmax:
txmax = tx
if rx > rxmax:
rxmax = rx
@staticmethod
def _makebar(samp, badsamp, maxsamp):
barstr = "#" * (samp - badsamp)
pad = " " * (maxsamp - samp)
return pad, barstr, '#' * badsamp
def display_speedgraph(self, y_pos, maxsz=40):
""" display global speed graph """
txmax, rxmax = 1024, 1024
for _tx, _rx, b_tx, b_rx in self._speed_samples:
if _tx > txmax:
txmax = _tx
if _rx > rxmax:
rxmax = _rx
rxscale = 0
while rxmax > maxsz:
@ -164,108 +193,163 @@ class Monitor:
txscale += 1
txmax /= 2
def makebar(samp, max):
bar = "#" * samp
pad = " " * (max - samp)
return pad, bar
txlabelpad = int(txmax / 2) - 1
rxlabelpad = int(rxmax / 2) - 1
txlabelpad = int(txmax / 2)
rxlabelpad = int(rxmax / 2)
if txlabelpad <= 0:
txlabelpad = 1
if rxlabelpad <= 0:
rxlabelpad = 1
txlabelpad = " " * txlabelpad
rxlabelpad = " " * rxlabelpad
y += 1
self.win.move(y, 1)
self.win.addstr(
"{}tx{}{}rx{}".format(txlabelpad, txlabelpad, rxlabelpad, rxlabelpad)
)
for tx, rx in samps:
y += 1
self.win.move(y, 1)
txpad, txbar = makebar(scale(tx, txscale), int(txmax))
rxpad, rxbar = makebar(scale(rx, rxscale), int(rxmax))
self.win.addstr("{}{}|{}{}".format(txpad, txbar, rxbar, rxpad))
return y + 2
txlabelpad_str = " " * txlabelpad
rxlabelpad_str = " " * rxlabelpad
y_pos += 1
self.win.move(y_pos, 1)
for val in [txlabelpad_str, 'tx', txlabelpad_str, rxlabelpad_str, 'rx', rxlabelpad_str]:
self.win.addstr(val)
for _tx, _rx, b_tx, b_rx in self._speed_samples:
y_pos += 1
self.win.move(y_pos, 1)
txpad, txbar, btxbar = self._makebar(self._scale(_tx, txscale), self._scale(b_tx, txscale), int(txmax))
rxpad, rxbar, brxbar = self._makebar(self._scale(_rx, rxscale), self._scale(b_rx, rxscale), int(rxmax))
self.win.addstr(txpad)
self.win.addstr(btxbar, curses.color_pair(1))
self.win.addstr(txbar)
self.win.addstr('|')
self.win.addstr(rxbar)
self.win.addstr(brxbar, curses.color_pair(1))
self.win.addstr(rxpad)
return y_pos + 2
def calculate_bloat(self, links):
"""
calculate bandwith overhead
"""
paths = self.get_all_paths()
lltx = 0
llrx = 0
_tx = 0
_rx = 0
for link in links:
sessions = link["sessions"]["established"]
for sess in sessions:
lltx += sess['tx']
llrx += sess['rx']
for path in paths:
_tx += path['txRateCurrent']
_rx += path['rxRateCurrent']
lltx -= _tx
llrx -= _rx
if lltx < 0:
lltx = 0
if llrx < 0:
llrx = 0
return lltx, llrx
def display_link(self, y, link):
y += 1
self.win.move(y, 1)
def display_link(self, y_pos, link):
""" display links """
y_pos += 1
self.win.move(y_pos, 1)
sessions = link["sessions"]["established"]
for s in sessions:
y += 1
self.win.move(y, 1)
self.txrate += s["txRateCurrent"]
self.rxrate += s["rxRateCurrent"]
self.win.addstr(
"{}\t[{}\ttx]\t[{}\trx]".format(
s["remoteAddr"], self.speedOf(s["txRateCurrent"]), self.speedOf(s["rxRateCurrent"])
)
for sess in sessions:
y_pos = self.display_link_session(y_pos, sess)
return y_pos
def display_link_session(self, y_pos, sess):
""" display link sessions """
y_pos += 1
self.win.move(y_pos, 1)
self.txrate += sess["txRateCurrent"]
self.rxrate += sess["rxRateCurrent"]
self.win.addstr(
"{}\t[{}\ttx]\t[{}\trx]".format(
sess["remoteAddr"], self.speed_of(sess["txRateCurrent"]), self.speed_of(sess["rxRateCurrent"])
)
if (s['txMsgs'] or 0) > 1:
self.win.addstr(" [out window:\t{}]".format(s['txMsgQueueSize']))
if (s['rxMsgs'] or 0) > 1:
self.win.addstr(" [in window:\t{}]".format(s['rxMsgQueueSize']))
return y
)
if (sess['txMsgQueueSize'] or 0) > 1:
self.win.addstr(" [out window: {}]".format(sess['txMsgQueueSize']))
if (sess['rxMsgQueueSize'] or 0) > 1:
self.win.addstr(" [in window: {}]".format(sess['rxMsgQueueSize']))
def display(acks, label, num='acks', dem='packets'):
if acks[dem] > 0:
self.win.addstr(" [{}: {}]".format(label, round(float(acks[num]) / float(acks[dem]), 2)))
if ('recvMACKs' in sess) and ('sendMACKs' in sess):
display(sess['sendMACKs'], 'out MACK density')
display(sess['recvMACKs'], 'in MACK density')
dats = {'recvAcks': 'in acks',
'sendAcks': 'out acks',
'recvRTX': 'in RTX',
'sendRTX': 'out RTX'}
for key in dats:
val = dats[key]
if (key in sess) and (sess[key] > 0):
self.win.addstr(" [{}: {}]".format(val, sess[key]))
return y_pos
def display_dht(self, y, data):
y += 2
self.win.move(y, 1)
def display_dht(self, y_pos, data):
""" display dht window """
y_pos += 2
self.win.move(y_pos, 1)
self.win.addstr("DHT:")
y += 1
self.win.move(y, 1)
y_pos += 1
self.win.move(y_pos, 1)
self.win.addstr("introset lookups")
y = self.display_bucket(y, data["pendingIntrosetLookups"])
y += 1
self.win.move(y, 1)
y_pos = self.display_bucket(y_pos, data["pendingIntrosetLookups"])
y_pos += 1
self.win.move(y_pos, 1)
self.win.addstr("router lookups")
return self.display_bucket(y, data["pendingRouterLookups"])
return self.display_bucket(y_pos, data["pendingRouterLookups"])
def display_bucket(self, y, data):
def display_bucket(self, y_pos, data):
""" display dht bucket """
txs = data["tx"]
self.win.addstr(" ({} lookups)".format(len(txs)))
for tx in txs:
y += 1
self.win.move(y, 1)
self.win.addstr("search for {}".format(tx["tx"]["target"]))
return y
for transaction in txs:
y_pos += 1
self.win.move(y_pos, 1)
self.win.addstr("search for {}".format(transaction["tx"]["target"]))
return y_pos
def display_data(self):
"""draw main window"""
if self.data is not None:
self.win.addstr(1, 1, "lokinet online")
# print(self.data)
self.win.addstr(1, 1, self.rpc("llarp.version"))
services = self.data["services"] or {}
y = 3
y_pos = 3
try:
y = self.display_links(y, self.data["links"])
for k in services:
y = self.display_service(y, k, services[k])
y = self.display_dht(y, self.data["dht"])
except Exception as exc:
pass
y_pos = self.display_links(y_pos, self.data["links"])
for key in services:
y_pos = self.display_service(y_pos, key, services[key])
y_pos = self.display_dht(y_pos, self.data["dht"])
except Exception as e:
print(e)
else:
self.win.move(1, 1)
self.win.addstr("lokinet offline")
def run(self):
while True:
self.win.clear()
self.win.box()
self.update_data()
self.display_data()
""" run mainloop """
while self._run:
if self.update_data():
self.win.box()
self.display_data()
elif self._run:
self.win.addstr(1, 1, "offline")
else:
self._close()
return
self.win.refresh()
time.sleep(1)
if __name__ == "__main__":
import sys
try:
time.sleep(1)
except:
self._close()
return
self.win.clear()
def main():
""" main function """
mon = Monitor(
"http://{}/jsonrpc".format(
len(sys.argv) > 1 and sys.argv[1] or "127.0.0.1:1190"
)
len(sys.argv) > 1 and sys.argv[1] or "tcp://127.0.0.1:1190"
)
mon.run()
if __name__ == "__main__":
main()

@ -0,0 +1 @@
*.private

@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""
keygen tool for lokinet
"""
from argparse import ArgumentParser as AP
from base64 import b32encode
from nacl.signing import SigningKey
def base32z(data):
""" base32 z encode """
return b32encode(data).translate(
bytes.maketrans(
b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
b'ybndrfg8ejkmcpqxot1uwisza345h769')).decode().rstrip('=')
def main():
"""
main function for keygen
"""
argparser = AP()
argparser.add_argument('--keyfile', type=str, required=True, help='place to put generated keys')
args = argparser.parse_args()
secret = SigningKey.generate()
with open(args.keyfile, 'wb') as wfile:
wfile.write(b'd1:s64:')
wfile.write(secret.encode())
wfile.write(secret.verify_key.encode())
wfile.write(b'e')
print("{}.loki".format(base32z(secret.verify_key.encode())))
if __name__ == '__main__':
main()

@ -0,0 +1,14 @@
# lokinet key generator
requires:
* python3.7 or higher
* pynacl
usage:
```bash
./keygen.py --keyfile somekeyfile.private
```
this will overwrite the keyfile with new keys

@ -0,0 +1,7 @@
To be put at `/usr/lib/systemd/resolved.conf.d/lokinet.conf` for distro use and `/etc/systemd/resolved.conf.d/lokinet.conf` for local admin use.
To make use of it:
```
sudo ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
sudo systemctl enable --now systemd-resolved
```

@ -0,0 +1,3 @@
[Resolve]
DNS=127.3.2.1
Domains=~loki ~snode

@ -0,0 +1,8 @@
#!/usr/bin/env bash
#
# create signed release tarball with submodules bundled
#
repo=$(readlink -e $(dirname $0)/..)
branch=$(test -e $repo/.git/ && git rev-parse --abbrev-ref HEAD)
out="lokinet-$(git describe --exact-match --tags $(git log -n1 --pretty='%h') 2> /dev/null || ( echo -n $branch- && git rev-parse --short HEAD)).tar.xz"
git-archive-all -C $repo --force-submodules $out && rm -f $out.sig && (gpg --sign --detach $out &> /dev/null && gpg --verify $out.sig)

@ -1,23 +1,6 @@
set(NTRU_AVX_SRC
libntrup/src/avx/randomsmall.c
libntrup/src/avx/weight.c
libntrup/src/avx/swap.c
libntrup/src/avx/rq_round3.c
libntrup/src/avx/rq_recip3.c
libntrup/src/avx/small.c
libntrup/src/avx/randomweightw.c
libntrup/src/avx/dec.c
libntrup/src/avx/r3_recip.c
libntrup/src/avx/keypair.c
libntrup/src/avx/rq_rounded.c
libntrup/src/avx/mult.c
libntrup/src/avx/enc.c
libntrup/src/avx/int32_sort.c
libntrup/src/avx/rq.c
libntrup/src/avx/rq_mod3.c
)
set(NTRU_REF_SRC
add_library(lokinet-cryptography
libntrup/src/ntru.cpp
libntrup/src/ref/randomsmall.c
libntrup/src/ref/swap.c
libntrup/src/ref/rq_round3.c
@ -36,55 +19,52 @@ set(NTRU_REF_SRC
libntrup/src/ref/rq.c
)
set(NTRU_SRC
${NTRU_REF_SRC}
libntrup/src/ntru.cpp
)
set(CRYPTOGRAPHY_SRC ${NTRU_SRC})
add_library(${CRYPTOGRAPHY_LIB} STATIC ${CRYPTOGRAPHY_SRC})
add_log_tag(${CRYPTOGRAPHY_LIB})
target_include_directories(lokinet-cryptography PUBLIC libntrup/include)
# The avx implementation uses runtime CPU feature detection to enable itself, so we *always* want to
# compile it with avx2 support even if we aren't compiling with AVX2 enabled.
add_library(cryptography_avx_lib STATIC ${NTRU_AVX_SRC})
if(USE_AVX2)
# Assume cxxflags are already enabling AVX2
# compile it with avx2/fma support when supported by the compiler even if we aren't compiling with
# general AVX2 enabled.
set(NTRU_AVX_SRC
libntrup/src/avx/randomsmall.c
libntrup/src/avx/weight.c
libntrup/src/avx/swap.c
libntrup/src/avx/rq_round3.c
libntrup/src/avx/rq_recip3.c
libntrup/src/avx/small.c
libntrup/src/avx/randomweightw.c
libntrup/src/avx/dec.c
libntrup/src/avx/r3_recip.c
libntrup/src/avx/keypair.c
libntrup/src/avx/rq_rounded.c
libntrup/src/avx/mult.c
libntrup/src/avx/enc.c
libntrup/src/avx/int32_sort.c
libntrup/src/avx/rq.c
libntrup/src/avx/rq_mod3.c
)
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-mavx2 COMPILER_SUPPORTS_AVX2)
check_cxx_compiler_flag(-mfma COMPILER_SUPPORTS_FMA)
if(COMPILER_SUPPORTS_AVX2 AND COMPILER_SUPPORTS_FMA AND (NOT ANDROID))
target_sources(lokinet-cryptography PRIVATE ${NTRU_AVX_SRC})
set_property(SOURCE ${NTRU_AVX_SRC} APPEND PROPERTY COMPILE_FLAGS "-mavx2 -mfma")
message(STATUS "Building libntrup with runtime AVX2/FMA support")
else()
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-mavx2 COMPILER_SUPPORTS_AVX2)
check_cxx_compiler_flag(-mfma COMPILER_SUPPORTS_FMA)
if(COMPILER_SUPPORTS_AVX2 AND COMPILER_SUPPORTS_FMA)
target_compile_options(cryptography_avx_lib PRIVATE -mavx2 -mfma)
message(STATUS "Building libntrup with runtime AVX2/FMA support")
else()
message(STATUS "Not building with libntrup runtime AVX2/FMA support (can't figure out how to compile with AVX2/FMA: -mavx2 -mfma didn't work)")
endif()
target_sources(lokinet-cryptography PRIVATE libntrup/src/noavx-stubs.c)
message(STATUS "Not building with libntrup runtime AVX2/FMA support (either this architecture doesn't support them, or your compile doesn't support the -mavx2 -mfma flags")
endif()
target_link_libraries(${CRYPTOGRAPHY_LIB} PRIVATE cryptography_avx_lib)
option(DOWNLOAD_SODIUM "Allow libsodium to be downloaded and built locally if not found on the system" OFF)
enable_lto(lokinet-cryptography)
add_log_tag(lokinet-cryptography)
# Allow -DDOWNLOAD_SODIUM=FORCE to download without even checking for a local libsodium
if(NOT DOWNLOAD_SODIUM STREQUAL "FORCE")
find_package(Sodium 1.0.18)
if(BUILD_SHARED_LIBS)
install(TARGETS lokinet-cryptography LIBRARY DESTINATION lib)
endif()
if(sodium_FOUND)
target_include_directories(${CRYPTOGRAPHY_LIB} PUBLIC ${sodium_INCLUDE_DIR})
target_include_directories(cryptography_avx_lib PUBLIC ${sodium_INCLUDE_DIR})
target_link_libraries(${CRYPTOGRAPHY_LIB} PUBLIC ${sodium_LIBRARY_RELEASE})
elseif(DOWNLOAD_SODIUM)
message(STATUS "Sodium >= 1.0.18 not found, but DOWNLOAD_SODIUM specified, so downloading it")
include(DownloadLibSodium)
target_link_libraries(${CRYPTOGRAPHY_LIB} PUBLIC sodium_vendor)
target_link_libraries(cryptography_avx_lib PUBLIC sodium_vendor)
else()
message(FATAL_ERROR "Could not find libsodium >= 1.0.18; either install it on your system or use -DDOWNLOAD_SODIUM=ON to download and build an internal copy")
if (WARNINGS_AS_ERRORS)
target_compile_options(lokinet-cryptography PUBLIC -Wall -Wextra -Werror)
endif()
target_include_directories(${CRYPTOGRAPHY_LIB} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/libntrup/include")
target_include_directories(cryptography_avx_lib PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/libntrup/include")
target_link_libraries(lokinet-cryptography PUBLIC sodium)

@ -11,11 +11,14 @@
#include "rq.h"
#include "r3.h"
#ifndef __AVX2__
#error "This file requires compilation with AVX2 support"
#endif
int
crypto_kem_dec_avx2(unsigned char *k, const unsigned char *cstr,
const unsigned char *sk)
{
#if __AVX2__
small f[768];
modq h[768];
small grecip[768];
@ -67,10 +70,4 @@ crypto_kem_dec_avx2(unsigned char *k, const unsigned char *cstr,
for(i = 0; i < 32; ++i)
k[i] = (hash[32 + i] & ~result);
return result;
#else
(void)(k);
(void)(sk);
(void)(cstr);
return -1;
#endif
}

@ -9,11 +9,14 @@
#include <sodium/crypto_hash_sha512.h>
#include <sodium/crypto_kem.h>
#ifndef __AVX2__
#error "This file requires compilation with AVX2 support"
#endif
int
crypto_kem_enc_avx2(unsigned char *cstr, unsigned char *k,
const unsigned char *pk)
{
#if __AVX2__
small r[768];
modq h[768];
modq c[768];
@ -46,10 +49,4 @@ crypto_kem_enc_avx2(unsigned char *cstr, unsigned char *k,
rq_roundencode(cstr + 32, c);
return 0;
#else
(void)(cstr);
(void)(k);
(void)(pk);
return -1;
#endif
}

@ -14,10 +14,13 @@
"crypto_kem_SECRETKEYBYTES must match rq_encode_len + 2 * small_encode_len"
#endif
#ifndef __AVX2__
#error "This file requires compilation with AVX2 support"
#endif
int
crypto_kem_keypair_avx2(unsigned char *pk, unsigned char *sk)
{
#if __AVX2__
small g[768];
small grecip[768];
small f[768];
@ -39,9 +42,4 @@ crypto_kem_keypair_avx2(unsigned char *pk, unsigned char *sk)
memcpy(sk + 2 * small_encode_len, pk, rq_encode_len);
return 0;
#else
(void)(pk);
(void)(sk);
return -1;
#endif
}

@ -0,0 +1,29 @@
// Stubs for compilers/builds without avx2 support
//
int
crypto_kem_enc_avx2(unsigned char *cstr, unsigned char *k,
const unsigned char *pk)
{
(void)(cstr);
(void)(k);
(void)(pk);
return -1;
}
int
crypto_kem_dec_avx2(unsigned char *k, const unsigned char *cstr,
const unsigned char *sk)
{
(void)(k);
(void)(sk);
(void)(cstr);
return -1;
}
int
crypto_kem_keypair_avx2(unsigned char *pk, unsigned char *sk)
{
(void)(pk);
(void)(sk);
return -1;
}

@ -43,14 +43,12 @@ extern "C"
{
__crypto_kem_dec = &crypto_kem_dec_avx2;
__crypto_kem_enc = &crypto_kem_enc_avx2;
__crypto_kem_dec = &crypto_kem_dec_avx2;
__crypto_kem_keypair = &crypto_kem_keypair_avx2;
}
else
{
__crypto_kem_dec = &crypto_kem_dec_ref;
__crypto_kem_enc = &crypto_kem_enc_ref;
__crypto_kem_dec = &crypto_kem_dec_ref;
__crypto_kem_keypair = &crypto_kem_keypair_ref;
}
}

@ -1,53 +1,44 @@
set(EXE lokinet)
set(EXE_SRC main.cpp)
set(CTL lokinetctl)
set(CTL_SRC lokinetctl.cpp)
if(TRACY_ROOT)
list(APPEND EXE_SRC ${TRACY_ROOT}/TracyClient.cpp)
endif()
if(SHADOW)
set(LOKINET_SHADOW shadow-plugin-${SHARED_LIB})
set(LOKINET_SHADOW_LIBS ${SHARED_LIB})
add_shadow_plugin(${LOKINET_SHADOW} ${EXE_SRC})
target_link_libraries(${LOKINET_SHADOW} ${LOKINET_SHADOW_LIBS})
target_include_directories(${LOKINET_SHADOW} PUBLIC ${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/llarp ${PROJECT_SOURCE_DIR}/crypto/include)
add_shadow_plugin(shadow-plugin main.cpp ${TRACY_ROOT}/TracyClient.cpp)
target_link_libraries(shadow-plugin liblokinet)
enable_lto(shadow-plugin)
else()
if(WIN32 AND NOT MSVC_VERSION)
list(APPEND EXE_SRC ../llarp/win32/version.rc)
list(APPEND CTL_SRC ../llarp/win32/version.rc)
endif()
add_executable(${EXE} ${EXE_SRC})
add_executable(${CTL} ${CTL_SRC})
add_executable(lokinet main.cpp)
add_executable(lokinet-vpn lokinet-vpn.cpp)
enable_lto(lokinet lokinet-vpn)
target_compile_definitions(${EXE} PRIVATE -DVERSIONTAG=${GIT_VERSION_REAL})
target_compile_definitions(${CTL} PRIVATE -DVERSIONTAG=${GIT_VERSION_REAL})
if(TRACY_ROOT)
target_sources(lokinet PRIVATE ${TRACY_ROOT}/TracyClient.cpp)
endif()
add_log_tag(${EXE})
add_log_tag(${CTL})
foreach(exe lokinet lokinet-vpn)
if(WIN32 AND NOT MSVC_VERSION)
target_sources(${exe} PRIVATE ../llarp/win32/version.rc)
target_link_libraries(${exe} PRIVATE ws2_32 iphlpapi)
elseif(CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
target_link_directories(${exe} PRIVATE /usr/local/lib)
endif()
target_link_libraries(${exe} PRIVATE liblokinet)
if(WITH_JEMALLOC)
target_link_libraries(${exe} PUBLIC jemalloc)
endif()
target_compile_definitions(${exe} PRIVATE -DVERSIONTAG=${GIT_VERSION_REAL})
add_log_tag(${exe})
install(TARGETS ${exe} RUNTIME DESTINATION bin COMPONENT lokinet)
endforeach()
install(TARGETS ${EXE} RUNTIME DESTINATION bin COMPONENT lokinet)
if(WIN32)
install(PROGRAMS ${CMAKE_SOURCE_DIR}/lokinet-bootstrap.ps1 DESTINATION bin COMPONENT lokinet)
else()
install(PROGRAMS ${CMAKE_SOURCE_DIR}/lokinet-bootstrap DESTINATION bin COMPONENT lokinet)
endif()
if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
install(CODE "execute_process(COMMAND setcap cap_net_admin,cap_net_bind_service=+eip ${CMAKE_INSTALL_PREFIX}/bin/lokinet)")
elseif(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
target_link_directories(${EXE} PRIVATE /usr/local/lib)
target_link_directories(${CTL} PRIVATE /usr/local/lib)
if(CMAKE_SYSTEM_NAME MATCHES "Linux")
option(WITH_SETCAP "Enables setcap'ing the lokinet binary with the required capabilities during installation (requires root)" ON)
if(WITH_SETCAP)
install(CODE "execute_process(COMMAND setcap cap_net_admin,cap_net_bind_service=+eip ${CMAKE_INSTALL_PREFIX}/bin/lokinet)")
endif()
endif()
target_link_libraries(${EXE} PUBLIC ${EXE_LIBS} ${LIBS} ${CRYPTOGRAPHY_LIB})
target_link_libraries(${CTL} PUBLIC ${EXE_LIBS} ${LIBS} ${CRYPTOGRAPHY_LIB})
if(CURL_FOUND)
target_include_directories(${CTL} PRIVATE ${CURL_INCLUDE_DIRS})
target_link_libraries(${CTL} PRIVATE ${CURL_LIBRARIES})
target_compile_definitions(${CTL} PRIVATE -DWITH_CURL=1)
endif(CURL_FOUND)
endif(SHADOW)
endif()

@ -0,0 +1,229 @@
#include <lokimq/lokimq.h>
#include <nlohmann/json.hpp>
#include <cxxopts.hpp>
#include <future>
#include <vector>
#include <array>
#include <net/net.hpp>
#ifdef _WIN32
// add the unholy windows headers for iphlpapi
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <strsafe.h>
#else
#include <sys/wait.h>
#endif
/// do a lokimq request on an lmq instance blocking style
/// returns a json object parsed from the result
std::optional<nlohmann::json>
LMQ_Request(
lokimq::LokiMQ& lmq,
const lokimq::ConnectionID& id,
std::string_view method,
std::optional<nlohmann::json> args = std::nullopt)
{
std::promise<std::optional<std::string>> result_promise;
auto handleRequest = [&result_promise](bool success, std::vector<std::string> result) {
if ((not success) or result.empty())
{
result_promise.set_value(std::nullopt);
return;
}
result_promise.set_value(result[0]);
};
if (args.has_value())
{
lmq.request(id, method, handleRequest, args->dump());
}
else
{
lmq.request(id, method, handleRequest);
}
auto ftr = result_promise.get_future();
const auto str = ftr.get();
if (str.has_value())
return nlohmann::json::parse(*str);
return std::nullopt;
}
int
main(int argc, char* argv[])
{
cxxopts::Options opts("lokinet-vpn", "LokiNET vpn control utility");
opts.add_options()("v,verbose", "Verbose", cxxopts::value<bool>())(
"h,help", "help", cxxopts::value<bool>())("up", "put vpn up", cxxopts::value<bool>())(
"down", "put vpn down", cxxopts::value<bool>())(
"exit", "specify exit node address", cxxopts::value<std::string>())(
"rpc", "rpc url for lokinet", cxxopts::value<std::string>())(
"endpoint", "endpoint to use", cxxopts::value<std::string>())(
"token", "exit auth token to use", cxxopts::value<std::string>());
lokimq::address rpcURL("tcp://127.0.0.1:1190");
std::string exitAddress;
std::string endpoint = "default";
std::optional<std::string> token;
lokimq::LogLevel logLevel = lokimq::LogLevel::warn;
bool goUp = false;
bool goDown = false;
try
{
const auto result = opts.parse(argc, argv);
if (result.count("help") > 0)
{
std::cout << opts.help() << std::endl;
return 0;
}
if (result.count("verbose") > 0)
{
logLevel = lokimq::LogLevel::debug;
}
if (result.count("rpc") > 0)
{
rpcURL = lokimq::address(result["rpc"].as<std::string>());
}
if (result.count("exit") > 0)
{
exitAddress = result["exit"].as<std::string>();
}
goUp = result.count("up") > 0;
goDown = result.count("down") > 0;
if (result.count("endpoint") > 0)
{
endpoint = result["endpoint"].as<std::string>();
}
if (result.count("token") > 0)
{
token = result["token"].as<std::string>();
}
}
catch (const cxxopts::option_not_exists_exception& ex)
{
std::cerr << ex.what();
std::cout << opts.help() << std::endl;
return 1;
}
catch (std::exception& ex)
{
std::cout << ex.what() << std::endl;
return 1;
}
if ((not goUp) and (not goDown))
{
std::cout << opts.help() << std::endl;
return 1;
}
if (goUp and exitAddress.empty())
{
std::cout << "no exit address provided" << std::endl;
return 1;
}
lokimq::LokiMQ lmq{[](lokimq::LogLevel lvl, const char* file, int line, std::string msg) {
std::cout << lvl << " [" << file << ":" << line << "] " << msg << std::endl;
},
logLevel};
lmq.start();
std::promise<bool> connectPromise;
const auto connID = lmq.connect_remote(
rpcURL,
[&connectPromise](auto) { connectPromise.set_value(true); },
[&connectPromise](auto, std::string_view msg) {
std::cout << "failed to connect to lokinet RPC: " << msg << std::endl;
connectPromise.set_value(false);
});
auto ftr = connectPromise.get_future();
if (not ftr.get())
{
return 1;
}
std::vector<std::string> firstHops;
std::string ifname;
const auto maybe_status = LMQ_Request(lmq, connID, "llarp.status");
if (not maybe_status.has_value())
{
std::cout << "call to llarp.status failed" << std::endl;
return 1;
}
try
{
// extract first hops
const auto& links = maybe_status->at("result")["links"]["outbound"];
for (const auto& link : links)
{
const auto& sessions = link["sessions"]["established"];
for (const auto& session : sessions)
{
std::string addr = session["remoteAddr"];
const auto pos = addr.find(":");
firstHops.push_back(addr.substr(0, pos));
}
}
// get interface name
#ifdef _WIN32
// strip off the "::ffff."
ifname = maybe_status->at("result")["services"][endpoint]["ifaddr"];
const auto pos = ifname.find("/");
if (pos != std::string::npos)
{
ifname = ifname.substr(0, pos);
}
#else
ifname = maybe_status->at("result")["services"][endpoint]["ifname"];
#endif
}
catch (std::exception& ex)
{
std::cout << "failed to parse result: " << ex.what() << std::endl;
return 1;
}
if (goUp)
{
std::optional<nlohmann::json> maybe_result;
if (token.has_value())
{
maybe_result = LMQ_Request(
lmq,
connID,
"llarp.exit",
nlohmann::json{{"exit", exitAddress}, {"range", "0.0.0.0/0"}, {"token", *token}});
}
else
{
maybe_result = LMQ_Request(
lmq, connID, "llarp.exit", nlohmann::json{{"exit", exitAddress}, {"range", "0.0.0.0/0"}});
}
if (not maybe_result.has_value())
{
std::cout << "could not add exit" << std::endl;
return 1;
}
if (maybe_result->contains("error") and maybe_result->at("error").is_string())
{
std::cout << maybe_result->at("error").get<std::string>() << std::endl;
return 1;
}
}
if (goDown)
{
LMQ_Request(lmq, connID, "llarp.exit", nlohmann::json{{"range", "0.0.0.0/0"}, {"unmap", true}});
}
return 0;
}

@ -7,22 +7,18 @@
#include <string>
#include <vector>
#ifdef WITH_CURL
#include <curl/curl.h>
#endif
namespace
{
bool
dumpRc(const std::vector< std::string >& files)
dumpRc(const std::vector<std::string>& files)
{
nlohmann::json result;
for(const auto& file : files)
for (const auto& file : files)
{
llarp::RouterContact rc;
const bool ret = rc.Read(file.c_str());
if(ret)
if (ret)
{
result[file] = rc.ToJson();
}
@ -35,140 +31,57 @@ namespace
return true;
}
#ifdef WITH_CURL
size_t
curlCallback(void* contents, size_t size, size_t nmemb, void* userp) noexcept
{
auto* str = static_cast< std::string* >(userp);
size_t realsize = size * nmemb;
char* asChar = static_cast< char* >(contents);
std::copy(asChar, asChar + realsize, std::back_inserter(*str));
return realsize;
}
bool
executeJsonRpc(const std::string& command, const std::string& configFile)
{
// Do init (on windows this will do socket initialisation)
curl_global_init(CURL_GLOBAL_ALL);
llarp::Config config;
if(!config.Load(configFile.c_str()))
{
llarp::LogError("Failed to load from config file: ", configFile);
return false;
}
if(!config.api.enableRPCServer())
{
llarp::LogError("Config does not have RPC enabled");
return false;
}
std::string address = config.api.rpcBindAddr() + "/jsonrpc";
const nlohmann::json request{{"method", command},
{"params", nlohmann::json::object()},
{"id", "foo"}};
const std::string requestStr = request.dump();
std::unique_ptr< curl_slist, void (*)(curl_slist*) > chunk(
curl_slist_append(nullptr, "content-type: application/json"),
&curl_slist_free_all);
std::unique_ptr< CURL, void (*)(CURL*) > curl(curl_easy_init(),
&curl_easy_cleanup);
curl_easy_setopt(curl.get(), CURLOPT_URL, address.c_str());
curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, requestStr.c_str());
curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDSIZE, requestStr.size());
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, chunk.get());
std::string result;
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, curlCallback);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &result);
auto res = curl_easy_perform(curl.get());
if(res != CURLE_OK)
{
llarp::LogError("Failed to curl endpoint, ", curl_easy_strerror(res));
return false;
}
std::cout << result << "\n";
return true;
}
#endif
} // namespace
int
main(int argc, char* argv[])
{
cxxopts::Options options("lokinetctl",
"LokiNET is a free, open source, private, "
"decentralized, \"market based sybil resistant\" "
"and IP based onion routing network");
options.add_options()("v,verbose", "Verbose", cxxopts::value< bool >())(
"h,help", "help", cxxopts::value< bool >())(
"c,config", "config file",
cxxopts::value< std::string >()->default_value(
llarp::GetDefaultConfigPath().string()))
#ifdef WITH_CURL
("j,jsonrpc", "hit json rpc endpoint", cxxopts::value< std::string >())
#endif
("dump", "dump rc file",
cxxopts::value< std::vector< std::string > >(), "FILE");
cxxopts::Options options(
"lokinetctl",
"LokiNET is a free, open source, private, "
"decentralized, \"market based sybil resistant\" "
"and IP based onion routing network");
options.add_options()("v,verbose", "Verbose", cxxopts::value<bool>())(
"h,help", "help", cxxopts::value<bool>())(
"c,config",
"config file",
cxxopts::value<std::string>()->default_value(llarp::GetDefaultConfigPath().string()))(
"dump", "dump rc file", cxxopts::value<std::vector<std::string>>(), "FILE");
try
{
const auto result = options.parse(argc, argv);
if(result.count("verbose") > 0)
if (result.count("verbose") > 0)
{
SetLogLevel(llarp::eLogDebug);
llarp::LogContext::Instance().logStream =
std::make_unique< llarp::OStreamLogStream >(true, std::cerr);
std::make_unique<llarp::OStreamLogStream>(true, std::cerr);
llarp::LogDebug("debug logging activated");
}
else
{
SetLogLevel(llarp::eLogError);
llarp::LogContext::Instance().logStream =
std::make_unique< llarp::OStreamLogStream >(true, std::cerr);
std::make_unique<llarp::OStreamLogStream>(true, std::cerr);
}
if(result.count("help") > 0)
if (result.count("help") > 0)
{
std::cout << options.help() << std::endl;
return 0;
}
if(result.count("dump") > 0)
{
if(!dumpRc(result["dump"].as< std::vector< std::string > >()))
{
return 1;
}
}
#ifdef WITH_CURL
if(result.count("jsonrpc") > 0)
if (result.count("dump") > 0)
{
if(!executeJsonRpc(result["jsonrpc"].as< std::string >(),
result["config"].as< std::string >()))
if (!dumpRc(result["dump"].as<std::vector<std::string>>()))
{
return 1;
}
}
#endif
}
catch(const cxxopts::OptionParseException& ex)
catch (const cxxopts::OptionParseException& ex)
{
std::cerr << ex.what() << std::endl;
std::cout << options.help() << std::endl;

@ -5,6 +5,8 @@
#include <util/fs.hpp>
#include <util/logging/logger.hpp>
#include <util/logging/ostream_logger.hpp>
#include <util/str.hpp>
#include <util/thread/logic.hpp>
#include <csignal>
@ -13,23 +15,59 @@
#include <iostream>
#include <future>
#ifdef USE_JEMALLOC
#include <new>
#include <jemalloc/jemalloc.h>
void*
operator new(std::size_t sz)
{
void* ptr = malloc(sz);
if (ptr)
return ptr;
else
throw std::bad_alloc{};
}
void
operator delete(void* ptr) noexcept
{
free(ptr);
}
void
operator delete(void* ptr, size_t) noexcept
{
free(ptr);
}
#endif
int
lokinet_main(int, char**);
#ifdef _WIN32
#define wmin(x, y) (((x) < (y)) ? (x) : (y))
#define MIN wmin
#include <strsafe.h>
extern "C" LONG FAR PASCAL
win32_signal_handler(EXCEPTION_POINTERS *);
win32_signal_handler(EXCEPTION_POINTERS*);
extern "C" VOID FAR PASCAL
win32_daemon_entry(DWORD, LPTSTR*);
VOID ReportSvcStatus(DWORD, DWORD, DWORD);
VOID
insert_description();
SERVICE_STATUS SvcStatus;
SERVICE_STATUS_HANDLE SvcStatusHandle;
bool start_as_daemon = false;
#endif
struct llarp_main *ctx = 0;
std::promise< int > exit_code;
std::shared_ptr<llarp::Context> ctx;
std::promise<int> exit_code;
void
handle_signal(int sig)
{
if(ctx)
{
llarp_main_signal(ctx, sig);
}
if (ctx)
LogicCall(ctx->logic, std::bind(&llarp::Context::HandleSignal, ctx.get(), sig));
else
std::cerr << "Received signal " << sig << ", but have no context yet. Ignoring!" << std::endl;
}
#ifdef _WIN32
@ -39,7 +77,7 @@ startWinsock()
WSADATA wsockd;
int err;
err = ::WSAStartup(MAKEWORD(2, 2), &wsockd);
if(err)
if (err)
{
perror("Failed to start Windows Sockets");
return err;
@ -55,261 +93,510 @@ handle_signal_win32(DWORD fdwCtrlType)
handle_signal(SIGINT);
return TRUE; // probably unreachable
}
void
install_win32_daemon()
{
SC_HANDLE schSCManager;
SC_HANDLE schService;
std::array<char, 1024> szPath{};
if (!GetModuleFileName(nullptr, szPath.data(), MAX_PATH))
{
llarp::LogError("Cannot install service ", GetLastError());
return;
}
// just put the flag here. we eat it later on and specify the
// config path in the daemon entry point
StringCchCat(szPath.data(), 1024, " --win32-daemon");
// Get a handle to the SCM database.
schSCManager = OpenSCManager(
nullptr, // local computer
nullptr, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (nullptr == schSCManager)
{
llarp::LogError("OpenSCManager failed ", GetLastError());
return;
}
// Create the service
schService = CreateService(
schSCManager, // SCM database
"lokinet", // name of service
"Lokinet for Windows", // service name to display
SERVICE_ALL_ACCESS, // desired access
SERVICE_WIN32_OWN_PROCESS, // service type
SERVICE_DEMAND_START, // start type
SERVICE_ERROR_NORMAL, // error control type
szPath.data(), // path to service's binary
nullptr, // no load ordering group
nullptr, // no tag identifier
nullptr, // no dependencies
nullptr, // LocalSystem account
nullptr); // no password
if (schService == nullptr)
{
llarp::LogError("CreateService failed ", GetLastError());
CloseServiceHandle(schSCManager);
return;
}
else
llarp::LogInfo("Service installed successfully");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
insert_description();
}
VOID
insert_description()
{
SC_HANDLE schSCManager;
SC_HANDLE schService;
SERVICE_DESCRIPTION sd;
LPTSTR szDesc =
"LokiNET is a free, open source, private, "
"decentralized, \"market based sybil resistant\" "
"and IP based onion routing network";
// Get a handle to the SCM database.
schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (nullptr == schSCManager)
{
llarp::LogError("OpenSCManager failed ", GetLastError());
return;
}
// Get a handle to the service.
schService = OpenService(
schSCManager, // SCM database
"lokinet", // name of service
SERVICE_CHANGE_CONFIG); // need change config access
if (schService == nullptr)
{
llarp::LogError("OpenService failed ", GetLastError());
CloseServiceHandle(schSCManager);
return;
}
// Change the service description.
sd.lpDescription = szDesc;
if (!ChangeServiceConfig2(
schService, // handle to service
SERVICE_CONFIG_DESCRIPTION, // change: description
&sd)) // new description
{
llarp::LogError("ChangeServiceConfig2 failed");
}
else
llarp::LogInfo("Service description updated successfully.");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
}
void
uninstall_win32_daemon()
{
SC_HANDLE schSCManager;
SC_HANDLE schService;
// Get a handle to the SCM database.
schSCManager = OpenSCManager(
nullptr, // local computer
nullptr, // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if (nullptr == schSCManager)
{
llarp::LogError("OpenSCManager failed ", GetLastError());
return;
}
// Get a handle to the service.
schService = OpenService(
schSCManager, // SCM database
"lokinet", // name of service
0x10000); // need delete access
if (schService == nullptr)
{
llarp::LogError("OpenService failed ", GetLastError());
CloseServiceHandle(schSCManager);
return;
}
// Delete the service.
if (!DeleteService(schService))
{
llarp::LogError("DeleteService failed ", GetLastError());
}
else
llarp::LogInfo("Service deleted successfully\n");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
}
#endif
/// this sets up, configures and runs the main context
static void
run_main_context(std::string conffname, llarp_main_runtime_opts opts)
run_main_context(const fs::path confFile, const llarp::RuntimeOptions opts)
{
// this is important, can downgrade from Info though
llarp::LogDebug("Running from: ", fs::current_path().string());
llarp::LogInfo("Using config file: ", conffname);
ctx = llarp_main_init(conffname.c_str());
int code = 1;
if(ctx)
try
{
// this is important, can downgrade from Info though
llarp::LogDebug("Running from: ", fs::current_path().string());
llarp::LogInfo("Using config file: ", confFile);
llarp::Config conf;
conf.Load(confFile, opts.isRouter, confFile.parent_path());
ctx = std::make_shared<llarp::Context>();
ctx->Configure(conf);
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
#ifndef _WIN32
signal(SIGHUP, handle_signal);
#endif
code = llarp_main_setup(ctx);
ctx->Setup(opts);
llarp::util::SetThreadName("llarp-mainloop");
if(code == 0)
code = llarp_main_run(ctx, opts);
auto result = ctx->Run(opts);
exit_code.set_value(result);
}
catch (std::exception& e)
{
llarp::LogError("Fatal: caught exception while running: ", e.what());
exit_code.set_exception(std::current_exception());
}
catch (...)
{
llarp::LogError("Fatal: caught non-standard exception while running");
exit_code.set_exception(std::current_exception());
}
exit_code.set_value(code);
}
int
main(int argc, char *argv[])
main(int argc, char* argv[])
{
auto result = Lokinet_INIT();
if(result)
#ifndef _WIN32
return lokinet_main(argc, argv);
#else
SERVICE_TABLE_ENTRY DispatchTable[] = {{"lokinet", (LPSERVICE_MAIN_FUNCTION)win32_daemon_entry},
{NULL, NULL}};
if (lstrcmpi(argv[1], "--win32-daemon") == 0)
{
return result;
start_as_daemon = true;
StartServiceCtrlDispatcher(DispatchTable);
}
llarp_main_runtime_opts opts;
const char *singleThreadVar = getenv("LLARP_SHADOW");
if(singleThreadVar && std::string(singleThreadVar) == "1")
else
return lokinet_main(argc, argv);
#endif
}
int
lokinet_main(int argc, char* argv[])
{
auto result = Lokinet_INIT();
if (result)
{
opts.singleThreaded = true;
return result;
}
llarp::RuntimeOptions opts;
#ifdef _WIN32
if(startWinsock())
if (startWinsock())
return -1;
ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
SetConsoleCtrlHandler(handle_signal_win32, TRUE);
// SetUnhandledExceptionFilter(win32_signal_handler);
#endif
cxxopts::Options options("lokinet",
"LokiNET is a free, open source, private, "
"decentralized, \"market based sybil resistant\" "
"and IP based onion routing network");
options.add_options()("v,verbose", "Verbose", cxxopts::value< bool >())(
"h,help", "help", cxxopts::value< bool >())("version", "version",
cxxopts::value< bool >())(
"g,generate", "generate client config", cxxopts::value< bool >())(
"r,router", "generate router config", cxxopts::value< bool >())(
"f,force", "overwrite", cxxopts::value< bool >())(
"c,colour", "colour output",
cxxopts::value< bool >()->default_value("true"))(
"b,background",
"background mode (start, but do not connect to the network)",
cxxopts::value< bool >())("config", "path to configuration file",
cxxopts::value< std::string >());
cxxopts::Options options(
"lokinet",
"LokiNET is a free, open source, private, "
"decentralized, \"market based sybil resistant\" "
"and IP based onion routing network");
options.add_options()("v,verbose", "Verbose", cxxopts::value<bool>())
#ifdef _WIN32
("install", "install win32 daemon to SCM", cxxopts::value<bool>())(
"remove", "remove win32 daemon from SCM", cxxopts::value<bool>())
#endif
("h,help", "help", cxxopts::value<bool>())("version", "version", cxxopts::value<bool>())(
"g,generate", "generate client config", cxxopts::value<bool>())(
"r,router", "run as router instead of client", cxxopts::value<bool>())(
"f,force", "overwrite", cxxopts::value<bool>())(
"c,colour", "colour output", cxxopts::value<bool>()->default_value("true"))(
"b,background",
"background mode (start, but do not connect to the network)",
cxxopts::value<bool>())(
"config", "path to configuration file", cxxopts::value<std::string>());
options.parse_positional("config");
bool genconfigOnly = false;
bool asRouter = false;
bool overWrite = false;
std::string conffname;
bool overwrite = false;
fs::path configFile;
try
{
auto result = options.parse(argc, argv);
if(result.count("verbose") > 0)
if (result.count("verbose") > 0)
{
SetLogLevel(llarp::eLogDebug);
llarp::LogDebug("debug logging activated");
}
if(!result["colour"].as< bool >())
if (!result["colour"].as<bool>())
{
llarp::LogContext::Instance().logStream =
std::make_unique< llarp::OStreamLogStream >(false, std::cerr);
std::make_unique<llarp::OStreamLogStream>(false, std::cerr);
}
if(result.count("help"))
if (result.count("help"))
{
std::cout << options.help() << std::endl;
return 0;
}
if(result.count("version"))
if (result.count("version"))
{
std::cout << llarp::VERSION_FULL << std::endl;
return 0;
}
#ifdef _WIN32
if (result.count("install"))
{
std::cout << llarp_version() << std::endl;
install_win32_daemon();
return 0;
}
if(result.count("generate") > 0)
if (result.count("remove"))
{
uninstall_win32_daemon();
return 0;
}
#endif
if (result.count("generate") > 0)
{
genconfigOnly = true;
}
if(result.count("background") > 0)
if (result.count("background") > 0)
{
opts.background = true;
}
if(result.count("force") > 0)
if (result.count("router") > 0)
{
overWrite = true;
opts.isRouter = true;
}
if(result.count("router") > 0)
if (result.count("force") > 0)
{
asRouter = true;
// we should generate and exit (docker needs this, so we don't write a
// config each time on startup)
genconfigOnly = true;
overwrite = true;
}
if(result.count("config") > 0)
if (result.count("config") > 0)
{
auto arg = result["config"].as< std::string >();
if(!arg.empty())
auto arg = result["config"].as<std::string>();
if (!arg.empty())
{
conffname = arg;
configFile = arg;
}
}
}
catch(const cxxopts::option_not_exists_exception &ex)
catch (const cxxopts::option_not_exists_exception& ex)
{
std::cerr << ex.what();
std::cout << options.help() << std::endl;
return 1;
}
if(!conffname.empty())
if (!configFile.empty())
{
// when we have an explicit filepath
fs::path fname = fs::path(conffname);
fs::path basedir = fname.parent_path();
fs::path basedir = configFile.parent_path();
if(!basedir.empty())
if (genconfigOnly)
{
std::error_code ec;
if(!fs::create_directories(basedir, ec))
{
if(ec)
{
llarp::LogError("failed to create '", basedir.string(),
"': ", ec.message());
return 1;
}
}
}
if(genconfigOnly)
{
if(!llarp_ensure_config(conffname.c_str(), basedir.string().c_str(),
overWrite, asRouter))
return 1;
llarp::ensureConfig(basedir, configFile, overwrite, opts.isRouter);
}
else
{
std::error_code ec;
if(!fs::exists(fname, ec))
if (!fs::exists(configFile, ec))
{
llarp::LogError("Config file not found ", conffname);
llarp::LogError("Config file not found ", configFile);
return 1;
}
if (ec)
throw std::runtime_error(llarp::stringify("filesystem error: ", ec));
}
}
else
{
auto basepath = llarp::GetDefaultConfigDir();
llarp::LogDebug("Find or create ", basepath.string());
std::error_code ec;
// These paths are guaranteed to exist - $APPDATA or $HOME
// so only create .lokinet/*
if(!fs::create_directory(basepath, ec))
{
if(ec)
{
llarp::LogError("failed to create '", basepath.string(),
"': ", ec.message());
return 1;
}
}
auto fpath = llarp::GetDefaultConfigPath();
// if using default INI file, we're create it even if you don't ask us too
if(!llarp_ensure_config(fpath.string().c_str(), basepath.string().c_str(),
overWrite, asRouter))
return 1;
conffname = fpath.string();
llarp::ensureConfig(
llarp::GetDefaultDataDir(), llarp::GetDefaultConfigPath(), overwrite, opts.isRouter);
configFile = llarp::GetDefaultConfigPath();
}
if(genconfigOnly)
if (genconfigOnly)
{
return 0;
}
std::thread main_thread{std::bind(&run_main_context, conffname, opts)};
std::thread main_thread{std::bind(&run_main_context, configFile, opts)};
auto ftr = exit_code.get_future();
do
{
// do periodic non lokinet related tasks here
if(ctx != nullptr)
if (ctx and ctx->IsUp() and not ctx->LooksAlive())
{
auto ctx_pp = llarp::Context::Get(ctx);
if(ctx_pp != nullptr)
for (const auto& wtf : {"you have been visited by the mascott of the "
"deadlocked router.",
"⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣀⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠄⠄⠄⠄",
"⠄⠄⠄⠄⠄⢀⣀⣀⡀⠄⠄⠄⡠⢲⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠄⠄",
"⠄⠄⠄⠔⣈⣀⠄⢔⡒⠳⡴⠊⠄⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⣿⣿⣧⠄⠄",
"⠄⢜⡴⢑⠖⠊⢐⣤⠞⣩⡇⠄⠄⠄⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣆⠄⠝⠛⠋⠐",
"⢸⠏⣷⠈⠄⣱⠃⠄⢠⠃⠐⡀⠄⠄⠄⠄⠙⠻⢿⣿⣿⣿⣿⣿⣿⣿⡿⠛⠸⠄⠄⠄⠄",
"⠈⣅⠞⢁⣿⢸⠘⡄⡆⠄⠄⠈⠢⡀⠄⠄⠄⠄⠄⠄⠉⠙⠛⠛⠛⠉⠉⡀⠄⠡⢀⠄⣀",
"⠄⠙⡎⣹⢸⠄⠆⢘⠁⠄⠄⠄⢸⠈⠢⢄⡀⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠃⠄⠄⠄⠄⠄",
"⠄⠄⠑⢿⠈⢆⠘⢼⠄⠄⠄⠄⠸⢐⢾⠄⡘⡏⠲⠆⠠⣤⢤⢤⡤⠄⣖⡇⠄⠄⠄⠄⠄",
"⣴⣶⣿⣿⣣⣈⣢⣸⠄⠄⠄⠄⡾⣷⣾⣮⣤⡏⠁⠘⠊⢠⣷⣾⡛⡟⠈⠄⠄⠄⠄⠄⠄",
"⣿⣿⣿⣿⣿⠉⠒⢽⠄⠄⠄⠄⡇⣿⣟⣿⡇⠄⠄⠄⠄⢸⣻⡿⡇⡇⠄⠄⠄⠄⠄⠄⠄",
"⠻⣿⣿⣿⣿⣄⠰⢼⠄⠄⠄⡄⠁⢻⣍⣯⠃⠄⠄⠄⠄⠈⢿⣻⠃⠈⡆⡄⠄⠄⠄⠄⠄",
"⠄⠙⠿⠿⠛⣿⣶⣤⡇⠄⠄⢣⠄⠄⠈⠄⢠⠂⠄⠁⠄⡀⠄⠄⣀⠔⢁⠃⠄⠄⠄⠄⠄",
"⠄⠄⠄⠄⠄⣿⣿⣿⣿⣾⠢⣖⣶⣦⣤⣤⣬⣤⣤⣤⣴⣶⣶⡏⠠⢃⠌⠄⠄⠄⠄⠄⠄",
"⠄⠄⠄⠄⠄⠿⠿⠟⠛⡹⠉⠛⠛⠿⠿⣿⣿⣿⣿⣿⡿⠂⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄",
"⠠⠤⠤⠄⠄⣀⠄⠄⠄⠑⠠⣤⣀⣀⣀⡘⣿⠿⠙⠻⡍⢀⡈⠂⠄⠄⠄⠄⠄⠄⠄⠄⠄",
"⠄⠄⠄⠄⠄⠄⠑⠠⣠⣴⣾⣿⣿⣿⣿⣿⣿⣇⠉⠄⠻⣿⣷⣄⡀⠄⠄⠄⠄⠄⠄⠄⠄",
"file a bug report now or be cursed with this "
"annoying image in your syslog for all time."})
{
if(ctx_pp->IsUp() and not ctx_pp->LooksAlive())
{
for(const auto &wtf : {"you have been visited by the mascott of the "
"deadlocked router.",
"⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣀⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠄⠄⠄⠄",
"⠄⠄⠄⠄⠄⢀⣀⣀⡀⠄⠄⠄⡠⢲⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠄⠄",
"⠄⠄⠄⠔⣈⣀⠄⢔⡒⠳⡴⠊⠄⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⣿⣿⣧⠄⠄",
"⠄⢜⡴⢑⠖⠊⢐⣤⠞⣩⡇⠄⠄⠄⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣆⠄⠝⠛⠋⠐",
"⢸⠏⣷⠈⠄⣱⠃⠄⢠⠃⠐⡀⠄⠄⠄⠄⠙⠻⢿⣿⣿⣿⣿⣿⣿⣿⡿⠛⠸⠄⠄⠄⠄",
"⠈⣅⠞⢁⣿⢸⠘⡄⡆⠄⠄⠈⠢⡀⠄⠄⠄⠄⠄⠄⠉⠙⠛⠛⠛⠉⠉⡀⠄⠡⢀⠄⣀",
"⠄⠙⡎⣹⢸⠄⠆⢘⠁⠄⠄⠄⢸⠈⠢⢄⡀⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠃⠄⠄⠄⠄⠄",
"⠄⠄⠑⢿⠈⢆⠘⢼⠄⠄⠄⠄⠸⢐⢾⠄⡘⡏⠲⠆⠠⣤⢤⢤⡤⠄⣖⡇⠄⠄⠄⠄⠄",
"⣴⣶⣿⣿⣣⣈⣢⣸⠄⠄⠄⠄⡾⣷⣾⣮⣤⡏⠁⠘⠊⢠⣷⣾⡛⡟⠈⠄⠄⠄⠄⠄⠄",
"⣿⣿⣿⣿⣿⠉⠒⢽⠄⠄⠄⠄⡇⣿⣟⣿⡇⠄⠄⠄⠄⢸⣻⡿⡇⡇⠄⠄⠄⠄⠄⠄⠄",
"⠻⣿⣿⣿⣿⣄⠰⢼⠄⠄⠄⡄⠁⢻⣍⣯⠃⠄⠄⠄⠄⠈⢿⣻⠃⠈⡆⡄⠄⠄⠄⠄⠄",
"⠄⠙⠿⠿⠛⣿⣶⣤⡇⠄⠄⢣⠄⠄⠈⠄⢠⠂⠄⠁⠄⡀⠄⠄⣀⠔⢁⠃⠄⠄⠄⠄⠄",
"⠄⠄⠄⠄⠄⣿⣿⣿⣿⣾⠢⣖⣶⣦⣤⣤⣬⣤⣤⣤⣴⣶⣶⡏⠠⢃⠌⠄⠄⠄⠄⠄⠄",
"⠄⠄⠄⠄⠄⠿⠿⠟⠛⡹⠉⠛⠛⠿⠿⣿⣿⣿⣿⣿⡿⠂⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄",
"⠠⠤⠤⠄⠄⣀⠄⠄⠄⠑⠠⣤⣀⣀⣀⡘⣿⠿⠙⠻⡍⢀⡈⠂⠄⠄⠄⠄⠄⠄⠄⠄⠄",
"⠄⠄⠄⠄⠄⠄⠑⠠⣠⣴⣾⣿⣿⣿⣿⣿⣿⣇⠉⠄⠻⣿⣷⣄⡀⠄⠄⠄⠄⠄⠄⠄⠄",
"file a bug report now or be cursed with this "
"annoying image in your syslog for all time."})
{
LogError(wtf);
}
std::abort();
}
LogError(wtf);
llarp::LogContext::Instance().ImmediateFlush();
}
std::abort();
}
} while(ftr.wait_for(std::chrono::seconds(1)) != std::future_status::ready);
} while (ftr.wait_for(std::chrono::seconds(1)) != std::future_status::ready);
main_thread.join();
const auto code = ftr.get();
int code = 0;
try
{
code = ftr.get();
}
catch (const std::exception& e)
{
std::cerr << "main thread threw exception: " << e.what() << std::endl;
code = 1;
}
catch (...)
{
std::cerr << "main thread threw non-standard exception" << std::endl;
code = 2;
}
llarp::LogContext::Instance().ImmediateFlush();
#ifdef _WIN32
::WSACleanup();
ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, code);
#endif
if(ctx)
if (ctx)
{
llarp_main_free(ctx);
ctx.reset();
}
return code;
}
#ifdef _WIN32
VOID
ReportSvcStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint)
{
static DWORD dwCheckPoint = 1;
// Fill in the SERVICE_STATUS structure.
SvcStatus.dwCurrentState = dwCurrentState;
SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
SvcStatus.dwWaitHint = dwWaitHint;
if (dwCurrentState == SERVICE_START_PENDING)
SvcStatus.dwControlsAccepted = 0;
else
SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
if ((dwCurrentState == SERVICE_RUNNING) || (dwCurrentState == SERVICE_STOPPED))
SvcStatus.dwCheckPoint = 0;
else
SvcStatus.dwCheckPoint = dwCheckPoint++;
// Report the status of the service to the SCM.
SetServiceStatus(SvcStatusHandle, &SvcStatus);
}
VOID FAR PASCAL
SvcCtrlHandler(DWORD dwCtrl)
{
// Handle the requested control code.
switch (dwCtrl)
{
case SERVICE_CONTROL_STOP:
ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
// Signal the service to stop.
handle_signal(SIGINT);
return;
case SERVICE_CONTROL_INTERROGATE:
break;
default:
break;
}
}
// The win32 daemon entry point is just a trampoline that returns control
// to the original lokinet entry
// and only gets called if we get --win32-daemon in the command line
VOID FAR PASCAL
win32_daemon_entry(DWORD argc, LPTSTR* argv)
{
// Register the handler function for the service
SvcStatusHandle = RegisterServiceCtrlHandler("lokinet", SvcCtrlHandler);
if (!SvcStatusHandle)
{
llarp::LogError("failed to register daemon control handler");
return;
}
// These SERVICE_STATUS members remain as set here
SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
SvcStatus.dwServiceSpecificExitCode = 0;
// Report initial status to the SCM
ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);
// SCM clobbers startup args, regenerate them here
argc = 2;
argv[1] = "c:/programdata/.lokinet/lokinet.ini";
argv[2] = nullptr;
lokinet_main(argc, argv);
}
#endif

@ -0,0 +1,13 @@
[Unit]
Description=LokiNET VPN tunnel: shove all traffic over lokinet
Wants=lokinet.service
After=lokinet.service
[Service]
Type=oneshot
ExecStart=/usr/bin/lokinet-vpn --up
ExecStop=/usr/bin/lokinet-vpn --down
RemainAfterExit=true
[Install]
WantedBy=multi-user.target

1
doc

@ -1 +0,0 @@
docs

@ -0,0 +1,39 @@
find_program(DOXYGEN doxygen)
if (NOT DOXYGEN)
message(STATUS "Documentation generation disabled (doxygen not found)")
return()
endif()
find_program(SPHINX_BUILD sphinx-build)
if (NOT DOXYGEN)
message(STATUS "Documentation generation disabled (sphinx-build not found)")
return()
endif()
set(lokinet_doc_sources "${DOCS_SRC}")
string(REPLACE ";" " " lokinet_doc_sources_spaced "${lokinet_doc_sources}")
add_custom_command(
OUTPUT doxyxml/index.xml
COMMAND ${DOXYGEN} Doxyfile
DEPENDS
${CMAKE_CURRENT_BINARY_DIR}/Doxyfile
${lokinet_doc_sources}
)
add_custom_command(
OUTPUT html/index.html
COMMAND ${SPHINX_BUILD}
-Dbreathe_projects.lokinet=${CMAKE_CURRENT_BINARY_DIR}/doxyxml
-Dversion=${lokinet_VERSION} -Drelease=${lokinet_VERSION}
-Aversion=${lokinet_VERSION} -Aversions=${lokinet_VERSION_MAJOR},${lokinet_VERSION_MINOR},${lokinet_VERSION_PATCH}
-b html
${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}/html
DEPENDS
${CMAKE_CURRENT_BINARY_DIR}/index.rst
${CMAKE_CURRENT_BINARY_DIR}/conf.py
${CMAKE_CURRENT_BINARY_DIR}/doxyxml/index.xml
)
add_custom_target(doc DEPENDS html/index.html)
configure_file(conf.py.in conf.py @ONLY)
configure_file(Doxyfile.in Doxyfile @ONLY)
configure_file(index.rst index.rst COPYONLY)

@ -0,0 +1,20 @@
PROJECT_NAME = "Lokinet"
PROJECT_NUMBER = v@lokinet_VERSION@
PROJECT_BRIEF = "Anonymous, decentralized and IP based overlay network for the internet."
OUTPUT_DIRECTORY = @CMAKE_CURRENT_BINARY_DIR@
STRIP_FROM_PATH = @PROJECT_SOURCE_DIR@ @PROJECT_BINARY_DIR@
JAVADOC_AUTOBRIEF = YES
ALIASES = "rst=\verbatim embed:rst"
ALIASES += "endrst=\endverbatim"
BUILTIN_STL_SUPPORT = YES
INPUT = @lokinet_doc_sources_spaced@
INCLUDE_PATH = @PROJECT_SOURCE_DIR@/include @PROJECT_SOURCE_DIR@/llarp @PROJECT_SOURCE_DIR@/crypto/libntrup/include @PROJECT_SOURCE_DIR@/external/ghc-filesystem/include/
RECURSIVE = YES
CLANG_ASSISTED_PARSING = NO
#CLANG_OPTIONS = -std=c++17 -Wno-pragma-once-outside-header
GENERATE_HTML = NO
HTML_OUTPUT = doxyhtml
GENERATE_LATEX = NO
GENERATE_XML = YES
XML_OUTPUT = doxyxml
MACRO_EXPANSION = YES

@ -0,0 +1,117 @@
* lokinet components
** basic data structures
*** AlignedBuffer
*** RouterContact
**** self signed router descriptor
*** Crypto key types
** network / threading / sync utilities
*** threadpool
*** logic (single thread threadpool)
** configuration
*** ini parser
*** llarp::Configuration
** cryptography
*** llarp::Crypto interface
**** libsodium / sntrup implementation
*** llarp::CryptoManager
**** crypto implementation signleton manager
** nodedb
*** llarp_nodedb
**** holds many RouterContacts loaded from disk in memory
**** uses a filesystem skiplist for on disk storage
**** stores in a std::unordered_map addressable via public identity key
** event loop
*** llarp_event_loop
**** udp socket read/write
**** network interface packet read/write
**** stream connection (outbound stream)
**** stream acceptor (inbound stream)
** link layer message transport:
*** ILinkSession
**** the interface for an entity that is single session with relay
**** responsible for delivery recieval of link layer messages in full
*** ILinkLayer
**** bound to an address / interface
**** has a direction, inbound / outbound
**** distinctly identified by the union of interface and direction
**** Holds many ILinkSessions bound on the distinctly idenitfied direction/interface
** link layer messages
*** link layer message parser
**** parses buffers as bencoded dicts
*** link layer message handler
**** handles each type of link layer message
** IHopHandler
*** llarp::PathHopConfig
**** txid, rxid, shared secret at hop
*** llarp::path::Path
**** a built path or a path being built
**** owns a std::vector<PathHopConfig> for each hop's info
*** TransitHop
**** a single hop on a built path
**** has txid, rxid, shared secret, hash of shared secret
** pathset
*** path::Builder
**** builds and maintains a set of paths for a common use
** routing layer message router
*** routing::IMessageHandler
**** interface for routing layer message processing
**** transit hops implement this if they are an endpoint
**** path::Path implement this always
** dht "layer" / rc gossiper
*** TODO rewrite/refactor
** hidden service data structures
*** IntroSet
**** decrypted plaintext hidden service descriptor
*** EncryptedIntroSet
**** public encrpyted / signed version of IntroSet
** service endpoint / outbound context connectivitybackend
*** service::Endpoint
**** backend for sending/recieving packets over the hidden service protocol layer
**** kitchen sink
*** service::SendContext
**** interface type for sending to a resource on the network
*** service::OutboundContext
**** implements SendContext extends path::Builder and path::PathSet
**** for maintaining a pathset that aligns on an introset's intros
~
** snode / exit connectivity backend
*** exit::BaseSession
**** extends path::Builder
**** obtains an exit/snode session from the router they are aligning to
*** exit::Endpoint
**** snode/exit side of an exit::Session
** snapp / exit / mobile / null frontend handlers
*** handlers::TunEndpoint
**** extends service::Endpoint
**** provides tun interface frontend for hidden service backend
*** handlers::ExitEndpoint
**** provides tun interface frontend for exit/snode backend
** outbound message dispatcher
*** TODO tom please document these

@ -0,0 +1,189 @@
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'lokinet'
copyright = '2020, Jeff Becker'
author = 'Jeff Becker'
# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
release = ''
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['breathe', 'exhale']
breathe_projects = { "lokinet": "@CMAKE_CURRENT_BINARY_DIR@/doxyxml/" }
breathe_default_project = "lokinet"
breathe_domain_by_extension = {"h" : "cpp", "hpp": "cpp"}
exhale_args = {
# These arguments are required
"containmentFolder": "./api",
"rootFileName": "lokinet.rst",
"rootFileTitle": "lokinet internals",
"doxygenStripFromPath": "..",
# Suggested optional arguments
"createTreeView": True,
# TIP: if using the sphinx-bootstrap-theme, you need
# "treeViewIsBootstrap": True,
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
source_suffix = ['.rst', '.md']
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
highlight_language = 'c++'
primary_domain = 'cpp'
default_role = 'cpp:any'
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'lokinetdoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'lokinet.tex', 'lokinet Documentation',
'Jeff Becker', 'manual'),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'lokinet', 'lokinet Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'lokinet', 'lokinet Documentation',
author, 'lokinet', 'One line description of project.',
'Miscellaneous'),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']

@ -0,0 +1,12 @@
to configure lokinet to be an exit add into `lokinet.ini` `[network]` section the following:
exit=true
keyfile=/var/lib/lokinet/exit.private
reachable=1
ifaddr=10.0.0.1/16
post setup for exit (as root) given `eth0` is used to get to the internet:
# echo 1 > /proc/sys/net/ipv4/ip_forward
# iptables -t nat -A POSTROUTING -s 10.0.0.0/16 -o eth0 -j MASQUERADE

@ -0,0 +1,8 @@
Welcome to Lokinet Internals
============================
.. toctree::
:maxdepth: 2
api/lokinet

@ -0,0 +1,47 @@
# snapp config options
## required
### ifname
network interface name
### ifaddr
ip range of network interface
## optional
### keyfile
the private key to persist address with.
if not specified the address will be ephemeral.
### reachable
bool value that sets if we publish our snapp to the dht
`true`: we are reachable via dht
`false`: we are not reachable via dht
### hops
number of hops in a path, min is `1`, max is `8`, defaults to `4`
### paths
number of paths to maintain at any given time, defaults to `6`.
### blacklist-snode
adds a `.snode` to path build blacklist
### exit-node
specify a `.snode` or `.loki` address to use as an exit broker
### local-dns
address to bind local dns resoler to, defaults to `127.3.2.1:53`
if port is omitted it uses port `53`
### upstream-dns
address to forward non lokinet related queries to. if not set lokinet dns will reply with srvfail.
### mapaddr
perma map `.loki` address to an ip owned by the snapp
to map `whatever.loki` to `10.0.10.10` it can be specified via:
```
mapaddr=whatever.loki:10.0.10.10
```
## compile time optional features
### on-up
path to shell script to call when our interface is up
### on-down
path to shell script to call when our interface is down
### on-ready
path to shell script to call when snapp is first ready

@ -0,0 +1,38 @@
What is a RouterEvent?
A RouterEvent is a way of representing a conceptual event that took place in a "router" (relay or client).
RouterEvents are used in order to collect information about a network all in one place and preserve causality.
How do I make a new RouterEvent?
Add your event following the structure in llarp/tooling/router_event.{hpp,cpp}
Add your event to pybind in pybind/llarp/tooling/router_event.cpp
What if a class my event uses is missing members in pybind?
Find the relevant file pybind/whatever/class.cpp and remedy that!
What if I need to refer to classes which aren't available already in pybind?
Add pybind/namespace/namespace/etc/class.cpp and pybind it!
You will need to edit the following files accordingly:
pybind/common.hpp
pybind/module.cpp
pybind/CMakeLists.txt
How do I use a RouterEvent?
From the cpp side, find the place in the code where it makes the most logical sense
that the conceptual event has taken place (and you have the relevant information to
create the "event" instance) and create it there as follows:
#include <llarp/tooling/relevant_event_header.hpp>
where the event takes place, do the following:
auto event = std::make_unique<event_type_here>(constructor_args...);
somehow_get_a_router->NotifyRouterEvent(std::move(event));
From the Python side...it's a python object!

@ -0,0 +1 @@
Subproject commit ac35e705ebf20187b7ff92c29d1411f6a4c8d522

2
external/date vendored

@ -1 +1 @@
Subproject commit 9a0ee2542848ab8625984fc8cdbfb9b5414c0082
Subproject commit cac99da8dc88be719a728dc1b597b0ac307c1800

@ -1 +1 @@
Subproject commit e63a58c5bac94a3a75a7083f87bb092531407a92
Subproject commit d8abf146a43ea12d28b09dfa71ece3bad4168185

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

Loading…
Cancel
Save