Compare commits

..

9 Commits

Author SHA1 Message Date
Dmitriy Karpushin aef20430f2 Configuring of ikev2 2023-07-07 14:19:03 +03:00
Dmitriy Karpushin b818de3378 Merge remote-tracking branch 'origin/feature/ikev2_android' into feature/ikev2_android 2023-04-24 15:42:18 +03:00
Dmitriy Karpushin cf86c6e912 Start logic 2023-04-24 15:41:24 +03:00
Dmitry Karpushin 483263171b Merge branch 'dev' into feature/ikev2_android 2023-04-24 13:19:23 +03:00
Dmitriy Karpushin 5fb91d8f5b Update of strongswan submodule 2023-04-24 13:18:09 +03:00
Dmitriy Karpushin 100f8ad95d Refactoring of build process + utility classes 2023-04-24 13:05:56 +03:00
Dmitriy Karpushin e43041572e Strongswan submodule fixes 2023-04-13 09:55:58 +03:00
Dmitriy Karpushin 4b103a1622 Pre-configuring of StrongSwan from project cmake file 2023-04-13 09:14:56 +03:00
Dmitriy Karpushin b6c7ef415d strongswan submodule for IKEv2 support 2023-04-05 16:07:31 +03:00
88 changed files with 5193 additions and 491 deletions
+10 -8
View File
@@ -9,7 +9,7 @@ jobs:
runs-on: ubuntu-latest
env:
QT_VERSION: 6.5.0
QT_VERSION: 6.4.1
QIF_VERSION: 4.5
steps:
@@ -63,7 +63,7 @@ jobs:
runs-on: windows-latest
env:
QT_VERSION: 6.5.0
QT_VERSION: 6.4.1
QIF_VERSION: 4.5
BUILD_ARCH: 64
@@ -124,7 +124,8 @@ jobs:
runs-on: macos-latest
env:
QT_VERSION: 6.5.0
QT_VERSION: 6.4.1
QIF_VERSION: 4.4
steps:
- name: 'Setup xcode'
@@ -138,18 +139,18 @@ jobs:
version: ${{ env.QT_VERSION }}
host: 'mac'
target: 'desktop'
modules: 'qtremoteobjects qt5compat qtshadertools qtmultimedia'
arch: 'clang_64'
modules: 'qtremoteobjects qt5compat qtshadertools'
dir: ${{ runner.temp }}
set-env: 'true'
- name: 'Install iOS Qt'
- name: 'Install ios Qt'
uses: jurplel/install-qt-action@v3
with:
version: ${{ env.QT_VERSION }}
host: 'mac'
target: 'ios'
modules: 'qtremoteobjects qt5compat qtshadertools qtmultimedia'
modules: 'qtremoteobjects qt5compat qtshadertools'
dir: ${{ runner.temp }}
setup-python: 'true'
set-env: 'true'
@@ -199,7 +200,7 @@ jobs:
runs-on: macos-latest
env:
QT_VERSION: 6.5.0
QT_VERSION: 6.4.1
QIF_VERSION: 4.5
steps:
@@ -262,7 +263,8 @@ jobs:
arch: ['android_x86_64', 'android_x86'] #, 'android_armv7', 'android_arm64_v8a']
env:
QT_VERSION: 6.5.0
QT_VERSION: 6.4.1
QIF_VERSION: 4.5
steps:
- name: 'Install desktop Qt'
+1 -1
View File
@@ -129,4 +129,4 @@ captures/
client/3rd/ShadowSocks/ss_ios.xcconfig
# UML generated pics
out/
out/
+3
View File
@@ -34,6 +34,9 @@
[submodule "client/3rd/SortFilterProxyModel"]
path = client/3rd/SortFilterProxyModel
url = https://github.com/mitchcurtis/SortFilterProxyModel.git
[submodule "client/3rd/strongswan/sources"]
path = client/3rd/strongswan/sources
url = https://github.com/kolobchanin/strongswan.git
[submodule "client/3rd/mbedtls"]
path = client/3rd/mbedtls
url = https://github.com/Mbed-TLS/mbedtls.git
Submodule
+1
Submodule 3rd/QtSsh added at a34ded6e69
+6
View File
@@ -0,0 +1,6 @@
TEMPLATE = subdirs
SUBDIRS = client
!ios:!android {
SUBDIRS += service
}
+2 -15
View File
@@ -1,31 +1,18 @@
cmake_minimum_required(VERSION 3.25.0 FATAL_ERROR)
set(PROJECT AmneziaVPN)
project(${PROJECT} VERSION 3.0.7.1
DESCRIPTION "AmneziaVPN"
HOMEPAGE_URL "https://amnezia.org/"
)
set(RELEASE_DATE "2023-05-15")
set(APP_MAJOR_VERSION ${CMAKE_PROJECT_VERSION_MAJOR}.${CMAKE_PROJECT_VERSION_MINOR}.${CMAKE_PROJECT_VERSION_PATCH})
project(${PROJECT})
if(ANDROID)
set(QT_ANDROID_BUILD_ALL_ABIS ON)
endif()
# TODO: determine build step for arm64 build, from x86_64 host
if(APPLE AND NOT IOS)
if(CMAKE_HOST_SYSTEM_PROCESSOR STREQUAL "arm64")
set(CMAKE_OSX_ARCHITECTURES "arm64")
elseif(CMAKE_HOST_SYSTEM_PROCESSOR STREQUAL "x86_64")
set(CMAKE_OSX_ARCHITECTURES "x86_64")
endif()
set(CMAKE_OSX_ARCHITECTURES "x86_64")
endif()
add_subdirectory(client)
if(NOT IOS AND NOT ANDROID)
add_subdirectory(service)
include(${CMAKE_SOURCE_DIR}/deploy/installer/config.cmake)
endif()
+29 -24
View File
@@ -7,9 +7,10 @@ Amnezia is a VPN client with the key feature of deploying your own VPN server on
## Features
- Very easy to use - enter your ip address, ssh login and password, and Amnezia client will automatically install VPN docker containers to your server and connect to VPN.
- OpenVPN, ShadowSocks, WireGuard, IKEv2 protocols support.
- Split tunneling support - add any sites to client to enable VPN only for them (only for desktops)
- Windows, MacOS, Linux, Android, iOS releases.
- OpenVPN and OpenVPN over ShadowSocks protocols support.
- Custom VPN routing mode support - add any sites to client to enable VPN only for them.
- Windows and MacOS support.
- Unsecure sharing connection profile for family use.
## Tech
@@ -19,7 +20,7 @@ AmneziaVPN uses a number of open source projects to work:
- [OpenVPN](https://openvpn.net/)
- [ShadowSocks](https://shadowsocks.org/)
- [Qt](https://www.qt.io/)
- [LibSsh](https://libssh.org) - forked form Qt Creator
- [QtSsh](https://github.com/jaredtao/QtSsh) - forked form Qt Creator
- and more...
## Checking out the source code
@@ -35,35 +36,39 @@ git submodule update --init
Want to contribute? Welcome!
### Building sources and deployment
Look deploy folder for build scripts.
Easiest way to build your own executables - is to fork project and configure [Travis CI](https://travis-ci.com/)
Or you can build sources manually using Qt Creator. Qt >= 14.2 supported.
Look to the `build_macos.sh` and `build_windows.bat` scripts in `deploy` folder for details.
### How to build iOS app from source code on MacOS
1. First, make sure you have [XCode](https://developer.apple.com/xcode/) installed, at least version 14 or higher.
1. First, make sure you have [XCode](https://developer.apple.com/xcode/) installed,
at least version 12 or higher.
2. We use QT to generate the XCode project. we need QT version 6.4. Install QT for macos in [here](https://doc.qt.io/qt-6/macos.html)
3. Install cmake is require. We recommend cmake version 3.25. You can install cmake in [here](https://cmake.org/download/)
4. You also need to install go >= v1.16. If you don't have it done already,
2. We use `qmake` to generate the XCode project and then we "patch" it to add
extra components such as the wireguard, the browser bridge and so on. We patch
the XCode project using [xcodeproj](https://github.com/CocoaPods/Xcodeproj). To
install it:
```bash
gem install xcodeproj # probably you want to run this command with `sudo`
```
3. You also need to install go >= v1.16. If you don't have it done already,
download go from the [official website](https://golang.org/dl/) or use Homebrew.
Latest version is recommended. Install gomobile
Latest version is recommended.
4. Navigate inside client folder and generate the XCode project using our script:
```bash
export PATH=$PATH:~/go/bin
go install golang.org/x/mobile/cmd/gomobile@latest
gomobile init
cd client
./scripts/apple_compile.sh ios
```
5. Build project
If you have more than one version of Qt installed, you'll most likely get
a "`qmake` cannot be found in your `$PATH`" error. In this case run this script
using QT\IOS\_BIN env to set the path for the Qt5 macos build bin folder.
For example, the path could look like this:
```bash
export QT_BIN_DIR="<PATH-TO-QT-FOLDER>/Qt/<QT-VERSION>/ios/bin"
export QT_IOS_BIN=$QT_BIN_DIR
export PATH=$PATH:~/go/bin
mkdir build-ios
$QT_IOS_BIN/qt-cmake . -B build-ios -GXcode -DQT_HOST_PATH=$QT_BIN_DIR
QT_IOS_BIN="/Users/username/Qt/6.4.1/ios/bin" ./scripts/apple_compile.sh ios
```
Replace PATH-TO-QT-FOLDER and QT-VERSION to your environment
If you get `gomobile: command not found` make sure to set PATH to the location
of the bin folder where gomobile was installed. Usually, it's in `GOPATH`.
@@ -71,7 +76,7 @@ of the bin folder where gomobile was installed. Usually, it's in `GOPATH`.
export PATH=$(PATH):/path/to/GOPATH/bin
```
5. Open XCode project. You can then run/test/archive/ship the app.
5. Xcode should automatically open. You can then run/test/archive/ship the app.
If build fails with the following error
```
Binary file not shown.
Binary file not shown.
+20
View File
@@ -0,0 +1,20 @@
include(ExternalProject)
set(STRONGSWAN_SOURCES_ROOT ${CMAKE_CURRENT_LIST_DIR}/sources)
ExternalProject_Add(
strongswan
UPDATE_DISCONNECTED true
CONFIGURE_HANDLED_BY_BUILD true
PREFIX ${STRONGSWAN_SOURCES_ROOT}
SOURCE_DIR ${STRONGSWAN_SOURCES_ROOT}
BINARY_DIR ${STRONGSWAN_SOURCES_ROOT}
INSTALL_DIR ${STRONGSWAN_SOURCES_ROOT}
STAMP_DIR ${STRONGSWAN_SOURCES_ROOT}/stamp
LOG_DIR ${STRONGSWAN_SOURCES_ROOT}/log
TMP_DIR ${STRONGSWAN_SOURCES_ROOT}/tmp
CONFIGURE_COMMAND ./autogen.sh
COMMAND ./configure --disable-kernel-netlink
BUILD_COMMAND make #dist
INSTALL_COMMAND ""
)
+249
View File
@@ -0,0 +1,249 @@
#ifndef AmneziaVPN_Swift_h
#define AmneziaVPN_Swift_h
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgcc-compat"
#if !defined(__has_include)
# define __has_include(x) 0
#endif
#if !defined(__has_attribute)
# define __has_attribute(x) 0
#endif
#if !defined(__has_feature)
# define __has_feature(x) 0
#endif
#if !defined(__has_warning)
# define __has_warning(x) 0
#endif
#if __has_include(<swift/objc-prologue.h>)
# include <swift/objc-prologue.h>
#endif
#pragma clang diagnostic ignored "-Wauto-import"
#include <Foundation/Foundation.h>
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#if !defined(SWIFT_TYPEDEFS)
# define SWIFT_TYPEDEFS 1
# if __has_include(<uchar.h>)
# include <uchar.h>
# elif !defined(__cplusplus)
typedef uint_least16_t char16_t;
typedef uint_least32_t char32_t;
# endif
typedef float swift_float2 __attribute__((__ext_vector_type__(2)));
typedef float swift_float3 __attribute__((__ext_vector_type__(3)));
typedef float swift_float4 __attribute__((__ext_vector_type__(4)));
typedef double swift_double2 __attribute__((__ext_vector_type__(2)));
typedef double swift_double3 __attribute__((__ext_vector_type__(3)));
typedef double swift_double4 __attribute__((__ext_vector_type__(4)));
typedef int swift_int2 __attribute__((__ext_vector_type__(2)));
typedef int swift_int3 __attribute__((__ext_vector_type__(3)));
typedef int swift_int4 __attribute__((__ext_vector_type__(4)));
typedef unsigned int swift_uint2 __attribute__((__ext_vector_type__(2)));
typedef unsigned int swift_uint3 __attribute__((__ext_vector_type__(3)));
typedef unsigned int swift_uint4 __attribute__((__ext_vector_type__(4)));
#endif
#if !defined(SWIFT_PASTE)
# define SWIFT_PASTE_HELPER(x, y) x##y
# define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y)
#endif
#if !defined(SWIFT_METATYPE)
# define SWIFT_METATYPE(X) Class
#endif
#if !defined(SWIFT_CLASS_PROPERTY)
# if __has_feature(objc_class_property)
# define SWIFT_CLASS_PROPERTY(...) __VA_ARGS__
# else
# define SWIFT_CLASS_PROPERTY(...)
# endif
#endif
#if __has_attribute(objc_runtime_name)
# define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X)))
#else
# define SWIFT_RUNTIME_NAME(X)
#endif
#if __has_attribute(swift_name)
# define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X)))
#else
# define SWIFT_COMPILE_NAME(X)
#endif
#if __has_attribute(objc_method_family)
# define SWIFT_METHOD_FAMILY(X) __attribute__((objc_method_family(X)))
#else
# define SWIFT_METHOD_FAMILY(X)
#endif
#if __has_attribute(noescape)
# define SWIFT_NOESCAPE __attribute__((noescape))
#else
# define SWIFT_NOESCAPE
#endif
#if __has_attribute(ns_consumed)
# define SWIFT_RELEASES_ARGUMENT __attribute__((ns_consumed))
#else
# define SWIFT_RELEASES_ARGUMENT
#endif
#if __has_attribute(warn_unused_result)
# define SWIFT_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
# define SWIFT_WARN_UNUSED_RESULT
#endif
#if __has_attribute(noreturn)
# define SWIFT_NORETURN __attribute__((noreturn))
#else
# define SWIFT_NORETURN
#endif
#if !defined(SWIFT_CLASS_EXTRA)
# define SWIFT_CLASS_EXTRA
#endif
#if !defined(SWIFT_PROTOCOL_EXTRA)
# define SWIFT_PROTOCOL_EXTRA
#endif
#if !defined(SWIFT_ENUM_EXTRA)
# define SWIFT_ENUM_EXTRA
#endif
#if !defined(SWIFT_CLASS)
# if __has_attribute(objc_subclassing_restricted)
# define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA
# define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# else
# define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# endif
#endif
#if !defined(SWIFT_RESILIENT_CLASS)
# if __has_attribute(objc_class_stub)
# define SWIFT_RESILIENT_CLASS(SWIFT_NAME) SWIFT_CLASS(SWIFT_NAME) __attribute__((objc_class_stub))
# define SWIFT_RESILIENT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_class_stub)) SWIFT_CLASS_NAMED(SWIFT_NAME)
# else
# define SWIFT_RESILIENT_CLASS(SWIFT_NAME) SWIFT_CLASS(SWIFT_NAME)
# define SWIFT_RESILIENT_CLASS_NAMED(SWIFT_NAME) SWIFT_CLASS_NAMED(SWIFT_NAME)
# endif
#endif
#if !defined(SWIFT_PROTOCOL)
# define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA
# define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA
#endif
#if !defined(SWIFT_EXTENSION)
# define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__)
#endif
#if !defined(OBJC_DESIGNATED_INITIALIZER)
# if __has_attribute(objc_designated_initializer)
# define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
# else
# define OBJC_DESIGNATED_INITIALIZER
# endif
#endif
#if !defined(SWIFT_ENUM_ATTR)
# if defined(__has_attribute) && __has_attribute(enum_extensibility)
# define SWIFT_ENUM_ATTR(_extensibility) __attribute__((enum_extensibility(_extensibility)))
# else
# define SWIFT_ENUM_ATTR(_extensibility)
# endif
#endif
#if !defined(SWIFT_ENUM)
# define SWIFT_ENUM(_type, _name, _extensibility) enum _name : _type _name; enum SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type
# if __has_feature(generalized_swift_name)
# define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_ATTR(_extensibility) SWIFT_ENUM_EXTRA _name : _type
# else
# define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME, _extensibility) SWIFT_ENUM(_type, _name, _extensibility)
# endif
#endif
#if !defined(SWIFT_UNAVAILABLE)
# define SWIFT_UNAVAILABLE __attribute__((unavailable))
#endif
#if !defined(SWIFT_UNAVAILABLE_MSG)
# define SWIFT_UNAVAILABLE_MSG(msg) __attribute__((unavailable(msg)))
#endif
#if !defined(SWIFT_AVAILABILITY)
# define SWIFT_AVAILABILITY(plat, ...) __attribute__((availability(plat, __VA_ARGS__)))
#endif
#if !defined(SWIFT_WEAK_IMPORT)
# define SWIFT_WEAK_IMPORT __attribute__((weak_import))
#endif
#if !defined(SWIFT_DEPRECATED)
# define SWIFT_DEPRECATED __attribute__((deprecated))
#endif
#if !defined(SWIFT_DEPRECATED_MSG)
# define SWIFT_DEPRECATED_MSG(...) __attribute__((deprecated(__VA_ARGS__)))
#endif
#if __has_feature(attribute_diagnose_if_objc)
# define SWIFT_DEPRECATED_OBJC(Msg) __attribute__((diagnose_if(1, Msg, "warning")))
#else
# define SWIFT_DEPRECATED_OBJC(Msg) SWIFT_DEPRECATED_MSG(Msg)
#endif
#if !defined(IBSegueAction)
# define IBSegueAction
#endif
#if __has_feature(modules)
#if __has_warning("-Watimport-in-framework-header")
#pragma clang diagnostic ignored "-Watimport-in-framework-header"
#endif
@import Foundation;
@import ObjectiveC;
#endif
#pragma clang diagnostic ignored "-Wproperty-attribute-mismatch"
#pragma clang diagnostic ignored "-Wduplicate-method-arg"
#if __has_warning("-Wpragma-clang-attribute")
# pragma clang diagnostic ignored "-Wpragma-clang-attribute"
#endif
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#pragma clang diagnostic ignored "-Wnullability"
#if __has_attribute(external_source_symbol)
# pragma push_macro("any")
# undef any
# pragma clang attribute push(__attribute__((external_source_symbol(language="Swift", defined_in="AmneziaVPN",generated_declaration))), apply_to=any(function,enum,objc_interface,objc_category,objc_protocol))
# pragma pop_macro("any")
#endif
@class NSString;
@class NSData;
enum ConnectionState : NSInteger;
@class NSDate;
@class NSNumber;
@class VPNIPAddressRange;
SWIFT_CLASS("_TtC10AmneziaVPN18IOSVpnProtocolImpl")
@interface IOSVpnProtocolImpl : NSObject
- (nonnull instancetype)initWithBundleID:(NSString * _Nonnull)bundleID privateKey:(NSData * _Nonnull)privateKey deviceIpv4Address:(NSString * _Nonnull)deviceIpv4Address deviceIpv6Address:(NSString * _Nonnull)deviceIpv6Address closure:(void (^ _Nonnull)(enum ConnectionState, NSDate * _Nullable))closure callback:(void (^ _Nonnull)(BOOL))callback OBJC_DESIGNATED_INITIALIZER;
- (nonnull instancetype)initWithBundleID:(NSString * _Nonnull)bundleID config:(NSString * _Nonnull)config closure:(void (^ _Nonnull)(enum ConnectionState, NSDate * _Nullable))closure callback:(void (^ _Nonnull)(BOOL))callback;
- (nonnull instancetype)initWithBundleID:(NSString * _Nonnull)bundleID tunnelConfig:(NSString * _Nonnull)tunnelConfig ssConfig:(NSString * _Nonnull)ssConfig closure:(void (^ _Nonnull)(enum ConnectionState, NSDate * _Nullable))closure callback:(void (^ _Nonnull)(BOOL))callback;
- (void)connectWithDnsServer:(NSString * _Nonnull)dnsServer serverIpv6Gateway:(NSString * _Nonnull)serverIpv6Gateway serverPublicKey:(NSString * _Nonnull)serverPublicKey presharedKey:(NSString * _Nonnull)presharedKey serverIpv4AddrIn:(NSString * _Nonnull)serverIpv4AddrIn serverPort:(NSInteger)serverPort allowedIPAddressRanges:(NSArray<VPNIPAddressRange *> * _Nonnull)allowedIPAddressRanges ipv6Enabled:(Boolean)enabled reason:(NSInteger)reason failureCallback:(void (^ _Nonnull)(void))failureCallback;
- (void)connectWithOvpnConfig:(NSString * _Nonnull)ovpnConfig failureCallback:(void (^ _Nonnull)(void))failureCallback;
- (void)connectWithSsConfig:(NSString * _Nonnull)ssConfig ovpnConfig:(NSString * _Nonnull)ovpnConfig failureCallback:(void (^ _Nonnull)(void))failureCallback;
- (void)disconnect;
- (void)checkStatusWithCallback:(void (^ _Nonnull)(NSString * _Nonnull, NSString * _Nonnull, NSString * _Nonnull))callback;
- (nonnull instancetype)init SWIFT_UNAVAILABLE;
+ (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable");
@end
typedef SWIFT_ENUM(NSInteger, ConnectionState, closed) {
ConnectionStateError = 0,
ConnectionStateConnected = 1,
ConnectionStateDisconnected = 2,
};
SWIFT_CLASS("_TtC10AmneziaVPN17VPNIPAddressRange")
@interface VPNIPAddressRange : NSObject
- (nonnull instancetype)initWithAddress:(NSString * _Nonnull)address networkPrefixLength:(uint8_t)networkPrefixLength isIpv6:(BOOL)isIpv6 OBJC_DESIGNATED_INITIALIZER;
- (nonnull instancetype)init SWIFT_UNAVAILABLE;
+ (nonnull instancetype)new SWIFT_UNAVAILABLE_MSG("-init is unavailable");
@end
#if __has_attribute(external_source_symbol)
# pragma clang attribute pop
#endif
#pragma clang diagnostic pop
#endif /* AmneziaVPN_Swift_h */
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.application-groups</key>
<array>
<string>group.org.amnezia.AmneziaVPN</string>
</array>
<key>keychain-access-groups</key>
<array>
<string>$(AppIdentifierPrefix)group.org.amnezia.AmneziaVPN</string>
</array>
</dict>
</plist>
+134 -115
View File
@@ -1,11 +1,14 @@
cmake_minimum_required(VERSION 3.25.0 FATAL_ERROR)
set(PROJECT AmneziaVPN)
project(${PROJECT})
set(QT_BUILD_TOOLS_WHEN_CROSS_COMPILING ON)
project(${PROJECT} VERSION 2.1.2)
set(BUILD_ID 1)
SET(QT_BUILD_TOOLS_WHEN_CROSS_COMPILING ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(${CMAKE_VERSION} VERSION_GREATER_EQUAL 3.17)
cmake_policy(SET CMP0099 OLD)
endif()
if(ANDROID)
# For a some reason cmake do not applying GNU_SOURCE/BSD_SOURCE flags on Android platform.
@@ -13,37 +16,29 @@ if(ANDROID)
add_definitions(-D_BSD_SOURCE)
endif()
if(CMAKE_XCODE_BUILD_SYSTEM VERSION_GREATER_EQUAL 12)
cmake_policy(SET CMP0114 NEW)
endif()
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
set_property(GLOBAL PROPERTY AUTOGEN_TARGETS_FOLDER "Autogen")
set_property(GLOBAL PROPERTY AUTOMOC_TARGETS_FOLDER "Autogen")
set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER "Autogen")
set(PACKAGES
Widgets Core Gui Network Xml
RemoteObjects Quick Svg QuickControls2
Core5Compat Concurrent
find_package(Qt6 REQUIRED COMPONENTS
Widgets Core Gui Network Xml
RemoteObjects Quick Svg QuickControls2
Core5Compat Concurrent
)
if(IOS)
set(PACKAGES
${PACKAGES}
Multimedia
)
endif()
find_package(Qt6 REQUIRED COMPONENTS ${PACKAGES})
set(LIBS ${LIBS}
Qt6::Widgets Qt6::Core Qt6::Gui
Qt6::Network Qt6::Xml Qt6::RemoteObjects
Qt6::Quick Qt6::Svg Qt6::QuickControls2
Qt6::Core5Compat Qt6::Concurrent
)
if(IOS)
set(LIBS
${LIBS}
Qt6::Multimedia
)
endif()
qt_standard_project_setup()
@@ -69,8 +64,6 @@ include_directories(
${CMAKE_CURRENT_BINARY_DIR}
)
configure_file(${CMAKE_CURRENT_LIST_DIR}/../version.h.in ${CMAKE_CURRENT_BINARY_DIR}/version.h)
set(HEADERS ${HEADERS}
${CMAKE_CURRENT_LIST_DIR}/migrations.h
${CMAKE_CURRENT_LIST_DIR}/../ipc/ipc.h
@@ -89,7 +82,6 @@ set(HEADERS ${HEADERS}
${CMAKE_CURRENT_LIST_DIR}/ui/uilogic.h
${CMAKE_CURRENT_LIST_DIR}/ui/qautostart.h
${CMAKE_CURRENT_LIST_DIR}/protocols/vpnprotocol.h
${CMAKE_CURRENT_BINARY_DIR}/version.h
${CMAKE_CURRENT_LIST_DIR}/core/sshclient.h
)
@@ -154,11 +146,6 @@ qt6_add_resources(QRC ${QRC} ${CMAKE_CURRENT_LIST_DIR}/resources.qrc)
if(WIN32)
add_compile_definitions(MVPN_WINDOWS)
configure_file(
${CMAKE_CURRENT_LIST_DIR}/platforms/windows/amneziavpn.rc.in
${CMAKE_CURRENT_BINARY_DIR}/amneziavpn.rc
)
set(HEADERS ${HEADERS}
${CMAKE_CURRENT_LIST_DIR}/protocols/ikev2_vpn_protocol_windows.h
)
@@ -168,7 +155,7 @@ if(WIN32)
)
set(RESOURCES ${RESOURCES}
${CMAKE_CURRENT_BINARY_DIR}/amneziavpn.rc
${CMAKE_CURRENT_LIST_DIR}/platforms/windows/amneziavpn.rc
)
set(LIBS ${LIBS}
@@ -184,9 +171,6 @@ if(WIN32)
endif()
if(APPLE)
cmake_policy(SET CMP0099 OLD)
cmake_policy(SET CMP0114 NEW)
if(NOT BUILD_OSX_APP_IDENTIFIER)
set(BUILD_OSX_APP_IDENTIFIER org.amnezia.AmneziaVPN CACHE STRING "OSX Application identifier")
endif()
@@ -204,6 +188,7 @@ if(APPLE)
set(CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM ${BUILD_VPN_DEVELOPMENT_TEAM})
set(CMAKE_XCODE_ATTRIBUTE_GROUP_ID_IOS ${BUILD_IOS_GROUP_IDENTIFIER})
#set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../build)
if(NOT IOS)
set(CMAKE_OSX_ARCHITECTURES "x86_64" CACHE INTERNAL "" FORCE)
@@ -211,7 +196,7 @@ if(APPLE)
set(HEADERS ${HEADERS} ${CMAKE_CURRENT_LIST_DIR}/ui/macos_util.h)
set(SOURCES ${SOURCES} ${CMAKE_CURRENT_LIST_DIR}/ui/macos_util.mm)
set(CMAKE_OSX_DEPLOYMENT_TARGET 10.15)
set(CMAKE_OSX_DEPLOYMENT_TARGET 13.0)
add_compile_definitions(MVPN_MACOS)
# ICON = $$PWD/images/app.icns
@@ -222,7 +207,7 @@ if(APPLE)
find_library(FW_APPKIT AppKit)
find_library(FW_SECURITY Security)
set(LIBS ${LIBS}
set(LIBS ${LIBS}
${FW_COCOA} ${FW_APPLICATIONSERVICES}
${FW_FOUNDATION} ${FW_APPKIT}
${FW_SECURITY} ${FW_CORESERVICES}
@@ -231,6 +216,7 @@ if(APPLE)
endif()
endif()
if(LINUX AND NOT ANDROID)
add_compile_definitions(MVPN_LINUX)
@@ -240,7 +226,7 @@ endif()
if(WIN32 OR (APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
message("Client desktop build")
add_compile_definitions(AMNEZIA_DESKTOP)
set(HEADERS ${HEADERS}
${CMAKE_CURRENT_LIST_DIR}/core/ipcclient.h
${CMAKE_CURRENT_LIST_DIR}/core/privileged_process.h
@@ -287,6 +273,8 @@ if(ANDROID)
${CMAKE_CURRENT_LIST_DIR}/platforms/android/androidvpnactivity.cpp
${CMAKE_CURRENT_LIST_DIR}/protocols/android_vpnprotocol.cpp
)
file(COPY ${CMAKE_CURRENT_LIST_DIR}/3rd/strongswan DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/3rd)
endif()
if(IOS)
@@ -311,26 +299,26 @@ if(IOS)
add_compile_definitions(MVPN_IOS)
set(HEADERS ${HEADERS}
${CMAKE_CURRENT_LIST_DIR}/protocols/ios_vpnprotocol.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/iosnotificationhandler.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/json.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/bigint.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/bigintipv6addr.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/ipaddress.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/ipaddressrange.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/QtAppDelegate.h
${CMAKE_CURRENT_LIST_DIR}/protocols/ios_vpnprotocol.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/iosnotificationhandler.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/json.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/bigint.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/bigintipv6addr.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/ipaddress.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/ipaddressrange.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/QtAppDelegate.h
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/QtAppDelegate-C-Interface.h
)
set(SOURCES ${SOURCES}
${CMAKE_CURRENT_LIST_DIR}/protocols/ios_vpnprotocol.mm
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/iosnotificationhandler.mm
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/json.cpp
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/iosglue.mm
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/ipaddress.cpp
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/ipaddressrange.cpp
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/QRCodeReaderBase.mm
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/QtAppDelegate.mm
${CMAKE_CURRENT_LIST_DIR}/protocols/ios_vpnprotocol.mm
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/iosnotificationhandler.mm
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/json.cpp
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/iosglue.mm
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/ipaddress.cpp
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/ipaddressrange.cpp
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/QRCodeReaderBase.mm
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/QtAppDelegate.mm
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/MobileUtils.mm
)
endif()
@@ -345,7 +333,9 @@ qt_add_translations(${PROJECT} TS_FILES
${CMAKE_CURRENT_LIST_DIR}/translations/amneziavpn_ru.ts)
if(APPLE AND NOT IOS)
set_target_properties(${PROJECT} PROPERTIES MACOSX_BUNDLE TRUE)
set_target_properties(AmneziaVPN PROPERTIES
MACOSX_BUNDLE TRUE
)
endif()
if(IOS)
@@ -353,66 +343,66 @@ if(IOS)
enable_language(OBJCXX)
enable_language(Swift)
#disable in cicd
include(cmake/osxtools.cmake)
# set(CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY TRUE)
set_target_properties(${PROJECT} PROPERTIES XCODE_ATTRIBUTE_ENABLE_BITCODE "NO")
set_target_properties(${PROJECT} PROPERTIES XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_APPICON_NAME "AppIcon")
set_target_properties(${PROJECT} PROPERTIES XCODE_LINK_BUILD_PHASE_MODE KNOWN_LOCATION)
set(CMAKE_XCODE_ATTRIBUTE_LD_RUNPATH_SEARCH_PATHS "@executable_path/../../Frameworks")
set(CMAKE_XCODE_ATTRIBUTE_FRAMEWORK_SEARCH_PATHS ${CMAKE_CURRENT_LIST_DIR}/3rd/OpenVPNAdapter/build/Release-iphoneos)
#need to change for debug and release
set_target_properties(${PROJECT}
PROPERTIES XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "org.amnezia.${PROJECT}"
XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1"
XCODE_ATTRIBUTE_DEVELOPMENT_TEAM "X7UJ388FXK"
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "Apple Distribution"
)
set_target_properties(${PROJECT}
PROPERTIES XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "org.amnezia.${PROJECT}"
XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1"
XCODE_ATTRIBUTE_DEVELOPMENT_TEAM "X7UJ388FXK"
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY[variant=Debug] "Apple Development"
)
set(LIBS ${LIBS}
${CMAKE_CURRENT_LIST_DIR}/3rd/OpenSSL/lib/ios/iphone/libcrypto.a
${CMAKE_CURRENT_LIST_DIR}/3rd/OpenSSL/lib/ios/iphone/libssl.a
)
)
target_include_directories(${PROJECT} PRIVATE ${Qt6Gui_PRIVATE_INCLUDE_DIRS})
set(BUILD_ID ${A_PROJECT_BUILD})
set_target_properties(${PROJECT} PROPERTIES
XCODE_LINK_BUILD_PHASE_MODE KNOWN_LOCATION
MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_LIST_DIR}/ios/app/Info.plist.in
MACOSX_BUNDLE_ICON_FILE "AppIcon"
MACOSX_BUNDLE_INFO_STRING "AmneziaVPN"
MACOSX_BUNDLE_BUNDLE_NAME "AmneziaVPN"
MACOSX_BUNDLE_GUI_IDENTIFIER "${BUILD_IOS_APP_IDENTIFIER}"
MACOSX_BUNDLE_BUNDLE_VERSION "${CMAKE_PROJECT_VERSION_TWEAK}"
MACOSX_BUNDLE_LONG_VERSION_STRING "${CMAKE_PROJECT_VERSION}-${BUILD_ID}"
MACOSX_BUNDLE_SHORT_VERSION_STRING "${CMAKE_PROJECT_VERSION}"
XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "${BUILD_IOS_APP_IDENTIFIER}"
XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS "${CMAKE_CURRENT_LIST_DIR}/ios/app/main.entitlements"
XCODE_ATTRIBUTE_MARKETING_VERSION "${APP_MAJOR_VERSION}"
XCODE_ATTRIBUTE_CURRENT_PROJECT_VERSION "${CMAKE_PROJECT_VERSION_TWEAK}"
XCODE_ATTRIBUTE_PRODUCT_NAME "AmneziaVPN"
XCODE_ATTRIBUTE_BUNDLE_INFO_STRING "AmneziaVPN"
XCODE_GENERATE_SCHEME TRUE
XCODE_ATTRIBUTE_ENABLE_BITCODE "NO"
XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_APPICON_NAME "AppIcon"
XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1,2"
XCODE_EMBED_FRAMEWORKS_CODE_SIGN_ON_COPY ON
XCODE_LINK_BUILD_PHASE_MODE KNOWN_LOCATION
XCODE_ATTRIBUTE_LD_RUNPATH_SEARCH_PATHS "@executable_path/Frameworks"
XCODE_EMBED_APP_EXTENSIONS networkextension
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "Apple Distribution"
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY[variant=Debug] "Apple Development"
XCODE_ATTRIBUTE_CODE_SIGN_STYLE Manual
XCODE_ATTRIBUTE_PROVISIONING_PROFILE_SPECIFIER "match AppStore org.amnezia.AmneziaVPN"
XCODE_ATTRIBUTE_PROVISIONING_PROFILE_SPECIFIER[variant=Debug] "match Development org.amnezia.AmneziaVPN"
)
set_target_properties(${PROJECT} PROPERTIES
XCODE_ATTRIBUTE_SWIFT_VERSION "5.0"
XCODE_ATTRIBUTE_CLANG_ENABLE_MODULES "YES"
XCODE_ATTRIBUTE_SWIFT_OBJC_BRIDGING_HEADER "${CMAKE_CURRENT_LIST_DIR}/platforms/ios/WireGuard-Bridging-Header.h"
XCODE_ATTRIBUTE_SWIFT_PRECOMPILE_BRIDGING_HEADER "NO"
XCODE_ATTRIBUTE_SWIFT_OPTIMIZATION_LEVEL "-Onone"
XCODE_ATTRIBUTE_SWIFT_OBJC_INTERFACE_HEADER_NAME "AmneziaVPN-Swift.h"
)
set_target_properties(${PROJECT} PROPERTIES
XCODE_ATTRIBUTE_DEVELOPMENT_TEAM "X7UJ388FXK"
OUTPUT_NAME "AmneziaVPN"
MACOSX_BUNDLE ON
MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_LIST_DIR}/ios/app/Info.plist.in
MACOSX_BUNDLE_BUNDLE_NAME "AmneziaVPN"
MACOSX_BUNDLE_BUNDLE_VERSION "${BUILD_ID}"
MACOSX_BUNDLE_COPYRIGHT "MPL-2.0"
MACOSX_BUNDLE_GUI_IDENTIFIER "${BUILD_IOS_APP_IDENTIFIER}"
MACOSX_BUNDLE_INFO_STRING "AmneziaVPN"
MACOSX_BUNDLE_LONG_VERSION_STRING "${CMAKE_PROJECT_VERSION}-${BUILD_ID}"
MACOSX_BUNDLE_SHORT_VERSION_STRING "${CMAKE_PROJECT_VERSION}"
XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "${BUILD_IOS_APP_IDENTIFIER}"
XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS "${CMAKE_CURRENT_LIST_DIR}/ios/app/main.entitlements"
XCODE_ATTRIBUTE_MARKETING_VERSION "${CMAKE_PROJECT_VERSION}"
XCODE_GENERATE_SCHEME TRUE
MACOSX_BUNDLE_ICON_FILE "AppIcon"
)
target_include_directories(${PROJECT} PRIVATE ${CMAKE_CURRENT_LIST_DIR})
@@ -422,10 +412,8 @@ if(IOS)
-DVPN_NE_BUNDLEID=\"${BUILD_IOS_APP_IDENTIFIER}.network-extension\"
)
target_sources(${PROJECT} PRIVATE
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/iosvpnprotocol.swift
${CMAKE_CURRENT_LIST_DIR}/platforms/ios/ioslogger.swift
target_sources(${PROJECT} PRIVATE
${CMAKE_CURRENT_LIST_DIR}/3rd/wireguard-apple/Sources/Shared/Keychain.swift
${CMAKE_CURRENT_LIST_DIR}/3rd/wireguard-apple/Sources/WireGuardKit/IPAddressRange.swift
${CMAKE_CURRENT_LIST_DIR}/3rd/wireguard-apple/Sources/WireGuardKit/InterfaceConfiguration.swift
@@ -442,43 +430,75 @@ if(IOS)
${CMAKE_CURRENT_LIST_DIR}/3rd/wireguard-apple/Sources/WireGuardKit/PrivateKey.swift
)
target_sources(${PROJECT} PRIVATE
platforms/ios/iosvpnprotocol.swift
platforms/ios/ioslogger.swift
)
target_sources(${PROJECT} PRIVATE
${CMAKE_CURRENT_LIST_DIR}/ios/app/launch.png
${CMAKE_CURRENT_LIST_DIR}/ios/app/AmneziaVPNLaunchScreen.storyboard
${CMAKE_CURRENT_LIST_DIR}/ios/Media.xcassets
)
set_source_files_properties(
${CMAKE_CURRENT_LIST_DIR}/ios/app/launch.png
${CMAKE_CURRENT_LIST_DIR}/ios/app/AmneziaVPNLaunchScreen.storyboard
PROPERTIES MACOSX_PACKAGE_LOCATION "Resources"
)
target_sources(${PROJECT} PRIVATE
${CMAKE_CURRENT_LIST_DIR}/ios/Media.xcassets
)
set_source_files_properties(
${CMAKE_CURRENT_LIST_DIR}/ios/Media.xcassets
PROPERTIES MACOSX_PACKAGE_LOCATION "Resources"
)
add_subdirectory(ios/networkextension)
add_dependencies(${PROJECT} networkextension)
set_target_properties(${PROJECT} PROPERTIES XCODE_EMBED_APP_EXTENSIONS networkextension)
set_property(TARGET ${PROJECT} PROPERTY XCODE_EMBED_FRAMEWORKS
"${CMAKE_CURRENT_LIST_DIR}/3rd/OpenVPNAdapter/build/Release-iphoneos/OpenVPNAdapter.framework"
)
set_target_properties(${PROJECT} PROPERTIES XCODE_EMBED_FRAMEWORKS_CODE_SIGN_ON_COPY ON)
set_target_properties(${PROJECT} PROPERTIES XCODE_LINK_BUILD_PHASE_MODE KNOWN_LOCATION)
set(CMAKE_XCODE_ATTRIBUTE_FRAMEWORK_SEARCH_PATHS ${CMAKE_CURRENT_LIST_DIR}/3rd/OpenVPNAdapter/build/Release-iphoneos)
target_link_libraries("networkextension" PRIVATE "${CMAKE_CURRENT_LIST_DIR}/3rd/OpenVPNAdapter/build/Release-iphoneos/OpenVPNAdapter.framework")
set_target_properties("networkextension"
PROPERTIES XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "org.amnezia.${PROJECT}.network-extension"
XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1"
XCODE_ATTRIBUTE_DEVELOPMENT_TEAM "X7UJ388FXK"
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "Apple Distribution"
)
set_target_properties("networkextension"
PROPERTIES XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "org.amnezia.${PROJECT}.network-extension"
XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1"
XCODE_ATTRIBUTE_DEVELOPMENT_TEAM "X7UJ388FXK"
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY[variant=Debug] "Apple Development"
)
set_target_properties (${PROJECT} PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_STYLE Manual)
set_target_properties(${PROJECT} PROPERTIES XCODE_ATTRIBUTE_PROVISIONING_PROFILE_SPECIFIER "match AppStore org.amnezia.AmneziaVPN")
set_target_properties(${PROJECT} PROPERTIES XCODE_ATTRIBUTE_PROVISIONING_PROFILE_SPECIFIER[variant=Debug] "match Development org.amnezia.AmneziaVPN")
set_target_properties("networkextension" PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_STYLE Manual)
set_target_properties("networkextension" PROPERTIES XCODE_ATTRIBUTE_PROVISIONING_PROFILE_SPECIFIER "match AppStore org.amnezia.AmneziaVPN.network-extension")
set_target_properties("networkextension" PROPERTIES XCODE_ATTRIBUTE_PROVISIONING_PROFILE_SPECIFIER[variant=Debug] "match Development org.amnezia.AmneziaVPN.network-extension")
endif()
if(ANDROID)
add_custom_command(
TARGET ${PROJECT} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_LIST_DIR}/android/AndroidManifest.xml
${CMAKE_CURRENT_LIST_DIR}/android/build.gradle
${CMAKE_CURRENT_LIST_DIR}/android/gradle/wrapper/gradle-wrapper.jar
${CMAKE_CURRENT_LIST_DIR}/android/gradle/wrapper/gradle-wrapper.properties
${CMAKE_CURRENT_LIST_DIR}/android/gradlew
${CMAKE_CURRENT_LIST_DIR}/android/gradlew.bat
${CMAKE_CURRENT_LIST_DIR}/android/gradle.properties
${CMAKE_CURRENT_LIST_DIR}/android/res/values/libs.xml
${CMAKE_CURRENT_LIST_DIR}/android/AndroidManifest.xml
${CMAKE_CURRENT_LIST_DIR}/android/build.gradle
${CMAKE_CURRENT_LIST_DIR}/android/gradle/wrapper/gradle-wrapper.jar
${CMAKE_CURRENT_LIST_DIR}/android/gradle/wrapper/gradle-wrapper.properties
${CMAKE_CURRENT_LIST_DIR}/android/gradlew
${CMAKE_CURRENT_LIST_DIR}/android/gradlew.bat
${CMAKE_CURRENT_LIST_DIR}/android/gradle.properties
${CMAKE_CURRENT_LIST_DIR}/android/res/values/libs.xml
${CMAKE_CURRENT_LIST_DIR}/android/res/xml/fileprovider.xml
${CMAKE_CURRENT_LIST_DIR}/android/src/org/amnezia/vpn/AuthHelper.java
${CMAKE_CURRENT_LIST_DIR}/android/src/org/amnezia/vpn/IPCContract.kt
@@ -489,7 +509,6 @@ if(ANDROID)
${CMAKE_CURRENT_LIST_DIR}/android/src/org/amnezia/vpn/VPNService.kt
${CMAKE_CURRENT_LIST_DIR}/android/src/org/amnezia/vpn/VPNServiceBinder.kt
${CMAKE_CURRENT_LIST_DIR}/android/src/org/amnezia/vpn/qt/AmneziaApp.kt
${CMAKE_CURRENT_LIST_DIR}/android/src/org/amnezia/vpn/qt/PackageManagerHelper.java
${CMAKE_CURRENT_LIST_DIR}/android/src/org/amnezia/vpn/qt/VPNActivity.kt
${CMAKE_CURRENT_LIST_DIR}/android/src/org/amnezia/vpn/qt/VPNApplication.java
${CMAKE_CURRENT_LIST_DIR}/android/src/org/amnezia/vpn/qt/VPNClientBinder.kt
@@ -498,7 +517,7 @@ if(ANDROID)
)
set_property(TARGET ${PROJECT} PROPERTY
QT_ANDROID_PACKAGE_SOURCE_DIR
QT_ANDROID_PACKAGE_SOURCE_DIR
${CMAKE_CURRENT_LIST_DIR}/android
)
@@ -565,5 +584,5 @@ if(WIN32)
)
endif()
if(IOS)
include(cmake/ios-arch-fixup.cmake)
#include(cmake/ios-arch-fixup.cmake)
endif()
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string>${ASSETCATALOG_COMPILER_APPICON_NAME}</string>
<key>CFBundleIdentifier</key>
<string>${PRODUCT_BUNDLE_IDENTIFIER}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>${QMAKE_PKGINFO_TYPEINFO}</string>
<key>LSMinimumSystemVersion</key>
<string>${MACOSX_DEPLOYMENT_TARGET}</string>
<key>NOTE</key>
<string>This file was generated by Qt/QMake.</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSSupportsAutomaticGraphicsSwitching</key>
<true/>
</dict>
</plist>
+29
View File
@@ -0,0 +1,29 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "wireguard-go-version.h"
#include "3rd/wireguard-apple/Sources/WireGuardKitC/WireGuardKitC.h"
#include <stdbool.h>
#include <stdint.h>
#define WG_KEY_LEN (32)
#define WG_KEY_LEN_BASE64 (45)
#define WG_KEY_LEN_HEX (65)
void key_to_base64(char base64[WG_KEY_LEN_BASE64],
const uint8_t key[WG_KEY_LEN]);
bool key_from_base64(uint8_t key[WG_KEY_LEN], const char* base64);
void key_to_hex(char hex[WG_KEY_LEN_HEX], const uint8_t key[WG_KEY_LEN]);
bool key_from_hex(uint8_t key[WG_KEY_LEN], const char* hex);
bool key_eq(const uint8_t key1[WG_KEY_LEN], const uint8_t key2[WG_KEY_LEN]);
void write_msg_to_log(const char* tag, const char* msg);
#import "TargetConditionals.h"
#if TARGET_OS_OSX
# include <libproc.h>
#endif
+1 -1
View File
@@ -8,7 +8,7 @@
#include "core/servercontroller.h"
#include "logger.h"
#include "version.h"
#include "defines.h"
#include <QQuickStyle>
#include "platforms/ios/QRCodeReaderBase.h"
+39 -6
View File
@@ -1,7 +1,7 @@
apply plugin: 'com.github.ben-manes.versions'
buildscript {
ext{
ext {
kotlin_version = "1.7.22"
// for libwg
appcompatVersion = '1.1.0'
@@ -11,6 +11,7 @@ buildscript {
streamsupportVersion = '1.7.0'
threetenabpVersion = '1.1.1'
groupName = 'org.amnezia.vpn'
relativePathToStrongswan = '../3rd/strongswan/sources/src/frontends/android/app/src/main/jni'
}
repositories {
@@ -105,7 +106,7 @@ android {
resources.srcDirs = ['resources']
renderscript.srcDirs = ['src']
assets.srcDirs = ['assets']
jniLibs.srcDirs = ['libs']
jniLibs.srcDirs = ['libs', relativePathToStrongswan]
androidTest.assets.srcDirs += files("${qtAndroidDir}/schemas".toString())
}
}
@@ -138,33 +139,65 @@ android {
targetSdkVersion = 31
versionCode 10 // Change to a higher number
versionName "2.0.10" // Change to a higher number
multiDexEnabled true
javaCompileOptions.annotationProcessorOptions.arguments = [
"room.schemaLocation": "${qtAndroidDir}/schemas".toString()
]
}
buildTypes {
buildTypes {
release {
// That would enable treeshaking and remove java code that is just called from qt
minifyEnabled false
externalNativeBuild {
cmake {
arguments "-DANDROID_PACKAGE_NAME=${groupName}", "-DGRADLE_USER_HOME=${project.gradle.gradleUserHomeDir}"
arguments "-DANDROID_PACKAGE_NAME=${groupName}",
"-DGRADLE_USER_HOME=${project.gradle.gradleUserHomeDir}"
}
}
}
debug {
//applicationIdSuffix ".debug"
//versionNameSuffix "-debug"
minifyEnabled false
externalNativeBuild {
cmake {
arguments "-DANDROID_PACKAGE_NAME=${groupName}", "-DGRADLE_USER_HOME=${project.gradle.gradleUserHomeDir}"
arguments "-DANDROID_PACKAGE_NAME=${groupName}",
"-DGRADLE_USER_HOME=${project.gradle.gradleUserHomeDir}"
}
}
}
}
}
task buildStrongSwanNative(type: Exec) {
environment = System.getenv() + ['JNI_PACKAGE': 'org_amnezia_vpn', 'JNI_PACKAGE_STRING': 'org/amnezia/vpn']
workingDir "${relativePathToStrongswan}"
commandLine "${android.ndkDirectory}/ndk-build", '-j', Runtime.runtime.availableProcessors()
doLast {
copy {
from "${workingDir} + /../libs"
into 'libs'
}
}
}
task cleanStrongSwanNative(type: Exec) {
workingDir "${relativePathToStrongswan}"
commandLine "${android.ndkDirectory}/ndk-build", 'clean'
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn buildStrongSwanNative
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
clean.dependsOn 'cleanStrongSwanNative'
// externalNativeBuild {
// cmake {
@@ -0,0 +1,761 @@
package org.amnezia.vpn
import android.annotation.TargetApi
import android.content.pm.PackageManager
import android.net.VpnService
import android.net.VpnService.Builder
import android.os.Build
import android.os.ParcelFileDescriptor
import android.system.OsConstants
import java.lang.Runnable
import org.amnezia.vpn.ikev2.VpnProfile
import org.amnezia.vpn.ikev2.VpnProfile.SelectedAppsHandling
import org.amnezia.vpn.ikev2.VpnType
import org.amnezia.vpn.ikev2.VpnType.VpnTypeFeature
import org.amnezia.vpn.ikev2.utils.IPRange
import org.amnezia.vpn.ikev2.utils.IPRangeSet
import org.amnezia.vpn.ikev2.utils.Utils
import org.amnezia.vpn.ikev2.utils.Constants
import org.amnezia.vpn.ikev2.utils.SettingsWriter
import org.amnezia.vpn.ikev2.utils.SimpleFetcher
const val PACKAGE_NAME = "org.amnezia.vpn"
const val LOG_FILE = "charon.log"
const val TAG = "amnezia_ikev2"
class IKEv2Thread(
val vpnServiceBuilder: android.net.VpnService.Builder,
val filesDirAbsolutePath: String
): Runnable {
private val mBuilderAdapter: BuilderAdapter = BuilderAdapter(vpnServiceBuilder)
private var mCurrentProfile: VpnProfile? = null
private var mNextProfile: VpnProfile? = null
@kotlin.jvm.Volatile
private var mCurrentCertificateAlias: String? = null
@kotlin.jvm.Volatile
private var mCurrentUserCertificateAlias: String? = null
@kotlin.jvm.Volatile
private var mProfileUpdated = false
@kotlin.jvm.Volatile
private var mTerminate = false
@kotlin.jvm.Volatile
private var mIsDisconnecting = false
private val mLogFile: String
private val mAppDir: String
init {
mLogFile = filesDirAbsolutePath + java.io.File.separator + LOG_FILE
mAppDir = filesDirAbsolutePath
}
fun setNextProfile(profile: VpnProfile) {
// TODO: take a look at "vpnprofileimportactivity" in starongswan repo
// to understand how to pass the profile object before starting of ikev2 tunnel
synchronized(this) {
mNextProfile = profile
mProfileUpdated = true
notifyAll()
}
}
override fun run() {
while (true) {
synchronized(this) {
try {
while (!mProfileUpdated) {
Log.i(TAG, "charon contunue")
continue
}
mProfileUpdated = false
stopCurrentConnection()
if (mNextProfile == null) {
setState(State.DISABLED)
if (mTerminate) {
return@synchronized
}
} else {
mCurrentProfile = mNextProfile
mNextProfile = null
val currentProfile = mCurrentProfile
/* store this in a separate (volatile) variable to avoid
* a possible deadlock during deinitialization */
mCurrentCertificateAlias = currentProfile!!.certificateAlias
mCurrentUserCertificateAlias = currentProfile!!.userCertificateAlias
startConnection(currentProfile)
mIsDisconnecting = false
SimpleFetcher.enable()
addNotification()
mBuilderAdapter.setProfile(currentProfile)
val flags: Int = currentProfile!!.flags
if (initializeCharon(
mBuilderAdapter,
mLogFile,
mAppDir,
currentProfile.vpnType!!.has(VpnTypeFeature.BYOD),
flags and VpnProfile.FLAGS_IPv6_TRANSPORT !== 0
)
) {
Log.i(TAG, "charon started")
if (currentProfile.vpnType!!.has(VpnTypeFeature.USER_PASS) &&
currentProfile.password == null
) { /* this can happen if Always-on VPN is enabled with an incomplete profile */
setError(ErrorState.PASSWORD_MISSING)
return@synchronized
}
val writer = SettingsWriter()
writer.setValue("global.language", java.util.Locale.getDefault().getLanguage())
writer.setValue("global.mtu", currentProfile.MTU)
writer.setValue("global.nat_keepalive", currentProfile.NATKeepAlive)
writer.setValue("global.rsa_pss", flags and VpnProfile.FLAGS_RSA_PSS !== 0)
writer.setValue("global.crl", flags and VpnProfile.FLAGS_DISABLE_CRL === 0)
writer.setValue("global.ocsp", flags and VpnProfile.FLAGS_DISABLE_OCSP === 0)
writer.setValue("connection.type", currentProfile.vpnType!!.identifier)
writer.setValue("connection.server", currentProfile.gateway)
writer.setValue("connection.port", currentProfile.port)
writer.setValue("connection.username", currentProfile.username)
writer.setValue("connection.password", currentProfile.password)
writer.setValue("connection.local_id", currentProfile.localId)
writer.setValue("connection.remote_id", currentProfile.remoteId)
writer.setValue("connection.certreq", flags and VpnProfile.FLAGS_SUPPRESS_CERT_REQS === 0)
writer.setValue("connection.strict_revocation", flags and VpnProfile.FLAGS_STRICT_REVOCATION !== 0)
writer.setValue("connection.ike_proposal", currentProfile.ikeProposal)
writer.setValue("connection.esp_proposal", currentProfile.espProposal)
initiate(writer.serialize())
} else {
Log.e(TAG, "failed to start charon")
setError(ErrorState.GENERIC_ERROR)
setState(State.DISABLED)
mCurrentProfile = null
}
}
} catch (ex: java.lang.InterruptedException) {
stopCurrentConnection()
setState(State.DISABLED)
}
}
}
}
/**
* Notify the state service about a new connection attempt.
* Called by the handler thread.
*
* @param profile currently active VPN profile
*/
private fun startConnection(profile: VpnProfile) {
// synchronized(mServiceLock) {
// if (mService != null) {
// mService.startConnection(profile)
// }
// }
}
/**
* Stop any existing connection by deinitializing charon.
*/
private fun stopCurrentConnection() {
synchronized(this) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mNextProfile?.let {
mBuilderAdapter.setProfile(it)
mBuilderAdapter.establishBlocking()
}
}
if (mCurrentProfile != null) {
setState(State.DISCONNECTING)
mIsDisconnecting = true
SimpleFetcher.disable()
deinitializeCharon()
Log.i(TAG, "charon stopped")
mCurrentProfile = null
if (mNextProfile == null) { /* only do this if we are not connecting to another profile */
removeNotification()
mBuilderAdapter.closeBlocking()
}
}
}
}
/**
* Update the current VPN state on the state service. Called by the handler
* thread and any of charon's threads.
*
* @param state current state
*/
private fun setState(state: State) {
// synchronized(mServiceLock) {
// if (mService != null) {
// mService.setState(state)
// }
// }
}
/**
* Initialization of charon, provided by libandroidbridge.so
*
* @param builder BuilderAdapter for this connection
* @param logfile absolute path to the logfile
* @param appdir absolute path to the data directory of the app
* @param byod enable BYOD features
* @param ipv6 enable IPv6 transport
* @return TRUE if initialization was successful
*/
external fun initializeCharon(
builder: BuilderAdapter?,
logfile: String?,
appdir: String?,
byod: Boolean,
ipv6: Boolean
): Boolean
/**
* Deinitialize charon, provided by libandroidbridge.so
*/
external fun deinitializeCharon()
/**
* Initiate VPN, provided by libandroidbridge.so
*/
external fun initiate(config: String?)
/**
* Adapter for VpnService.Builder which is used to access it safely via JNI.
* There is a corresponding C object to access it from native code.
*/
class BuilderAdapter(val builder: VpnService.Builder) {
private lateinit var mProfile: VpnProfile
private lateinit var mBuilder: VpnService.Builder
private lateinit var mCache: BuilderCache
private lateinit var mEstablishedCache: BuilderCache
private val mDropper: PacketDropper = PacketDropper()
init {
mBuilder = builder
}
@kotlin.jvm.Synchronized
fun setProfile(profile: VpnProfile) {
mProfile = profile
mBuilder = createBuilder(mProfile.name ?: "")
mCache = BuilderCache(mProfile)
}
private fun createBuilder(name: String): VpnService.Builder {
// val builder: VpnService.Builder = Builder()
mBuilder.setSession(name)
/* even though the option displayed in the system dialog says "Configure"
* we just use our main Activity */
// val context: Context = getApplicationContext()
// val intent = Intent(context, MainActivity::class.java)
// var flags: Int = PendingIntent.FLAG_UPDATE_CURRENT
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// flags = flags or PendingIntent.FLAG_IMMUTABLE
// }
// val pending: PendingIntent = PendingIntent.getActivity(context, 0, intent, flags)
// builder.setConfigureIntent(pending)
/* mark all VPN connections as unmetered (default changed for Android 10) */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
mBuilder.setMetered(false)
}
return mBuilder
}
@kotlin.jvm.Synchronized
fun addAddress(address: String?, prefixLength: Int): Boolean {
try {
mCache.addAddress(address, prefixLength)
} catch (ex: java.lang.IllegalArgumentException) {
return false
}
return true
}
@kotlin.jvm.Synchronized
fun addDnsServer(address: String?): Boolean {
try {
mCache.addDnsServer(address)
} catch (ex: java.lang.IllegalArgumentException) {
return false
}
return true
}
@kotlin.jvm.Synchronized
fun addRoute(address: String?, prefixLength: Int): Boolean {
try {
mCache.addRoute(address, prefixLength)
} catch (ex: java.lang.IllegalArgumentException) {
return false
}
return true
}
@kotlin.jvm.Synchronized
fun addSearchDomain(domain: String): Boolean {
try {
mBuilder.addSearchDomain(domain)
} catch (ex: java.lang.IllegalArgumentException) {
return false
}
return true
}
@kotlin.jvm.Synchronized
fun setMtu(mtu: Int): Boolean {
try {
mCache.setMtu(mtu)
} catch (ex: java.lang.IllegalArgumentException) {
return false
}
return true
}
@kotlin.jvm.Synchronized
private fun establishIntern(): ParcelFileDescriptor? {
val fd: ParcelFileDescriptor?
try {
mCache.applyData(mBuilder)
fd = mBuilder.establish()
if (fd != null) {
closeBlocking()
}
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
return null
}
if (fd == null) {
return null
}
/* now that the TUN device is created we don't need the current
* builder anymore, but we might need another when reestablishing */
mBuilder = createBuilder(mProfile.name ?: "")
mEstablishedCache = mCache
mCache = BuilderCache(mProfile)
return fd
}
@kotlin.jvm.Synchronized
fun establish(): Int {
val fd: ParcelFileDescriptor? = establishIntern()
return if (fd != null) fd.detachFd() else -1
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@kotlin.jvm.Synchronized
fun establishBlocking() {
/* just choose some arbitrary values to block all traffic (except for what's configured in the profile) */
mCache.addAddress("172.16.252.1", 32)
mCache.addAddress("fd00::fd02:1", 128)
mCache.addRoute("0.0.0.0", 0)
mCache.addRoute("::", 0)
/* set DNS servers to avoid DNS leak later */
mBuilder.addDnsServer("8.8.8.8")
mBuilder.addDnsServer("2001:4860:4860::8888")
/* use blocking mode to simplify packet dropping */
mBuilder.setBlocking(true)
val fd: ParcelFileDescriptor? = establishIntern()
if (fd != null) {
mDropper.start(fd)
}
}
@kotlin.jvm.Synchronized
fun closeBlocking() {
mDropper.stop()
}
@kotlin.jvm.Synchronized
fun establishNoDns(): Int {
val fd: ParcelFileDescriptor?
if (mEstablishedCache == null) {
return -1
}
fd = try {
val builder: VpnService.Builder = createBuilder(mProfile.name ?: "")
mEstablishedCache.applyData(builder)
builder.establish()
} catch (ex: java.lang.Exception) {
ex.printStackTrace()
return -1
}
return if (fd == null) {
-1
} else fd.detachFd()
}
private inner class PacketDropper : java.lang.Runnable {
private var mFd: ParcelFileDescriptor? = null
private lateinit var mThread: java.lang.Thread
fun start(fd: ParcelFileDescriptor) {
mFd = fd
mThread = java.lang.Thread(this)
mThread.start()
}
fun stop() {
if (mFd != null) {
try {
mThread.interrupt()
mThread.join()
mFd?.close()
} catch (e: java.lang.InterruptedException) {
e.printStackTrace()
} catch (e: java.io.IOException) {
e.printStackTrace()
}
mFd = null
}
}
@kotlin.jvm.Synchronized
override fun run() {
try {
val plain: java.io.FileInputStream = java.io.FileInputStream(mFd?.getFileDescriptor())
val packet: java.nio.ByteBuffer = java.nio.ByteBuffer.allocate(mCache.mMtu)
while (true) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { /* just read and ignore all data, regular read() is not interruptible */
val len: Int = plain.getChannel().read(packet)
packet.clear()
if (len < 0) {
break
}
} else { /* this is rather ugly but on older platforms not even the NIO version of read() is interruptible */
var wait = true
if (plain.available() > 0) {
val len: Int = plain.read(packet.array())
packet.clear()
if (len < 0 || java.lang.Thread.interrupted()) {
break
}
/* check again right away, there may be another packet */wait = false
}
if (wait) {
java.lang.Thread.sleep(250)
}
}
}
} catch (e: java.nio.channels.ClosedByInterruptException) {
/* regular interruption */
} catch (e: java.lang.InterruptedException) {
} catch (e: java.io.IOException) {
e.printStackTrace()
}
}
}
}
/**
* Cache non DNS related information so we can recreate the builder without
* that information when reestablishing IKE_SAs
*/
class BuilderCache(profile: VpnProfile) {
val mAddresses: MutableList<IPRange> = java.util.ArrayList<IPRange>()
val mRoutesIPv4: MutableList<IPRange> = java.util.ArrayList<IPRange>()
val mRoutesIPv6: MutableList<IPRange> = java.util.ArrayList<IPRange>()
val mIncludedSubnetsv4: IPRangeSet = IPRangeSet()
val mIncludedSubnetsv6: IPRangeSet = IPRangeSet()
val mExcludedSubnets: IPRangeSet
val mSplitTunneling: Int
val mAppHandling: SelectedAppsHandling
val mSelectedApps: java.util.SortedSet<String>
val mDnsServers: MutableList<java.net.InetAddress> = java.util.ArrayList<java.net.InetAddress>()
var mMtu: Int
var mIPv4Seen = false
var mIPv6Seen = false
var mDnsServersConfigured = false
init {
val included: IPRangeSet = IPRangeSet.fromString(profile?.includedSubnets)
for (range in included) {
if (range.getFrom() is java.net.Inet4Address) {
mIncludedSubnetsv4.add(range)
} else if (range.getFrom() is java.net.Inet6Address) {
mIncludedSubnetsv6.add(range)
}
}
mExcludedSubnets = IPRangeSet.fromString(profile.excludedSubnets ?: "")
val splitTunneling: Int? = profile.splitTunneling
mSplitTunneling = splitTunneling ?: 0
var appHandling: SelectedAppsHandling = profile.selectedAppsHandling
mSelectedApps = profile.selectedAppsSet
when (appHandling) {
SelectedAppsHandling.SELECTED_APPS_DISABLE -> {
appHandling = SelectedAppsHandling.SELECTED_APPS_EXCLUDE
mSelectedApps.clear()
mSelectedApps.add(PACKAGE_NAME)
}
SelectedAppsHandling.SELECTED_APPS_EXCLUDE -> {
mSelectedApps.add(PACKAGE_NAME)
}
SelectedAppsHandling.SELECTED_APPS_ONLY -> {
mSelectedApps.remove(PACKAGE_NAME)
}
}
mAppHandling = appHandling
val dnsServers = profile.dnsServers
if (dnsServers != null) {
for (server in dnsServers.split("\\s+")) {
try {
mDnsServers.add(Utils.parseInetAddress(server))
recordAddressFamily(server)
mDnsServersConfigured = true
} catch (e: java.net.UnknownHostException) {
e.printStackTrace()
}
}
}
/* set a default MTU, will be set by the daemon for regular interfaces */
val mtu: Int? = profile.MTU
mMtu = mtu ?: Constants.MTU_MAX
}
fun addAddress(address: String?, prefixLength: Int) {
try {
mAddresses.add(IPRange(address, prefixLength))
recordAddressFamily(address)
} catch (ex: java.net.UnknownHostException) {
ex.printStackTrace()
}
}
fun addDnsServer(address: String?) {
/* ignore received DNS servers if any were configured */
if (mDnsServersConfigured) {
return
}
try {
mDnsServers.add(Utils.parseInetAddress(address))
recordAddressFamily(address)
} catch (e: java.net.UnknownHostException) {
e.printStackTrace()
}
}
fun addRoute(address: String?, prefixLength: Int) {
try {
if (isIPv6(address)) {
mRoutesIPv6.add(IPRange(address, prefixLength))
} else {
mRoutesIPv4.add(IPRange(address, prefixLength))
}
} catch (ex: java.net.UnknownHostException) {
ex.printStackTrace()
}
}
fun setMtu(mtu: Int) {
mMtu = mtu
}
fun recordAddressFamily(address: String?) {
try {
if (isIPv6(address)) {
mIPv6Seen = true
} else {
mIPv4Seen = true
}
} catch (ex: java.net.UnknownHostException) {
ex.printStackTrace()
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun applyData(builder: VpnService.Builder) {
for (address in mAddresses) {
builder.addAddress(address.getFrom(), address.getPrefix())
}
for (server in mDnsServers) {
builder.addDnsServer(server)
}
/* add routes depending on whether split tunneling is allowed or not,
* that is, whether we have to handle and block non-VPN traffic */
if (mSplitTunneling and VpnProfile.SPLIT_TUNNELING_BLOCK_IPV4 === 0) {
if (mIPv4Seen) { /* split tunneling is used depending on the routes and configuration */
val ranges = IPRangeSet()
if (mIncludedSubnetsv4.size() > 0) {
ranges.add(mIncludedSubnetsv4)
} else {
ranges.addAll(mRoutesIPv4)
}
ranges.remove(mExcludedSubnets)
for (subnet in ranges.subnets()) {
try {
builder.addRoute(subnet.getFrom(), subnet.getPrefix())
} catch (e: java.lang.IllegalArgumentException) { /* some Android versions don't seem to like multicast addresses here,
* ignore it for now */
if (!subnet.getFrom().isMulticastAddress()) {
throw e
}
}
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { /* allow traffic that would otherwise be blocked to bypass the VPN */
builder.allowFamily(OsConstants.AF_INET)
}
} else if (mIPv4Seen) { /* only needed if we've seen any addresses. otherwise, traffic
* is blocked by default (we also install no routes in that case) */
builder.addRoute("0.0.0.0", 0)
}
/* same thing for IPv6 */
if (mSplitTunneling and VpnProfile.SPLIT_TUNNELING_BLOCK_IPV6 === 0) {
if (mIPv6Seen) {
val ranges = IPRangeSet()
if (mIncludedSubnetsv6.size() > 0) {
ranges.add(mIncludedSubnetsv6)
} else {
ranges.addAll(mRoutesIPv6)
}
ranges.remove(mExcludedSubnets)
for (subnet in ranges.subnets()) {
try {
builder.addRoute(subnet.getFrom(), subnet.getPrefix())
} catch (e: java.lang.IllegalArgumentException) {
if (!subnet.getFrom().isMulticastAddress()) {
throw e
}
}
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.allowFamily(OsConstants.AF_INET6)
}
} else if (mIPv6Seen) {
builder.addRoute("::", 0)
}
/* apply selected applications */
if (mSelectedApps.size > 0 &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
) {
when (mAppHandling) {
SelectedAppsHandling.SELECTED_APPS_EXCLUDE -> for (app in mSelectedApps) {
try {
builder.addDisallowedApplication(app)
} catch (e: PackageManager.NameNotFoundException) {
// possible if not configured via GUI or app was uninstalled
}
}
SelectedAppsHandling.SELECTED_APPS_ONLY -> for (app in mSelectedApps) {
try {
builder.addAllowedApplication(app)
} catch (e: PackageManager.NameNotFoundException) {
// possible if not configured via GUI or app was uninstalled
}
}
else -> {}
}
}
builder.setMtu(mMtu)
}
@kotlin.Throws(java.net.UnknownHostException::class)
private fun isIPv6(address: String?): Boolean {
val addr: java.net.InetAddress = Utils.parseInetAddress(address)
if (addr is java.net.Inet4Address) {
return false
} else if (addr is java.net.Inet6Address) {
return true
}
return false
}
}
/**
* Function called via JNI to determine information about the Android version.
*/
private fun getAndroidVersion(): String? {
var version = "Android " + Build.VERSION.RELEASE + " - " + Build.DISPLAY
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
version += "/" + Build.VERSION.SECURITY_PATCH
}
return version
}
/**
* Function called via JNI to determine information about the device.
*/
private fun getDeviceString(): String? {
return ((Build.MODEL + " - " + Build.BRAND).toString() + "/" + Build.PRODUCT).toString() + "/" + Build.MANUFACTURER
}
/**
* Add a permanent notification while we are connected to avoid the service getting killed by
* the system when low on memory.
*/
private fun addNotification() {
// mHandler.post(object : java.lang.Runnable {
// fun run() {
// mShowNotification = true
// startForeground(
// org.strongswan.android.logic.CharonVpnService.VPN_STATE_NOTIFICATION_ID,
// buildNotification(false)
// )
// }
// })
}
/**
* Remove the permanent notification.
*/
private fun removeNotification() {
// mHandler.post(object : java.lang.Runnable {
// fun run() {
// mShowNotification = false
// stopForeground(true)
// }
// })
}
/**
* Set an error on the state service. Called by the handler thread and any
* of charon's threads.
*
* @param error error state
*/
private fun setError(error: ErrorState) {
// synchronized(mServiceLock) {
// if (mService != null) {
// mService.setError(error)
// }
// }
}
enum class State {
DISABLED, CONNECTING, CONNECTED, DISCONNECTING
}
enum class ErrorState {
NO_ERROR, AUTH_FAILED, PEER_AUTH_FAILED, LOOKUP_FAILED, UNREACHABLE, GENERIC_ERROR, PASSWORD_MISSING, CERTIFICATE_UNAVAILABLE
}
}
@@ -150,6 +150,8 @@ class VPNService : BaseVpnService(), LocalDnsService.Interface {
private var mOpenVPNThreadv3: OpenVPNThreadv3? = null
var currentTunnelHandle = -1
private var ikev2VpnThread: IKEv2Thread? = null
private var intent: Intent? = null
private var flags = 0
private var startId = 0
@@ -165,6 +167,7 @@ class VPNService : BaseVpnService(), LocalDnsService.Interface {
Log.e(tag, "Wireguard Version ${wgVersion()}")
mOpenVPNThreadv3 = OpenVPNThreadv3(this)
mAlreadyInitialised = true
ikev2VpnThread = IKEv2Thread(mbuilder, getFilesDir().getAbsolutePath())
}
override fun onCreate() {
@@ -384,8 +387,11 @@ class VPNService : BaseVpnService(), LocalDnsService.Interface {
startShadowsocks()
startTest()
}
"ikev2" -> {
startIPSEC()
}
else -> {
Log.e(tag, "No protocol")
Log.e(tag, "Unknown protocol ($mProtocol)")
return 0
}
}
@@ -393,9 +399,22 @@ class VPNService : BaseVpnService(), LocalDnsService.Interface {
return 1
}
private fun startIPSEC() {
Log.v(tag, "start ipsec")
ikev2VpnThread = IKEv2Thread(mbuilder, getFilesDir().getAbsolutePath())
// TODO: pass the "vpnprofile" instance as a parameter
// ikev2VpnThread.setNextProfile()
Thread({
ikev2VpnThread?.run()
}).start()
}
fun establish(): ParcelFileDescriptor? {
Log.v(tag, "Aman: establish....................")
mbuilder.allowFamily(OsConstants.AF_INET)
mbuilder.allowFamily(OsConstants.AF_INET6)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) mbuilder.setMetered(false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) setUnderlyingNetworks(null)
@@ -0,0 +1,111 @@
package org.amnezia.vpn.ikev2
import android.text.TextUtils
class VpnProfile : kotlin.Cloneable {
var name: String? = null
var gateway: String? = null
var username: String? = null
var password: String? = null
var certificateAlias: String? = null
var userCertificateAlias: String? = null
var remoteId: String? = null
var localId: String? = null
var excludedSubnets: String? = null
var includedSubnets: String? = null
var selectedApps: String? = null
var ikeProposal: String? = null
var espProposal: String? = null
var dnsServers: String? = null
var MTU: Int? = null
var port: Int? = null
var splitTunneling: Int? = null
var NATKeepAlive: Int? = null
private var mFlags: Int? = null
var selectedAppsHandling = SelectedAppsHandling.SELECTED_APPS_DISABLE
private var mVpnType: VpnType? = null
private var mUUID: java.util.UUID?
var id: Long = -1
enum class SelectedAppsHandling(val value: Int) {
SELECTED_APPS_DISABLE(0), SELECTED_APPS_EXCLUDE(1), SELECTED_APPS_ONLY(2);
}
init {
mUUID = java.util.UUID.randomUUID()
}
var uUID: java.util.UUID?
get() = mUUID
set(uuid) {
mUUID = uuid
}
var vpnType: VpnType?
get() = mVpnType
set(type) {
mVpnType = type
}
fun setSelectedApps(selectedApps: java.util.SortedSet<String?>) {
this.selectedApps = if (selectedApps.size > 0) TextUtils.join(" ", selectedApps) else null
}
val selectedAppsSet: java.util.SortedSet<String>
get() {
val set: java.util.TreeSet<String> = java.util.TreeSet<String>()
if (!TextUtils.isEmpty(selectedApps)) {
set.addAll(
java.util.Arrays.asList<String>(
*selectedApps!!.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }
.toTypedArray()))
}
return set
}
fun setSelectedAppsHandling(value: Int) {
selectedAppsHandling = SelectedAppsHandling.SELECTED_APPS_DISABLE
for (handling in VpnProfile.SelectedAppsHandling.values()) {
if (handling.value == value) {
selectedAppsHandling = handling
break
}
}
}
var flags: Int = 0
override fun toString(): String {
return name!!
}
override fun equals(o: Any?): Boolean {
if (o != null && o is VpnProfile) {
val other = o
return if (mUUID != null && other.uUID != null) {
mUUID == other.uUID
} else id == other.id
}
return false
}
override fun clone(): VpnProfile {
return try {
super.clone() as VpnProfile
} catch (e: java.lang.CloneNotSupportedException) {
throw java.lang.AssertionError()
}
}
companion object {
/* While storing this as EnumSet would be nicer this simplifies storing it in a database */
const val SPLIT_TUNNELING_BLOCK_IPV4 = 1
const val SPLIT_TUNNELING_BLOCK_IPV6 = 2
const val FLAGS_SUPPRESS_CERT_REQS = 1 shl 0
const val FLAGS_DISABLE_CRL = 1 shl 1
const val FLAGS_DISABLE_OCSP = 1 shl 2
const val FLAGS_STRICT_REVOCATION = 1 shl 3
const val FLAGS_RSA_PSS = 1 shl 4
const val FLAGS_IPv6_TRANSPORT = 1 shl 5
}
}
@@ -0,0 +1,79 @@
package org.amnezia.vpn.ikev2
enum class VpnType(
/**
* The identifier used to store this value in the database
* @return identifier
*/
val identifier: String, features: java.util.EnumSet<VpnTypeFeature>
) {
/* the order here must match the items in R.array.vpn_types */
IKEV2_EAP("ikev2-eap", java.util.EnumSet.of(VpnTypeFeature.USER_PASS)), IKEV2_CERT(
"ikev2-cert", java.util.EnumSet.of(
VpnTypeFeature.CERTIFICATE
)
),
IKEV2_CERT_EAP(
"ikev2-cert-eap",
java.util.EnumSet.of(VpnTypeFeature.USER_PASS, VpnTypeFeature.CERTIFICATE)
),
IKEV2_EAP_TLS(
"ikev2-eap-tls", java.util.EnumSet.of(
VpnTypeFeature.CERTIFICATE
)
),
IKEV2_BYOD_EAP("ikev2-byod-eap", java.util.EnumSet.of(VpnTypeFeature.USER_PASS, VpnTypeFeature.BYOD));
/**
* Features of a VPN type.
*/
enum class VpnTypeFeature {
/** client certificate is required */
CERTIFICATE,
/** username and password are required */
USER_PASS,
/** enable BYOD features */
BYOD
}
private val mFeatures: java.util.EnumSet<VpnTypeFeature>
/**
* Enum which provides additional information about the supported VPN types.
*
* @param id identifier used to store and transmit this specific type
* @param features of the given VPN type
* @param certificate true if a client certificate is required
*/
init {
mFeatures = features
}
/**
* Checks whether a feature is supported/required by this type of VPN.
*
* @return true if the feature is supported/required
*/
fun has(feature: VpnTypeFeature?): Boolean {
return mFeatures.contains(feature)
}
companion object {
/**
* Get the enum entry with the given identifier.
*
* @param identifier get the enum entry with this identifier
* @return the enum entry, or the default if not found
*/
fun fromIdentifier(identifier: String): VpnType {
for (type in VpnType.values()) {
if (identifier == type.identifier) {
return type
}
}
return IKEV2_EAP
}
}
}
@@ -0,0 +1,272 @@
/*
* Copyright (C) 2013 Tobias Brunner
*
* Copyright (C) secunet Security Networks AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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.
*/
package org.amnezia.vpn.ikev2.utils;
import java.nio.ByteBuffer;
/**
* Very similar to ByteBuffer (although with a stripped interface) but it
* automatically resizes the underlying buffer.
*/
public class BufferedByteWriter
{
/**
* The underlying byte buffer
*/
private byte[] mBuffer;
/**
* ByteBuffer used as wrapper around the buffer to easily convert values
*/
private ByteBuffer mWriter;
/**
* Create a writer with a default initial capacity
*/
public BufferedByteWriter()
{
this(0);
}
/**
* Create a writer with the given initial capacity (helps avoid expensive
* resizing if known).
* @param capacity initial capacity
*/
public BufferedByteWriter(int capacity)
{
capacity = capacity > 4 ? capacity : 32;
mBuffer = new byte[capacity];
mWriter = ByteBuffer.wrap(mBuffer);
}
/**
* Ensure that there is enough space available to write the requested
* number of bytes. If necessary the internal buffer is resized.
* @param required required number of bytes
*/
private void ensureCapacity(int required)
{
if (mWriter.remaining() >= required)
{
return;
}
byte[] buffer = new byte[(mBuffer.length + required) * 2];
System.arraycopy(mBuffer, 0, buffer, 0, mWriter.position());
mBuffer = buffer;
ByteBuffer writer = ByteBuffer.wrap(buffer);
writer.position(mWriter.position());
mWriter = writer;
}
/**
* Write the given byte array to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put(byte[] value)
{
ensureCapacity(value.length);
mWriter.put(value);
return this;
}
/**
* Write the given byte to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put(byte value)
{
ensureCapacity(1);
mWriter.put(value);
return this;
}
/**
* Write the 8-bit length of the given data followed by the data itself
* @param value
* @return the writer
*/
public BufferedByteWriter putLen8(byte[] value)
{
ensureCapacity(1 + value.length);
mWriter.put((byte)value.length);
mWriter.put(value);
return this;
}
/**
* Write the 16-bit length of the given data followed by the data itself
* @param value
* @return the writer
*/
public BufferedByteWriter putLen16(byte[] value)
{
ensureCapacity(2 + value.length);
mWriter.putShort((short)value.length);
mWriter.put(value);
return this;
}
/**
* Write the given short value (16-bit) in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put16(byte value)
{
return this.put16((short)(value & 0xFF));
}
/**
* Write the given short value (16-bit) in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put16(short value)
{
ensureCapacity(2);
mWriter.putShort(value);
return this;
}
/**
* Write 24-bit of the given value in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put24(byte value)
{
ensureCapacity(3);
mWriter.putShort((short)0);
mWriter.put(value);
return this;
}
/**
* Write 24-bit of the given value in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put24(short value)
{
ensureCapacity(3);
mWriter.put((byte)0);
mWriter.putShort(value);
return this;
}
/**
* Write 24-bit of the given value in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put24(int value)
{
ensureCapacity(3);
mWriter.put((byte)(value >> 16));
mWriter.putShort((short)value);
return this;
}
/**
* Write the given int value (32-bit) in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put32(byte value)
{
return put32(value & 0xFF);
}
/**
* Write the given int value (32-bit) in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put32(short value)
{
return put32(value & 0xFFFF);
}
/**
* Write the given int value (32-bit) in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put32(int value)
{
ensureCapacity(4);
mWriter.putInt(value);
return this;
}
/**
* Write the given long value (64-bit) in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put64(byte value)
{
return put64(value & 0xFFL);
}
/**
* Write the given long value (64-bit) in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put64(short value)
{
return put64(value & 0xFFFFL);
}
/**
* Write the given long value (64-bit) in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put64(int value)
{
return put64(value & 0xFFFFFFFFL);
}
/**
* Write the given long value (64-bit) in big-endian order to the buffer
* @param value
* @return the writer
*/
public BufferedByteWriter put64(long value)
{
ensureCapacity(8);
mWriter.putLong(value);
return this;
}
/**
* Convert the internal buffer to a new byte array.
* @return byte array
*/
public byte[] toByteArray()
{
int length = mWriter.position();
byte[] bytes = new byte[length];
System.arraycopy(mBuffer, 0, bytes, 0, length);
return bytes;
}
}
@@ -0,0 +1,67 @@
/*
* Copyright (C) 2016-2020 Tobias Brunner
*
* Copyright (C) secunet Security Networks AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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.
*/
package org.amnezia.vpn.ikev2.utils;
public final class Constants
{
/**
* Intent action used to notify about changes to the VPN profiles
*/
public static final String VPN_PROFILES_CHANGED = "org.strongswan.android.VPN_PROFILES_CHANGED";
/**
* Used in the intent above to notify about edits or inserts of a VPN profile (long)
*/
public static final String VPN_PROFILES_SINGLE = "org.strongswan.android.VPN_PROFILES_SINGLE";
/**
* Used in the intent above to notify about the deletion of multiple VPN profiles (array of longs)
*/
public static final String VPN_PROFILES_MULTIPLE = "org.strongswan.android.VPN_PROFILES_MULTIPLE";
/**
* Limits for MTU
*/
public static final int MTU_MAX = 1500;
public static final int MTU_MIN = 1280;
/**
* Limits for NAT-T keepalive
*/
public static final int NAT_KEEPALIVE_MAX = 120;
public static final int NAT_KEEPALIVE_MIN = 10;
/**
* Preference key for default VPN profile
*/
public static final String PREF_DEFAULT_VPN_PROFILE = "pref_default_vpn_profile";
/**
* Value used to signify that the most recently used profile should be used as default
*/
public static final String PREF_DEFAULT_VPN_PROFILE_MRU = "pref_default_vpn_profile_mru";
/**
* Preference key to store the most recently used VPN profile
*/
public static final String PREF_MRU_VPN_PROFILE = "pref_mru_vpn_profile";
/**
* Preference key to store whether the user permanently dismissed our warning to add the app to the power whitelist
*/
public static final String PREF_IGNORE_POWER_WHITELIST = "pref_ignore_power_whitelist";
}
@@ -0,0 +1,510 @@
/*
* Copyright (C) 2012-2017 Tobias Brunner
*
* Copyright (C) secunet Security Networks AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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.
*/
package org.amnezia.vpn.ikev2.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import androidx.annotation.NonNull;
/**
* Class that represents a range of IP addresses. This range could be a proper subnet, but that's
* not necessarily the case (see {@code getPrefix} and {@code toSubnets}).
*/
public class IPRange implements Comparable<IPRange>
{
private final byte[] mBitmask = { (byte)0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
private byte[] mFrom;
private byte[] mTo;
private Integer mPrefix;
/**
* Determine if the range is a proper subnet and, if so, what the network prefix is.
*/
private void determinePrefix()
{
boolean matching = true;
mPrefix = mFrom.length * 8;
for (int i = 0; i < mFrom.length; i++)
{
for (int bit = 0; bit < 8; bit++)
{
if (matching)
{
if ((mFrom[i] & mBitmask[bit]) != (mTo[i] & mBitmask[bit]))
{
mPrefix = (i * 8) + bit;
matching = false;
}
}
else
{
if ((mFrom[i] & mBitmask[bit]) != 0 || (mTo[i] & mBitmask[bit]) == 0)
{
mPrefix = null;
return;
}
}
}
}
}
private IPRange(byte[] from, byte[] to)
{
mFrom = from;
mTo = to;
determinePrefix();
}
public IPRange(String from, String to) throws UnknownHostException
{
this(Utils.parseInetAddress(from), Utils.parseInetAddress(to));
}
public IPRange(InetAddress from, InetAddress to)
{
initializeFromRange(from, to);
}
private void initializeFromRange(InetAddress from, InetAddress to)
{
byte[] fa = from.getAddress(), ta = to.getAddress();
if (fa.length != ta.length)
{
throw new IllegalArgumentException("Invalid range");
}
if (compareAddr(fa, ta) < 0)
{
mFrom = fa;
mTo = ta;
}
else
{
mTo = fa;
mFrom = ta;
}
determinePrefix();
}
public IPRange(String base, int prefix) throws UnknownHostException
{
this(Utils.parseInetAddress(base), prefix);
}
public IPRange(InetAddress base, int prefix)
{
this(base.getAddress(), prefix);
}
private IPRange(byte[] from, int prefix)
{
initializeFromCIDR(from, prefix);
}
private void initializeFromCIDR(byte[] from, int prefix)
{
if (from.length != 4 && from.length != 16)
{
throw new IllegalArgumentException("Invalid address");
}
if (prefix < 0 || prefix > from.length * 8)
{
throw new IllegalArgumentException("Invalid prefix");
}
byte[] to = from.clone();
byte mask = (byte)(0xff << (8 - prefix % 8));
int i = prefix / 8;
if (i < from.length)
{
from[i] = (byte)(from[i] & mask);
to[i] = (byte)(to[i] | ~mask);
Arrays.fill(from, i+1, from.length, (byte)0);
Arrays.fill(to, i+1, to.length, (byte)0xff);
}
mFrom = from;
mTo = to;
mPrefix = prefix;
}
public IPRange(String cidr) throws UnknownHostException
{
/* only verify the basic structure */
if (!cidr.matches("(?i)^(([0-9.]+)|([0-9a-f:]+))(-(([0-9.]+)|([0-9a-f:]+))|(/\\d+))?$"))
{
throw new IllegalArgumentException("Invalid CIDR or range notation");
}
if (cidr.contains("-"))
{
String[] parts = cidr.split("-");
InetAddress from = InetAddress.getByName(parts[0]);
InetAddress to = InetAddress.getByName(parts[1]);
initializeFromRange(from, to);
}
else
{
String[] parts = cidr.split("/");
InetAddress addr = InetAddress.getByName(parts[0]);
byte[] base = addr.getAddress();
int prefix = base.length * 8;
if (parts.length > 1)
{
prefix = Integer.parseInt(parts[1]);
}
initializeFromCIDR(base, prefix);
}
}
/**
* Returns the first address of the range. The network ID in case this is a proper subnet.
*/
public InetAddress getFrom()
{
try
{
return InetAddress.getByAddress(mFrom);
}
catch (UnknownHostException ignored)
{
return null;
}
}
/**
* Returns the last address of the range.
*/
public InetAddress getTo()
{
try
{
return InetAddress.getByAddress(mTo);
}
catch (UnknownHostException ignored)
{
return null;
}
}
/**
* If this range is a proper subnet returns its prefix, otherwise returns null.
*/
public Integer getPrefix()
{
return mPrefix;
}
@Override
public int compareTo(@NonNull IPRange other)
{
int cmp = compareAddr(mFrom, other.mFrom);
if (cmp == 0)
{ /* smaller ranges first */
cmp = compareAddr(mTo, other.mTo);
}
return cmp;
}
@Override
public boolean equals(Object o)
{
if (o == null || !(o instanceof IPRange))
{
return false;
}
return this == o || compareTo((IPRange)o) == 0;
}
@Override
public String toString()
{
try
{
if (mPrefix != null)
{
return InetAddress.getByAddress(mFrom).getHostAddress() + "/" + mPrefix;
}
return InetAddress.getByAddress(mFrom).getHostAddress() + "-" +
InetAddress.getByAddress(mTo).getHostAddress();
}
catch (UnknownHostException ignored)
{
return super.toString();
}
}
private int compareAddr(byte a[], byte b[])
{
if (a.length != b.length)
{
return (a.length < b.length) ? -1 : 1;
}
for (int i = 0; i < a.length; i++)
{
if (a[i] != b[i])
{
if (((int)a[i] & 0xff) < ((int)b[i] & 0xff))
{
return -1;
}
else
{
return 1;
}
}
}
return 0;
}
/**
* Check if this range fully contains the given range.
*/
public boolean contains(IPRange range)
{
return compareAddr(mFrom, range.mFrom) <= 0 && compareAddr(range.mTo, mTo) <= 0;
}
/**
* Check if this and the given range overlap.
*/
public boolean overlaps(IPRange range)
{
return !(compareAddr(mTo, range.mFrom) < 0 || compareAddr(range.mTo, mFrom) < 0);
}
private byte[] dec(byte[] addr)
{
for (int i = addr.length - 1; i >= 0; i--)
{
if (--addr[i] != (byte)0xff)
{
break;
}
}
return addr;
}
private byte[] inc(byte[] addr)
{
for (int i = addr.length - 1; i >= 0; i--)
{
if (++addr[i] != 0)
{
break;
}
}
return addr;
}
/**
* Remove the given range from the current range. Returns a list of resulting ranges (these are
* not proper subnets). At most two ranges are returned, in case the given range is contained in
* this but does not equal it, which would result in an empty list (which is also the case if
* this range is fully contained in the given range).
*/
public List<IPRange> remove(IPRange range)
{
ArrayList<IPRange> list = new ArrayList<>();
if (!overlaps(range))
{ /* | this | or | this |
* | range | | range | */
list.add(this);
}
else if (!range.contains(this))
{ /* we are not completely removed, so none of these cases applies:
* | this | or | this | or | this |
* | range | | range | | range | */
if (compareAddr(mFrom, range.mFrom) < 0 && compareAddr(range.mTo, mTo) < 0)
{ /* the removed range is completely within our boundaries:
* | this |
* | range | */
list.add(new IPRange(mFrom, dec(range.mFrom.clone())));
list.add(new IPRange(inc(range.mTo.clone()), mTo));
}
else
{ /* one end is within our boundaries the other at or outside it:
* | this | or | this | or | this | or | this |
* | range | | range | | range | | range | */
byte[] from = compareAddr(mFrom, range.mFrom) < 0 ? mFrom : inc(range.mTo.clone());
byte[] to = compareAddr(mTo, range.mTo) > 0 ? mTo : dec(range.mFrom.clone());
list.add(new IPRange(from, to));
}
}
return list;
}
private boolean adjacent(IPRange range)
{
if (compareAddr(mTo, range.mFrom) < 0)
{
byte[] to = inc(mTo.clone());
return compareAddr(to, range.mFrom) == 0;
}
byte[] from = dec(mFrom.clone());
return compareAddr(from, range.mTo) == 0;
}
/**
* Merge two adjacent or overlapping ranges, returns null if it's not possible to merge them.
*/
public IPRange merge(IPRange range)
{
if (overlaps(range))
{
if (contains(range))
{
return this;
}
else if (range.contains(this))
{
return range;
}
}
else if (!adjacent(range))
{
return null;
}
byte[] from = compareAddr(mFrom, range.mFrom) < 0 ? mFrom : range.mFrom;
byte[] to = compareAddr(mTo, range.mTo) > 0 ? mTo : range.mTo;
return new IPRange(from, to);
}
/**
* Split the given range into a sorted list of proper subnets.
*/
public List<IPRange> toSubnets()
{
ArrayList<IPRange> list = new ArrayList<>();
if (mPrefix != null)
{
list.add(this);
}
else
{
int i = 0, bit = 0, prefix, netmask, common_byte, common_bit;
int from_cur, from_prev = 0, to_cur, to_prev = 1;
boolean from_full = true, to_full = true;
byte[] from = mFrom.clone();
byte[] to = mTo.clone();
/* find a common prefix */
while (i < from.length && (from[i] & mBitmask[bit]) == (to[i] & mBitmask[bit]))
{
if (++bit == 8)
{
bit = 0;
i++;
}
}
prefix = i * 8 + bit;
/* at this point we know that the addresses are either equal, or that the
* current bits in the 'from' and 'to' addresses are 0 and 1, respectively.
* we now look at the rest of the bits as two binary trees (0=left, 1=right)
* where 'from' and 'to' are both leaf nodes. all leaf nodes between these
* nodes are addresses contained in the range. to collect them as subnets
* we follow the trees from both leaf nodes to their root node and record
* all complete subtrees (right for from, left for to) we come across as
* subnets. in that process host bits are zeroed out. if both addresses
* are equal we won't enter the loop below.
* 0_____|_____1 for the 'from' address we assume we start on a
* 0__|__ 1 0__|__1 left subtree (0) and follow the left edges until
* _|_ _|_ _|_ _|_ we reach the root of this subtree, which is
* | | | | | | | | either the root of this whole 'from'-subtree
* 0 1 0 1 0 1 0 1 (causing us to leave the loop) or the root node
* of the right subtree (1) of another node (which actually could be the
* leaf node we start from). that whole subtree gets recorded as subnet.
* next we follow the right edges to the root of that subtree which again is
* either the 'from'-root or the root node in the left subtree (0) of
* another node. the complete right subtree of that node is the next subnet
* we record. from there we assume that we are in that right subtree and
* recursively follow right edges to its root. for the 'to' address the
* procedure is exactly the same but with left and right reversed.
*/
if (++bit == 8)
{
bit = 0;
i++;
}
common_byte = i;
common_bit = bit;
netmask = from.length * 8;
for (i = from.length - 1; i >= common_byte; i--)
{
int bit_min = (i == common_byte) ? common_bit : 0;
for (bit = 7; bit >= bit_min; bit--)
{
byte mask = mBitmask[bit];
from_cur = from[i] & mask;
if (from_prev == 0 && from_cur != 0)
{ /* 0 -> 1: subnet is the whole current (right) subtree */
list.add(new IPRange(from.clone(), netmask));
from_full = false;
}
else if (from_prev != 0 && from_cur == 0)
{ /* 1 -> 0: invert bit to switch to right subtree and add it */
from[i] ^= mask;
list.add(new IPRange(from.clone(), netmask));
from_cur = 1;
}
/* clear the current bit */
from[i] &= ~mask;
from_prev = from_cur;
to_cur = to[i] & mask;
if (to_prev != 0 && to_cur == 0)
{ /* 1 -> 0: subnet is the whole current (left) subtree */
list.add(new IPRange(to.clone(), netmask));
to_full = false;
}
else if (to_prev == 0 && to_cur != 0)
{ /* 0 -> 1: invert bit to switch to left subtree and add it */
to[i] ^= mask;
list.add(new IPRange(to.clone(), netmask));
to_cur = 0;
}
/* clear the current bit */
to[i] &= ~mask;
to_prev = to_cur;
netmask--;
}
}
if (from_full && to_full)
{ /* full subnet (from=to or from=0.. and to=1.. after common prefix) - not reachable
* due to the shortcut at the top */
list.add(new IPRange(from.clone(), prefix));
}
else if (from_full)
{ /* full from subnet (from=0.. after prefix) */
list.add(new IPRange(from.clone(), prefix + 1));
}
else if (to_full)
{ /* full to subnet (to=1.. after prefix) */
list.add(new IPRange(to.clone(), prefix + 1));
}
}
Collections.sort(list);
return list;
}
}
@@ -0,0 +1,224 @@
/*
* Copyright (C) 2012-2017 Tobias Brunner
*
* Copyright (C) secunet Security Networks AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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.
*/
package org.amnezia.vpn.ikev2.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
/**
* Class that represents a set of IP address ranges (not necessarily proper subnets) and allows
* modifying the set and enumerating the resulting subnets.
*/
public class IPRangeSet implements Iterable<IPRange>
{
private TreeSet<IPRange> mRanges = new TreeSet<>();
/**
* Parse the given string (space separated ranges in CIDR or range notation) and return the
* resulting set or {@code null} if the string was invalid. An empty set is returned if the given string
* is {@code null}.
*/
public static IPRangeSet fromString(String ranges)
{
IPRangeSet set = new IPRangeSet();
if (ranges != null)
{
for (String range : ranges.split("\\s+"))
{
try
{
set.add(new IPRange(range));
}
catch (Exception unused)
{ /* besides due to invalid strings exceptions might get thrown if the string
* contains a hostname (NetworkOnMainThreadException) */
return null;
}
}
}
return set;
}
/**
* Add a range to this set. Automatically gets merged with existing ranges.
*/
public void add(IPRange range)
{
if (mRanges.contains(range))
{
return;
}
reinsert:
while (true)
{
Iterator<IPRange> iterator = mRanges.iterator();
while (iterator.hasNext())
{
IPRange existing = iterator.next();
IPRange replacement = existing.merge(range);
if (replacement != null)
{
iterator.remove();
range = replacement;
continue reinsert;
}
}
mRanges.add(range);
break;
}
}
/**
* Add all ranges from the given set.
*/
public void add(IPRangeSet ranges)
{
if (ranges == this)
{
return;
}
for (IPRange range : ranges.mRanges)
{
add(range);
}
}
/**
* Add all ranges from the given collection to this set.
*/
public void addAll(Collection<? extends IPRange> coll)
{
for (IPRange range : coll)
{
add(range);
}
}
/**
* Remove the given range from this set. Existing ranges are automatically adjusted.
*/
public void remove(IPRange range)
{
ArrayList <IPRange> additions = new ArrayList<>();
Iterator<IPRange> iterator = mRanges.iterator();
while (iterator.hasNext())
{
IPRange existing = iterator.next();
List<IPRange> result = existing.remove(range);
if (result.size() == 0)
{
iterator.remove();
}
else if (!result.get(0).equals(existing))
{
iterator.remove();
additions.addAll(result);
}
}
mRanges.addAll(additions);
}
/**
* Remove the given ranges from ranges in this set.
*/
public void remove(IPRangeSet ranges)
{
if (ranges == this)
{
mRanges.clear();
return;
}
for (IPRange range : ranges.mRanges)
{
remove(range);
}
}
/**
* Get all the subnets derived from all the ranges in this set.
*/
public Iterable<IPRange> subnets()
{
return new Iterable<IPRange>()
{
@Override
public Iterator<IPRange> iterator()
{
return new Iterator<IPRange>()
{
private Iterator<IPRange> mIterator = mRanges.iterator();
private List<IPRange> mSubnets;
@Override
public boolean hasNext()
{
return (mSubnets != null && mSubnets.size() > 0) || mIterator.hasNext();
}
@Override
public IPRange next()
{
if (mSubnets == null || mSubnets.size() == 0)
{
IPRange range = mIterator.next();
mSubnets = range.toSubnets();
}
return mSubnets.remove(0);
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
};
}
@Override
public Iterator<IPRange> iterator()
{
return mRanges.iterator();
}
/**
* Returns the number of ranges, not subnets.
*/
public int size()
{
return mRanges.size();
}
@Override
public String toString()
{ /* we could use TextUtils, but that causes the unit tests to fail */
StringBuilder sb = new StringBuilder();
for (IPRange range : mRanges)
{
if (sb.length() > 0)
{
sb.append(" ");
}
sb.append(range.toString());
}
return sb.toString();
}
}
@@ -0,0 +1,161 @@
/*
* Copyright (C) 2015 Tobias Brunner
*
* Copyright (C) secunet Security Networks AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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.
*/
package org.amnezia.vpn.ikev2.utils;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.regex.Pattern;
/**
* Simple generator for data/files that may be parsed by libstrongswan's
* settings_t class.
*/
public class SettingsWriter
{
/**
* Top-level section
*/
private final SettingsSection mTop = new SettingsSection();
/**
* Set a string value
* @param key
* @param value
* @return the writer
*/
public SettingsWriter setValue(String key, String value)
{
Pattern pattern = Pattern.compile("[^#{}=\"\\n\\t ]+");
if (key == null || !pattern.matcher(key).matches())
{
return this;
}
String[] keys = key.split("\\.");
SettingsSection section = mTop;
section = findOrCreateSection(Arrays.copyOfRange(keys, 0, keys.length-1));
section.Settings.put(keys[keys.length-1], value);
return this;
}
/**
* Set an integer value
* @param key
* @param value
* @return the writer
*/
public SettingsWriter setValue(String key, Integer value)
{
return setValue(key, value == null ? null : value.toString());
}
/**
* Set a boolean value
* @param key
* @param value
* @return the writer
*/
public SettingsWriter setValue(String key, Boolean value)
{
return setValue(key, value == null ? null : value ? "1" : "0");
}
/**
* Serializes the settings to a string in the format understood by
* libstrongswan's settings_t parser.
* @return serialized settings
*/
public String serialize()
{
StringBuilder builder = new StringBuilder();
serializeSection(mTop, builder);
return builder.toString();
}
/**
* Serialize the settings in a section and recursively serialize sub-sections
* @param section
* @param builder
*/
private void serializeSection(SettingsSection section, StringBuilder builder)
{
for (Entry<String, String> setting : section.Settings.entrySet())
{
builder.append(setting.getKey()).append('=');
if (setting.getValue() != null)
{
builder.append("\"").append(escapeValue(setting.getValue())).append("\"");
}
builder.append('\n');
}
for (Entry<String, SettingsSection> subsection : section.Sections.entrySet())
{
builder.append(subsection.getKey()).append(" {\n");
serializeSection(subsection.getValue(), builder);
builder.append("}\n");
}
}
/**
* Escape value so it may be wrapped in "
* @param value
* @return
*/
private String escapeValue(String value)
{
return value.replace("\\", "\\\\").replace("\"", "\\\"");
}
/**
* Find or create the nested sections with the given names
* @param sections list of section names
* @return final section
*/
private SettingsSection findOrCreateSection(String[] sections)
{
SettingsSection section = mTop;
for (String name : sections)
{
SettingsSection subsection = section.Sections.get(name);
if (subsection == null)
{
subsection = new SettingsSection();
section.Sections.put(name, subsection);
}
section = subsection;
}
return section;
}
/**
* A section containing sub-sections and settings.
*/
private class SettingsSection
{
/**
* Assigned key/value pairs
*/
LinkedHashMap<String,String> Settings = new LinkedHashMap<String, String>();
/**
* Assigned sub-sections
*/
LinkedHashMap<String,SettingsSection> Sections = new LinkedHashMap<String, SettingsWriter.SettingsSection>();
}
}
@@ -0,0 +1,167 @@
/*
* Copyright (C) 2017-2018 Tobias Brunner
*
* Copyright (C) secunet Security Networks AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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.
*/
package org.amnezia.vpn.ikev2.utils;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import androidx.annotation.Keep;
@Keep
public class SimpleFetcher
{
private static ExecutorService mExecutor = Executors.newCachedThreadPool();
private static Object mLock = new Object();
private static ArrayList<Future> mFutures = new ArrayList<>();
private static boolean mDisabled;
public static byte[] fetch(String uri, byte[] data, String contentType)
{
Future<byte[]> future;
synchronized (mLock)
{
if (mDisabled)
{
return null;
}
future = mExecutor.submit(() -> {
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Connection", "close");
try
{
if (contentType != null)
{
conn.setRequestProperty("Content-Type", contentType);
}
if (data != null)
{
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(data.length);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(data);
out.close();
}
return streamToArray(conn.getInputStream());
}
catch (SocketTimeoutException e)
{
return null;
}
finally
{
conn.disconnect();
}
});
mFutures.add(future);
}
try
{
/* this enforces a timeout as the ones set on HttpURLConnection might not work reliably */
return future.get(10000, TimeUnit.MILLISECONDS);
}
catch (InterruptedException|ExecutionException|TimeoutException|CancellationException e)
{
return null;
}
finally
{
synchronized (mLock)
{
mFutures.remove(future);
}
}
}
/**
* Enable fetching after it has been disabled.
*/
public static void enable()
{
synchronized (mLock)
{
mDisabled = false;
}
}
/**
* Disable the fetcher and abort any future requests.
*
* The native thread is not cancelable as it is working on an IKE_SA (canceling the methods of
* HttpURLConnection is not reliably possible anyway), so to abort while fetching we cancel the
* Future (causing a return from fetch() immediately) and let the executor thread continue its
* thing in the background.
*
* Also prevents future fetches until enabled again (e.g. if we aborted OCSP but would then
* block in the subsequent fetch for a CRL).
*/
public static void disable()
{
synchronized (mLock)
{
mDisabled = true;
for (Future future : mFutures)
{
future.cancel(true);
}
}
}
private static byte[] streamToArray(InputStream in) throws IOException
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
try
{
while ((len = in.read(buf)) != -1)
{
out.write(buf, 0, len);
}
return out.toByteArray();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
in.close();
}
return null;
}
}
@@ -0,0 +1,78 @@
/*
* Copyright (C) 2014-2019 Tobias Brunner
*
* Copyright (C) secunet Security Networks AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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.
*/
package org.amnezia.vpn.ikev2.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Utils
{
static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
/**
* Converts the given byte array to a hexadecimal string encoding.
*
* @param bytes byte array to convert
* @return hex string
*/
public static String bytesToHex(byte[] bytes)
{
char[] hex = new char[bytes.length * 2];
for (int i = 0; i < bytes.length; i++)
{
int value = bytes[i];
hex[i*2] = HEXDIGITS[(value & 0xf0) >> 4];
hex[i*2+1] = HEXDIGITS[ value & 0x0f];
}
return new String(hex);
}
/**
* Validate the given proposal string
*
* @param ike true for IKE, false for ESP
* @param proposal proposal string
* @return true if valid
*/
public native static boolean isProposalValid(boolean ike, String proposal);
/**
* Parse an IP address without doing a name lookup
*
* @param address IP address string
* @return address bytes if valid
*/
private native static byte[] parseInetAddressBytes(String address);
/**
* Parse an IP address without doing a name lookup (as compared to InetAddress.fromName())
*
* @param address IP address string
* @return address if valid
* @throws UnknownHostException if address is invalid
*/
public static InetAddress parseInetAddress(String address) throws UnknownHostException
{
byte[] bytes = parseInetAddressBytes(address);
if (bytes == null)
{
throw new UnknownHostException();
}
return InetAddress.getByAddress(bytes);
}
}
@@ -1,189 +0,0 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.amnezia.vpn.qt;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.Manifest.permission;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.webkit.WebView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
// Gets used by /platforms/android/androidAppListProvider.cpp
public class PackageManagerHelper {
final static String TAG = "PackageManagerHelper";
final static int MIN_CHROME_VERSION = 65;
final static List<String> CHROME_BROWSERS = Arrays.asList(
new String[] {"com.google.android.webview", "com.android.webview", "com.google.chrome"});
private static String getAllAppNames(Context ctx) {
JSONObject output = new JSONObject();
PackageManager pm = ctx.getPackageManager();
List<String> browsers = getBrowserIDs(pm);
List<PackageInfo> packs = pm.getInstalledPackages(PackageManager.GET_PERMISSIONS);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
// Do not add ourselves and System Apps to the list, unless it might be a browser
if ((!isSystemPackage(p,pm) || browsers.contains(p.packageName))
&& !isSelf(p)) {
String appid = p.packageName;
String appName = p.applicationInfo.loadLabel(pm).toString();
try {
output.put(appid, appName);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return output.toString();
}
private static Drawable getAppIcon(Context ctx, String id) {
try {
return ctx.getPackageManager().getApplicationIcon(id);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return new ColorDrawable(Color.TRANSPARENT);
}
private static boolean isSystemPackage(PackageInfo pkgInfo, PackageManager pm) {
if( (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0){
// no system app
return false;
}
// For Systems Packages there are Cases where we want to add it anyway:
// Has the use Internet permission (otherwise makes no sense)
// Had at least 1 update (this means it's probably on any AppStore)
// Has a a launch activity (has a ui and is not just a system service)
if(!usesInternet(pkgInfo)){
return true;
}
if(!hadUpdate(pkgInfo)){
return true;
}
if(pm.getLaunchIntentForPackage(pkgInfo.packageName) == null){
// If there is no way to launch this from a homescreen, def a sys package
return true;
}
return false;
}
private static boolean isSelf(PackageInfo pkgInfo) {
return pkgInfo.packageName.equals("org.amnezia.vpn")
|| pkgInfo.packageName.equals("org.amnezia.vpn.debug");
}
private static boolean usesInternet(PackageInfo pkgInfo){
if(pkgInfo.requestedPermissions == null){
return false;
}
for(int i=0; i < pkgInfo.requestedPermissions.length; i++) {
String permission = pkgInfo.requestedPermissions[i];
if(Manifest.permission.INTERNET.equals(permission)){
return true;
}
}
return false;
}
private static boolean hadUpdate(PackageInfo pkgInfo){
return pkgInfo.lastUpdateTime > pkgInfo.firstInstallTime;
}
// Returns List of all Packages that can classify themselves as browsers
private static List<String> getBrowserIDs(PackageManager pm) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.mozilla.org/"));
intent.addCategory(Intent.CATEGORY_BROWSABLE);
// We've tried using PackageManager.MATCH_DEFAULT_ONLY flag and found that browsers that
// are not set as the default browser won't be matched even if they had CATEGORY_DEFAULT set
// in the intent filter
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, PackageManager.MATCH_ALL);
List<String> browsers = new ArrayList<String>();
for (int i = 0; i < resolveInfos.size(); i++) {
ResolveInfo info = resolveInfos.get(i);
String browserID = info.activityInfo.packageName;
browsers.add(browserID);
}
return browsers;
}
// Gets called in AndroidAuthenticationListener;
public static boolean isWebViewSupported(Context ctx) {
Log.v(TAG, "Checking if installed Webview is compatible with FxA");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// The default Webview is able do to FXA
return true;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PackageInfo pi = WebView.getCurrentWebViewPackage();
if (CHROME_BROWSERS.contains(pi.packageName)) {
return isSupportedChromeBrowser(pi);
}
return isNotAncientBrowser(pi);
}
// Before O the webview is hardcoded, but we dont know which package it is.
// Check if com.google.android.webview is installed
PackageManager pm = ctx.getPackageManager();
try {
PackageInfo pi = pm.getPackageInfo("com.google.android.webview", 0);
return isSupportedChromeBrowser(pi);
} catch (PackageManager.NameNotFoundException e) {
}
// Otherwise check com.android.webview
try {
PackageInfo pi = pm.getPackageInfo("com.android.webview", 0);
return isSupportedChromeBrowser(pi);
} catch (PackageManager.NameNotFoundException e) {
}
Log.e(TAG, "Android System WebView is not found");
// Giving up :(
return false;
}
private static boolean isSupportedChromeBrowser(PackageInfo pi) {
Log.d(TAG, "Checking Chrome Based Browser: " + pi.packageName);
Log.d(TAG, "version name: " + pi.versionName);
Log.d(TAG, "version code: " + pi.versionCode);
try {
String versionCode = pi.versionName.split(Pattern.quote(" "))[0];
String majorVersion = versionCode.split(Pattern.quote("."))[0];
int version = Integer.parseInt(majorVersion);
return version >= MIN_CHROME_VERSION;
} catch (Exception e) {
Log.e(TAG, "Failed to check Chrome Version Code " + pi.versionName);
return false;
}
}
private static boolean isNotAncientBrowser(PackageInfo pi) {
// Not a google chrome - So the version name is worthless
// Lets just make sure the WebView
// used is not ancient ==> Was updated in at least the last 365 days
Log.d(TAG, "Checking Chrome Based Browser: " + pi.packageName);
Log.d(TAG, "version name: " + pi.versionName);
Log.d(TAG, "version code: " + pi.versionCode);
double oneYearInMillis = 31536000000L;
return pi.lastUpdateTime > (System.currentTimeMillis() - oneYearInMillis);
}
}
+415
View File
@@ -0,0 +1,415 @@
QT += widgets core gui network xml remoteobjects quick svg quickcontrols2
equals(QT_MAJOR_VERSION, 6): QT += core5compat
TARGET = AmneziaVPN
TEMPLATE = app
# silent builds on CI env
IS_CI=$$(CI)
!isEmpty(IS_CI){
message("Detected CI env")
CONFIG += silent #ccache
}
CONFIG += qtquickcompiler
include("3rd/QtSsh/src/ssh/qssh.pri")
include("3rd/QtSsh/src/botan/botan.pri")
!android:!ios:include("3rd/SingleApplication/singleapplication.pri")
include ("3rd/SortFilterProxyModel/SortFilterProxyModel.pri")
include("3rd/qrcodegen/qrcodegen.pri")
include("3rd/QSimpleCrypto/QSimpleCrypto.pri")
include("3rd/qtkeychain/qtkeychain.pri")
INCLUDEPATH += $$PWD/3rd/QSimpleCrypto/include
INCLUDEPATH += $$PWD/3rd/OpenSSL/include
INCLUDEPATH += $$PWD/3rd/qtkeychain/include
INCLUDEPATH += $$PWD/3rd/libssh/include
DEPENDPATH += $$PWD/3rd/OpenSSL/include
HEADERS += \
../ipc/ipc.h \
amnezia_application.h \
configurators/cloak_configurator.h \
configurators/configurator_base.h \
configurators/ikev2_configurator.h \
configurators/shadowsocks_configurator.h \
configurators/ssh_configurator.h \
configurators/vpn_configurator.h \
configurators/wireguard_configurator.h \
containers/containers_defs.h \
core/defs.h \
core/errorstrings.h \
configurators/openvpn_configurator.h \
core/scripts_registry.h \
core/server_defs.h \
core/servercontroller.h \
defines.h \
logger.h \
managementserver.h \
platforms/ios/MobileUtils.h \
platforms/linux/leakdetector.h \
protocols/protocols_defs.h \
secure_qsettings.h \
settings.h \
ui/notificationhandler.h \
ui/models/containers_model.h \
ui/models/protocols_model.h \
ui/pages.h \
ui/pages_logic/AppSettingsLogic.h \
ui/pages_logic/GeneralSettingsLogic.h \
ui/pages_logic/NetworkSettingsLogic.h \
ui/pages_logic/NewServerProtocolsLogic.h \
ui/pages_logic/PageLogicBase.h \
ui/pages_logic/QrDecoderLogic.h \
ui/pages_logic/ServerConfiguringProgressLogic.h \
ui/pages_logic/ServerContainersLogic.h \
ui/pages_logic/ServerListLogic.h \
ui/pages_logic/ServerSettingsLogic.h \
ui/pages_logic/ShareConnectionLogic.h \
ui/pages_logic/SitesLogic.h \
ui/pages_logic/StartPageLogic.h \
ui/pages_logic/ViewConfigLogic.h \
ui/pages_logic/VpnLogic.h \
ui/pages_logic/WizardLogic.h \
ui/pages_logic/protocols/CloakLogic.h \
ui/pages_logic/protocols/OpenVpnLogic.h \
ui/pages_logic/protocols/OtherProtocolsLogic.h \
ui/pages_logic/protocols/PageProtocolLogicBase.h \
ui/pages_logic/protocols/ShadowSocksLogic.h \
ui/pages_logic/protocols/WireGuardLogic.h \
ui/property_helper.h \
ui/models/servers_model.h \
ui/uilogic.h \
ui/qautostart.h \
ui/models/sites_model.h \
utilities.h \
vpnconnection.h \
protocols/vpnprotocol.h \
constants.h \
platforms/ios/QRCodeReaderBase.h
SOURCES += \
amnezia_application.cpp \
configurators/cloak_configurator.cpp \
configurators/configurator_base.cpp \
configurators/ikev2_configurator.cpp \
configurators/shadowsocks_configurator.cpp \
configurators/ssh_configurator.cpp \
configurators/vpn_configurator.cpp \
configurators/wireguard_configurator.cpp \
containers/containers_defs.cpp \
core/errorstrings.cpp \
configurators/openvpn_configurator.cpp \
core/scripts_registry.cpp \
core/server_defs.cpp \
core/servercontroller.cpp \
logger.cpp \
main.cpp \
managementserver.cpp \
platforms/ios/MobileUtils.cpp \
platforms/linux/leakdetector.cpp \
protocols/protocols_defs.cpp \
secure_qsettings.cpp \
settings.cpp \
ui/notificationhandler.cpp \
ui/models/containers_model.cpp \
ui/models/protocols_model.cpp \
ui/pages_logic/AppSettingsLogic.cpp \
ui/pages_logic/GeneralSettingsLogic.cpp \
ui/pages_logic/NetworkSettingsLogic.cpp \
ui/pages_logic/NewServerProtocolsLogic.cpp \
ui/pages_logic/PageLogicBase.cpp \
ui/pages_logic/QrDecoderLogic.cpp \
ui/pages_logic/ServerConfiguringProgressLogic.cpp \
ui/pages_logic/ServerContainersLogic.cpp \
ui/pages_logic/ServerListLogic.cpp \
ui/pages_logic/ServerSettingsLogic.cpp \
ui/pages_logic/ShareConnectionLogic.cpp \
ui/pages_logic/SitesLogic.cpp \
ui/pages_logic/StartPageLogic.cpp \
ui/pages_logic/ViewConfigLogic.cpp \
ui/pages_logic/VpnLogic.cpp \
ui/pages_logic/WizardLogic.cpp \
ui/pages_logic/protocols/CloakLogic.cpp \
ui/pages_logic/protocols/OpenVpnLogic.cpp \
ui/pages_logic/protocols/OtherProtocolsLogic.cpp \
ui/pages_logic/protocols/PageProtocolLogicBase.cpp \
ui/pages_logic/protocols/ShadowSocksLogic.cpp \
ui/models/servers_model.cpp \
ui/pages_logic/protocols/WireGuardLogic.cpp \
ui/uilogic.cpp \
ui/qautostart.cpp \
ui/models/sites_model.cpp \
utilities.cpp \
vpnconnection.cpp \
protocols/vpnprotocol.cpp \
platforms/ios/QRCodeReaderBase.cpp
RESOURCES += \
resources.qrc
TRANSLATIONS = \
translations/amneziavpn_ru.ts
win32 {
DEFINES += MVPN_WINDOWS
OTHER_FILES += platforms/windows/amneziavpn.rc
RC_FILE = platforms/windows/amneziavpn.rc
HEADERS += \
protocols/ikev2_vpn_protocol_windows.h \
SOURCES += \
protocols/ikev2_vpn_protocol_windows.cpp \
VERSION = 2.0.0.0
QMAKE_TARGET_COMPANY = "AmneziaVPN"
QMAKE_TARGET_PRODUCT = "AmneziaVPN"
LIBS += \
-luser32 \
-lrasapi32 \
-lshlwapi \
-liphlpapi \
-lws2_32 \
-lgdi32
QMAKE_LFLAGS_WINDOWS += /entry:mainCRTStartup
!contains(QMAKE_TARGET.arch, x86_64) {
message("Windows x86 build")
LIBS += -L$$PWD/3rd/OpenSSL/lib/windows/x86/ -llibssl -llibcrypto
}
else {
message("Windows x86_64 build")
LIBS += -L$$PWD/3rd/OpenSSL/lib/windows/x86_64/ -llibssl -llibcrypto
}
}
macx {
DEFINES += MVPN_MACOS
ICON = $$PWD/images/app.icns
HEADERS += ui/macos_util.h
SOURCES += ui/macos_util.mm
LIBS += -framework Cocoa -framework ApplicationServices -framework CoreServices -framework Foundation -framework AppKit -framework Security
LIBS += $$PWD/3rd/OpenSSL/lib/macos/x86_64/libcrypto.a
LIBS += $$PWD/3rd/OpenSSL/lib/macos/x86_64/libssl.a
}
linux:!android {
DEFINES += MVPN_LINUX
LIBS += /usr/lib/x86_64-linux-gnu/libcrypto.a
LIBS += /usr/lib/x86_64-linux-gnu/libssl.a
LIBS += $$PWD/3rd/libssh/build/src/libssh.a
LIBS += -lz
INCLUDEPATH += $$PWD/platforms/linux
}
win32|macx|linux:!android {
DEFINES += AMNEZIA_DESKTOP
HEADERS += \
core/ipcclient.h \
core/privileged_process.h \
ui/systemtray_notificationhandler.h \
protocols/openvpnprotocol.h \
protocols/openvpnovercloakprotocol.h \
protocols/shadowsocksvpnprotocol.h \
protocols/wireguardprotocol.h \
SOURCES += \
core/ipcclient.cpp \
core/privileged_process.cpp \
ui/systemtray_notificationhandler.cpp \
protocols/openvpnprotocol.cpp \
protocols/openvpnovercloakprotocol.cpp \
protocols/shadowsocksvpnprotocol.cpp \
protocols/wireguardprotocol.cpp \
REPC_REPLICA += ../ipc/ipc_interface.rep
REPC_REPLICA += ../ipc/ipc_process_interface.rep
}
android {
message(Platform: android)
message("$$ANDROID_TARGET_ARCH")
versionAtLeast(QT_VERSION, 6.0.0) {
# We need to include qtprivate api's
# As QAndroidBinder is not yet implemented with a public api
QT += core-private
ANDROID_ABIS = $$ANDROID_TARGET_ARCH
}
DEFINES += MVPN_ANDROID
INCLUDEPATH += platforms/android
HEADERS += \
platforms/android/android_controller.h \
platforms/android/android_notificationhandler.h \
protocols/android_vpnprotocol.h \
platforms/android/androidutils.h \
platforms/android/androidvpnactivity.h
SOURCES += \
platforms/android/android_controller.cpp \
platforms/android/android_notificationhandler.cpp \
protocols/android_vpnprotocol.cpp \
platforms/android/androidutils.cpp \
platforms/android/androidvpnactivity.cpp
DISTFILES += \
android/AndroidManifest.xml \
android/build.gradle \
android/gradle/wrapper/gradle-wrapper.jar \
android/gradle/wrapper/gradle-wrapper.properties \
android/gradlew \
android/gradlew.bat \
android/gradle.properties \
android/res/values/libs.xml \
android/res/xml/fileprovider.xml \
android/src/org/amnezia/vpn/AuthHelper.java \
android/src/org/amnezia/vpn/IPCContract.kt \
android/src/org/amnezia/vpn/NotificationUtil.kt \
android/src/org/amnezia/vpn/OpenVPNThreadv3.kt \
android/src/org/amnezia/vpn/Prefs.kt \
android/src/org/amnezia/vpn/VpnLogger.kt \
android/src/org/amnezia/vpn/VpnService.kt \
android/src/org/amnezia/vpn/VpnServiceBinder.kt \
android/src/org/amnezia/vpn/qt/AmneziaApp.kt \
android/src/org/amnezia/vpn/qt/PackageManagerHelper.java \
android/src/org/amnezia/vpn/qt/VPNActivity.kt \
android/src/org/amnezia/vpn/qt/VPNApplication.java \
android/src/org/amnezia/vpn/qt/VPNPermissionHelper.kt
ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android
for (abi, ANDROID_ABIS): {
equals(ANDROID_TARGET_ARCH,$$abi) {
LIBS += $$PWD/3rd/OpenSSL/lib/android/$${abi}/libcrypto.a
LIBS += $$PWD/3rd/OpenSSL/lib/android/$${abi}/libssl.a
}
ANDROID_EXTRA_LIBS += $$PWD/android/lib/wireguard/$${abi}/libwg.so
ANDROID_EXTRA_LIBS += $$PWD/android/lib/wireguard/$${abi}/libwg-go.so
ANDROID_EXTRA_LIBS += $$PWD/android/lib/wireguard/$${abi}/libwg-quick.so
ANDROID_EXTRA_LIBS += $$PWD/android/lib/openvpn/$${abi}/libjbcrypto.so
ANDROID_EXTRA_LIBS += $$PWD/android/lib/openvpn/$${abi}/libopenvpn.so
ANDROID_EXTRA_LIBS += $$PWD/android/lib/openvpn/$${abi}/libopvpnutil.so
ANDROID_EXTRA_LIBS += $$PWD/android/lib/openvpn/$${abi}/libovpn3.so
ANDROID_EXTRA_LIBS += $$PWD/android/lib/openvpn/$${abi}/libovpnexec.so
}
}
ios {
message("Client iOS build")
CONFIG += static
CONFIG += file_copies
# For the authentication
LIBS += -framework AuthenticationServices
# For notifications
LIBS += -framework UIKit
LIBS += -framework Foundation
LIBS += -framework StoreKit
LIBS += -framework UserNotifications
LIBS += -framework AVFoundation
DEFINES += MVPN_IOS
HEADERS += \
protocols/ios_vpnprotocol.h \
platforms/ios/iosnotificationhandler.h \
platforms/ios/json.h \
platforms/ios/bigint.h \
platforms/ios/bigintipv6addr.h \
platforms/ios/ipaddress.h \
platforms/ios/ipaddressrange.h \
platforms/ios/QtAppDelegate.h \
platforms/ios/QtAppDelegate-C-Interface.h
SOURCES -= \
platforms/ios/QRCodeReaderBase.cpp \
platforms/ios/MobileUtils.cpp
SOURCES += \
protocols/ios_vpnprotocol.mm \
platforms/ios/iosnotificationhandler.mm \
platforms/ios/json.cpp \
platforms/ios/iosglue.mm \
platforms/ios/ipaddress.cpp \
platforms/ios/ipaddressrange.cpp \
platforms/ios/QRCodeReaderBase.mm \
platforms/ios/QtAppDelegate.mm \
platforms/ios/MobileUtils.mm
Q_ENABLE_BITCODE.value = NO
Q_ENABLE_BITCODE.name = ENABLE_BITCODE
QMAKE_MAC_XCODE_SETTINGS += Q_ENABLE_BITCODE
# CONFIG(iphoneos, iphoneos|iphonesimulator) {
iphoneos {
message("Building for iPhone OS")
QMAKE_TARGET_BUNDLE_PREFIX = org.amnezia
QMAKE_BUNDLE = AmneziaVPN
QMAKE_IOS_DEPLOYMENT_TARGET = 13.0
QMAKE_APPLE_TARGETED_DEVICE_FAMILY = 1
QMAKE_DEVELOPMENT_TEAM = X7UJ388FXK
QMAKE_PROVISIONING_PROFILE = f2fefb59-14aa-4aa9-ac14-1d5531b06dcc
QMAKE_XCODE_CODE_SIGN_IDENTITY = "Apple Distribution"
QMAKE_INFO_PLIST = $$PWD/ios/app/Info.plist
XCODEBUILD_FLAGS += -allowProvisioningUpdates
DEFINES += iphoneos
contains(QT_ARCH, arm64) {
message("Building for iOS/ARM v8 64-bit architecture")
ARCH_TAG = "ios_armv8_64"
LIBS += $$PWD/3rd/OpenSSL/lib/ios/iphone/libcrypto.a
LIBS += $$PWD/3rd/OpenSSL/lib/ios/iphone/libssl.a
} else {
message("Building for iOS/ARM v7 (32-bit) architecture")
ARCH_TAG = "ios_armv7"
}
}
# }
# CONFIG(iphonesimulator, iphoneos|iphonesimulator) {
# iphonesimulator {
# message("Building for iPhone Simulator")
# ARCH_TAG = "ios_x86_64"
#
# DEFINES += iphonesimulator
#
# LIBS += $$PWD/3rd/OpenSSL/lib/ios/simulator/libcrypto.a
# LIBS += $$PWD/3rd/OpenSSL/lib/ios/simulator/libssl.a
# }
# }
NETWORKEXTENSION=1
# ! build_pass: system(ruby $$PWD/scripts/xcode_patcher.rb "$$PWD" "$$OUT_PWD/AmneziaVPN.xcodeproj" "2.0" "2.0.0" "ios" "$$NETWORKEXTENSION"|| echo "Failed to merge xcode with wireguard")
#ruby %{sourceDir}/client/ios/xcode_patcher.rb "%{buildDir}/AmneziaVPN.xcodeproj" "2.0" "2.0.0" "ios" "1"
#cd client/ && /Users/md/Qt/5.15.2/ios/bin/qmake -o Makefile /Users/md/amnezia/desktop-client/client/client.pro -spec macx-ios-clang CONFIG+=iphonesimulator CONFIG+=simulator CONFIG+=qml_debug -after
# %{sourceDir}/client/ios/xcode_patcher.rb %{buildDir}/client/AmneziaVPN.xcodeproj 2.0 2.0.0 ios 1
}
+13 -10
View File
@@ -12,16 +12,16 @@ set(LIBS ${LIBS} SortFilterProxyModel)
include(${CLIENT_ROOT_DIR}/3rd/qrcodegen/qrcodegen.cmake)
include(${CLIENT_ROOT_DIR}/3rd/QSimpleCrypto/QSimpleCrypto.cmake)
set(BUILD_SHARED_LIBS ON CACHE BOOL "" FORCE)
add_subdirectory(${CLIENT_ROOT_DIR}/3rd/zlib)
if(WIN32)
set(ZLIB_LIBRARY $<IF:$<CONFIG:Debug>,zlibd,zlib>)
else()
set(ZLIB_LIBRARY z)
endif()
set(ZLIB_INCLUDE_DIR "${CLIENT_ROOT_DIR}/3rd/zlib" "${CMAKE_CURRENT_BINARY_DIR}/3rd/zlib")
link_directories(${CMAKE_CURRENT_BINARY_DIR}/3rd/zlib)
link_libraries(${ZLIB_LIBRARY})
#set(BUILD_SHARED_LIBS ON CACHE BOOL "" FORCE)
#add_subdirectory(${CLIENT_ROOT_DIR}/3rd/zlib)
#if(WIN32)
# set(ZLIB_LIBRARY $<IF:$<CONFIG:Debug>,zlibd,zlib>)
#else()
# set(ZLIB_LIBRARY z)
#endif()
#set(ZLIB_INCLUDE_DIR "${CLIENT_ROOT_DIR}/3rd/zlib" "${CMAKE_CURRENT_BINARY_DIR}/3rd/zlib")
#link_directories(${CMAKE_CURRENT_BINARY_DIR}/3rd/zlib)
#link_libraries(${ZLIB_LIBRARY})
if(IOS)
set(ENABLE_PROGRAMS OFF CACHE BOOL "" FORCE)
@@ -105,6 +105,9 @@ set(BUILD_WITH_QT6 ON)
add_subdirectory(${CLIENT_ROOT_DIR}/3rd/qtkeychain)
set(LIBS ${LIBS} qt6keychain)
include(${CLIENT_ROOT_DIR}/3rd/strongswan/strongswan.cmake)
include_directories(
${CLIENT_ROOT_DIR}/3rd/OpenSSL/include
${CLIENT_ROOT_DIR}/3rd/libssh/include
@@ -118,10 +118,6 @@ QString OpenVpnConfigurator::processConfigWithLocalSettings(QString jsonConfig)
config.append("redirect-gateway def1 bypass-dhcp\n");
}
}
// Prevent ipv6 leak
config.append("ifconfig-ipv6 fd15:53b6:dead::2/64 fd15:53b6:dead::1\n");
config.append("redirect-gateway ipv6\n");
#if (defined Q_OS_MAC || defined(Q_OS_LINUX)) && !defined(Q_OS_ANDROID)
config.replace("block-outside-dns", "");
+1
View File
@@ -170,6 +170,7 @@ bool ContainerProps::isSupportedByCurrentPlatform(DockerContainer c)
case DockerContainer::WireGuard: return true;
case DockerContainer::OpenVpn: return true;
case DockerContainer::ShadowSocks: return true;
case DockerContainer::Ipsec: return true;
default: return false;
}
+10
View File
@@ -0,0 +1,10 @@
#ifndef DEFINES_H
#define DEFINES_H
#define APPLICATION_NAME "AmneziaVPN"
#define SERVICE_NAME "AmneziaVPN-service"
#define ORGANIZATION_NAME "AmneziaVPN.ORG"
#define APP_MAJOR_VERSION "2.1.2"
#define APP_VERSION "2.1.2.0"
#endif // DEFINES_H
+92
View File
@@ -0,0 +1,92 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleAllowMixedLocalizations</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>AmneziaVPN</string>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>Amnezia VPN config</string>
<key>LSHandlerRank</key>
<string>Alternate</string>
<key>LSItemContentTypes</key>
<array>
<string>org.amnezia.AmneziaVPN.amnezia-config</string>
</array>
</dict>
</array>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIcons</key>
<dict/>
<key>CFBundleIcons~ipad</key>
<dict/>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${APP_DISPLAY_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>7</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIFileSharingEnabled</key>
<true/>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>NSCameraUsageDescription</key>
<string>Amnezia VPN needs access to the camera for reading QR-codes.</string>
<key>UILaunchStoryboardName</key>
<string>AmneziaVPNLaunchScreen</string>
<key>UIRequiresFullScreen</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array/>
<key>UIUserInterfaceStyle</key>
<string>Light</string>
<key>UTImportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.data</string>
</array>
<key>UTTypeDescription</key>
<string>Amnezia VPN config</string>
<key>UTTypeIconFiles</key>
<array/>
<key>UTTypeIdentifier</key>
<string>org.amnezia.AmneziaVPN.amnezia-config</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>vpn</string>
</array>
<key>public.mime-type</key>
<array>
<string>text/plain</string>
</array>
</dict>
</dict>
</array>
</dict>
</plist>
+13 -32
View File
@@ -4,45 +4,26 @@ set(CLIENT_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/../..)
add_executable(networkextension)
set_target_properties(networkextension PROPERTIES
OUTPUT_NAME "AmneziaVPNNetworkExtension"
XCODE_PRODUCT_TYPE com.apple.product-type.app-extension
BUNDLE_EXTENSION appex
MACOSX_BUNDLE ON
MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist.in
MACOSX_BUNDLE_INFO_STRING "AmneziaVPNNetworkExtension"
MACOSX_BUNDLE_BUNDLE_NAME "AmneziaVPNNetworkExtension"
MACOSX_BUNDLE_BUNDLE_VERSION "${BUILD_ID}"
MACOSX_BUNDLE_COPYRIGHT "MPL-2.0"
MACOSX_BUNDLE_GUI_IDENTIFIER "${BUILD_IOS_APP_IDENTIFIER}.network-extension"
MACOSX_BUNDLE_BUNDLE_VERSION "${CMAKE_PROJECT_VERSION_TWEAK}"
MACOSX_BUNDLE_INFO_STRING "AmneziaVPNNetworkExtension"
MACOSX_BUNDLE_LONG_VERSION_STRING "${CMAKE_PROJECT_VERSION}-${BUILD_ID}"
MACOSX_BUNDLE_SHORT_VERSION_STRING "${CMAKE_PROJECT_VERSION}"
XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "${BUILD_IOS_APP_IDENTIFIER}.network-extension"
XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS ${CMAKE_CURRENT_SOURCE_DIR}/AmneziaVPNNetworkExtension.entitlements
XCODE_ATTRIBUTE_MARKETING_VERSION "${APP_MAJOR_VERSION}"
XCODE_ATTRIBUTE_CURRENT_PROJECT_VERSION "${BUILD_ID}"
XCODE_ATTRIBUTE_PRODUCT_NAME "AmneziaVPNNetworkExtension"
XCODE_ATTRIBUTE_APPLICATION_EXTENSION_API_ONLY "YES"
XCODE_ATTRIBUTE_ENABLE_BITCODE "NO"
XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1,2"
XCODE_ATTRIBUTE_LD_RUNPATH_SEARCH_PATHS "@executable_path/../../Frameworks"
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "Apple Distribution"
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY[variant=Debug] "Apple Development"
XCODE_ATTRIBUTE_CODE_SIGN_STYLE Manual
XCODE_ATTRIBUTE_PROVISIONING_PROFILE_SPECIFIER "match AppStore org.amnezia.AmneziaVPN.network-extension"
XCODE_ATTRIBUTE_PROVISIONING_PROFILE_SPECIFIER[variant=Debug] "match Development org.amnezia.AmneziaVPN.network-extension"
)
set_target_properties(networkextension PROPERTIES
XCODE_ATTRIBUTE_SWIFT_VERSION "5.0"
XCODE_ATTRIBUTE_CLANG_ENABLE_MODULES "YES"
XCODE_ATTRIBUTE_SWIFT_OBJC_BRIDGING_HEADER "${CMAKE_CURRENT_SOURCE_DIR}/WireGuardNetworkExtension-Bridging-Header.h"
XCODE_ATTRIBUTE_SWIFT_OPTIMIZATION_LEVEL "-Onone"
XCODE_ATTRIBUTE_SWIFT_PRECOMPILE_BRIDGING_HEADER "NO"
)
set_target_properties("networkextension" PROPERTIES
XCODE_ATTRIBUTE_DEVELOPMENT_TEAM "X7UJ388FXK"
XCODE_ATTRIBUTE_APPLICATION_EXTENSION_API_ONLY "YES"
XCODE_ATTRIBUTE_ENABLE_BITCODE "NO"
XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS ${CMAKE_CURRENT_SOURCE_DIR}/AmneziaVPNNetworkExtension.entitlements
)
find_library(FW_ASSETS_LIBRARY AssetsLibrary)
@@ -102,7 +83,7 @@ include(${CLIENT_ROOT_DIR}/cmake/golang.cmake)
## Build the wireguard go library for iOS simulation.
## TODO: Some special handling around GOARCH for
execute_process(OUTPUT_VARIABLE SIM_SDKROOT OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND xcrun --sdk iphonesimulator --show-sdk-path)
build_go_archive(${CMAKE_CURRENT_BINARY_DIR}/libwg-sim.a ${CLIENT_ROOT_DIR}/3rd/wireguard-apple/Sources/WireGuardKitGo/go.mod
build_go_archive(${CMAKE_CURRENT_BINARY_DIR}/libwg-sim.a ${CMAKE_SOURCE_DIR}/3rd/wireguard-apple/Sources/WireGuardKitGo/go.mod
GOOS ios
GOARCH amd64
CGO_CFLAGS -arch x86_64 -isysroot ${SIM_SDKROOT}
@@ -111,7 +92,7 @@ build_go_archive(${CMAKE_CURRENT_BINARY_DIR}/libwg-sim.a ${CLIENT_ROOT_DIR}/3rd/
## Build the wireguard go library for iOS devices.
execute_process(OUTPUT_VARIABLE IOS_SDKROOT OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND xcrun --sdk ${CMAKE_OSX_SYSROOT} --show-sdk-path)
build_go_archive(${CMAKE_CURRENT_BINARY_DIR}/libwg-dev.a ${CLIENT_ROOT_DIR}/3rd/wireguard-apple/Sources/WireGuardKitGo/go.mod
build_go_archive(${CMAKE_CURRENT_BINARY_DIR}/libwg-dev.a ${CMAKE_SOURCE_DIR}/3rd/wireguard-apple/Sources/WireGuardKitGo/go.mod
GOOS ios
GOARCH arm64
CGO_CFLAGS -arch arm64 -isysroot ${IOS_SDKROOT}
@@ -130,4 +111,4 @@ add_custom_target(libwg_builder
## Link and depend on the wireguard library.
add_dependencies(networkextension libwg_builder)
target_link_libraries(networkextension PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/libwg-unified.a)
target_link_libraries(networkextension PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/libwg-unified.a)
+52
View File
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>MozillaVPNNetworkExtension</string>
<key>NSExtension</key>
<dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.networkextension.packet-tunnel</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).PacketTunnelProvider</string>
</dict>
<key>com.wireguard.ios.app_group_id</key>
<string>group.$(APP_ID_IOS)</string>
<key>com.wireguard.macos.app_group_id</key>
<string>$(DEVELOPMENT_TEAM).group.$(APP_ID_MACOS)</string>
</dict>
</plist>
+13
View File
@@ -0,0 +1,13 @@
DEVELOPMENT_TEAM = <X7UJ388FXK>
# MacOS configuration
GROUP_ID_MACOS = <>
APP_ID_MACOS = <>
NETEXT_ID_MACOS = <>
LOGIN_ID_MACOS = <>
NATIVEMESSAGING_ID_MACOS = <>
# IOS configuration
GROUP_ID_IOS = group.org.mozilla.ios.Guardian
APP_ID_IOS = org.mozilla.ios.FirefoxVPN
NETEXT_ID_IOS = org.mozilla.ios.FirefoxVPN.network-extension
+1 -1
View File
@@ -9,7 +9,7 @@
#include <iostream>
#include "version.h"
#include "defines.h"
#include "utilities.h"
#ifdef AMNEZIA_DESKTOP
+1 -1
View File
@@ -3,7 +3,7 @@
#include <QTimer>
#include "amnezia_application.h"
#include "version.h"
#include "defines.h"
#include "migrations.h"
#ifdef Q_OS_WIN
+1 -1
View File
@@ -5,7 +5,7 @@
#include <QFile>
#include <QStandardPaths>
#include "version.h"
#include "defines.h"
Migrations::Migrations(QObject *parent)
: QObject{parent}
@@ -176,6 +176,21 @@ ErrorCode AndroidController::start()
appContext.object());
QJsonDocument doc(m_vpnConfig);
/*** The following code snippet needs to correct displaying of config in debug console
* (Android's stdout limits length of output message)
*
* QString string(doc.toJson(QJsonDocument::Compact));
*
* qDebug() << "*** config: ";
* for (int i = 0; i <= string.length()/100; i++) {
* int start = i*100;
* qDebug() << string.mid(start, 100);
* }
*
* qDebug() << "*** config: " << m_vpnConfig;
***/
AndroidVPNActivity::sendToService(ServiceAction::ACTION_ACTIVATE, doc.toJson());
return NoError;
@@ -3,33 +3,41 @@ LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
IDI_ICON1 ICON "../../images/app.ico"
#define VER_FILEVERSION 2,0,0,0
#define VER_FILEVERSION_STR "2.0.0.0\0"
#define VER_PRODUCTVERSION 2,0,0,0
#define VER_PRODUCTVERSION_STR "2.0.0.0\0"
#define VER_COMPANYNAME_STR "AmneziaVPN"
#define VER_FILEDESCRIPTION_STR VER_COMPANYNAME_STR
#define VER_INTERNALNAME_STR VER_COMPANYNAME_STR
#define VER_FILEDESCRIPTION_STR "AmneziaVPN"
#define VER_INTERNALNAME_STR "AmneziaVPN"
#define VER_LEGALCOPYRIGHT_STR "AmneziaVPN."
#define VER_LEGALTRADEMARKS1_STR "All Rights Reserved"
#define VER_LEGALTRADEMARKS2_STR VER_LEGALTRADEMARKS1_STR
#define VER_ORIGINALFILENAME_STR "amneziavpn.exe"
#define VER_PRODUCTNAME_STR VER_COMPANYNAME_STR
#define VER_PRODUCTNAME_STR "AmneziaVPN"
#define VER_COMPANYDOMAIN_STR "https://amnezia.org/"
VS_VERSION_INFO VERSIONINFO
FILEVERSION @CMAKE_PROJECT_VERSION_MAJOR@,@CMAKE_PROJECT_VERSION_MINOR@,@CMAKE_PROJECT_VERSION_PATCH@,@CMAKE_PROJECT_VERSION_TWEAK@
PRODUCTVERSION @CMAKE_PROJECT_VERSION_MAJOR@,@CMAKE_PROJECT_VERSION_MINOR@,@CMAKE_PROJECT_VERSION_PATCH@
FILEVERSION VER_FILEVERSION
PRODUCTVERSION VER_PRODUCTVERSION
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904E4"
BEGIN
VALUE "CompanyName", VER_COMPANYNAME_STR
VALUE "FileDescription", "@CMAKE_PROJECT_DESCRIPTION@"
VALUE "FileVersion", "@CMAKE_PROJECT_VERSION@"
VALUE "FileDescription", VER_FILEDESCRIPTION_STR
VALUE "FileVersion", VER_FILEVERSION_STR
VALUE "InternalName", VER_INTERNALNAME_STR
VALUE "LegalCopyright", VER_LEGALCOPYRIGHT_STR
VALUE "LegalTrademarks1", VER_LEGALTRADEMARKS1_STR
VALUE "LegalTrademarks2", VER_LEGALTRADEMARKS2_STR
VALUE "OriginalFilename", VER_ORIGINALFILENAME_STR
VALUE "ProductName", VER_PRODUCTNAME_STR
VALUE "ProductVersion", "@CMAKE_PROJECT_VERSION@"
VALUE "ProductVersion", VER_PRODUCTVERSION_STR
END
END
+1 -1
View File
@@ -6,7 +6,7 @@
#include <QRandomGenerator>
#include "logger.h"
#include "version.h"
#include "defines.h"
#include "utilities.h"
#include "openvpnprotocol.h"
+254
View File
@@ -0,0 +1,254 @@
#!/bin/bash
. $(dirname $0)/commons.sh
if [ -f .env ]; then
. .env
fi
RELEASE=1
OS=
NETWORKEXTENSION=
WORKINGDIR=`pwd`
helpFunction() {
print G "Usage:"
print N "\t$0 <macos|ios|> [-d|--debug] [-n|--networkextension]"
print N ""
print N "By default, the project is compiled in release mode. Use -d or --debug for a debug build."
print N "Use -n or --networkextension to force the network-extension component for MacOS too."
print N ""
print N "If MVPN_IOS_ADJUST_TOKEN env is found, this will be used at compilation time."
print N ""
print G "Config variables:"
print N "\tQT_MACOS_BIN=</path/of/the/qt/bin/folder/for/macos>"
print N "\tQT_IOS_BIN=</path/of/the/qt/bin/folder/for/ios>"
print N ""
exit 0
}
print N "This script compiles AmneziaVPN for MacOS/iOS"
print N ""
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-d | --debug)
RELEASE=
shift
;;
-n | --networkextension)
NETWORKEXTENSION=1
shift
;;
-h | --help)
helpFunction
;;
*)
if [[ "$OS" ]]; then
helpFunction
fi
OS=$1
shift
;;
esac
done
fetch() {
if command -v "wget" &>/dev/null; then
wget -nc -O "$2" "$1"
return
fi
if command -v "curl" &>/dev/null; then
curl "$1" -o "$2" -s -L
return
fi
killProcess "You must have 'wget' or 'curl' installed."
}
sha256() {
if command -v "sha256sum" &>/dev/null; then
sha256sum "$1"
return 0
fi
if command -v "openssl" &>/dev/null; then
openssl dgst -sha256 "$1"
return 0
fi
killProcess "You must have 'sha256sum' or 'openssl' installed."
}
if [[ "$OS" != "macos" ]] && [[ "$OS" != "ios" ]] && [[ "$OS" != "macostest" ]]; then
helpFunction
fi
if [[ "$OS" == "ios" ]]; then
# Network-extension is the default for IOS
NETWORKEXTENSION=1
fi
if ! [ -d "ios" ] || ! [ -d "macos" ]; then
killProcess "This script must be executed at the root of the repository."
fi
QMAKE=qmake
if [ "$OS" = "macos" ] && ! [ "$QT_MACOS_BIN" = "" ]; then
QMAKE=$QT_MACOS_BIN/qmake
elif [ "$OS" = "macostest" ] && ! [ "$QT_MACOS_BIN" = "" ]; then
QMAKE=$QT_MACOS_BIN/qmake
elif [ "$OS" = "ios" ] && ! [ "$QT_IOS_BIN" = "" ]; then
QMAKE=$QT_IOS_BIN/qmake
fi
$QMAKE -v &>/dev/null || killProcess "qmake doesn't exist or it fails"
print Y "Retrieve the wireguard-go version... "
if [ "$OS" = "macos" ]; then
(cd macos/gobridge && go list -m golang.zx2c4.com/wireguard | sed -n 's/.*v\([0-9.]*\).*/#define WIREGUARD_GO_VERSION "\1"/p') > macos/gobridge/wireguard-go-version.h
elif [ "$OS" = "ios" ]; then
if [ ! -f 3rd/wireguard-apple/Sources/WireGuardKitGo/wireguard-go-version.h ]; then
print Y "Creating wireguard-go-version.h file"
touch 3rd/wireguard-apple/Sources/WireGuardKitGo/wireguard-go-version.h
cat <<EOF >> $WORKINGDIR/3rd/wireguard-apple/Sources/WireGuardKitGo/wireguard-go-version.h
#define WIREGUARD_GO_VERSION "0.0.0"
EOF
fi
(cd 3rd/wireguard-apple/Sources/WireGuardKitGo && go list -m golang.zx2c4.com/wireguard | sed -n 's/.*v\([0-9.]*\).*/#define WIREGUARD_GO_VERSION "\1"/p') > 3rd/wireguard-apple/Sources/WireGuardKitGo/wireguard-go-version.h
fi
print G "done."
printn Y "Cleaning the existing project... "
rm -rf AmneziaVPN.xcodeproj/ || killProcess "Failed to remove things"
print G "done."
printn Y "Extract the project version... "
SHORTVERSION=$(cat version.pri | grep VERSION | grep defined | cut -d= -f2 | tr -d \ )
FULLVERSION=$(cat versionfull.pri | grep BUILDVERSION | grep defined | cut -d= -f2 | tr -d \ )
print G "$SHORTVERSION - $FULLVERSION"
MACOS_FLAGS="
QTPLUGIN+=qsvg
CONFIG-=static
CONFIG+=balrog
"
MACOSTEST_FLAGS="
QTPLUGIN+=qsvg
CONFIG-=static
CONFIG+=DUMMY
"
IOS_FLAGS="
Q_OS_IOS=1
"
printn Y "Mode: "
if [[ "$RELEASE" ]]; then
print G "release"
MODE="CONFIG-=debug CONFIG+=release CONFIG-=debug_and_release"
else
print G "debug"
MODE="CONFIG+=debug CONFIG-=release CONFIG-=debug_and_release"
fi
OSRUBY=$OS
printn Y "OS: "
print G "$OS"
if [ "$OS" = "macos" ]; then
PLATFORM=$MACOS_FLAGS
elif [ "$OS" = "macostest" ]; then
OSRUBY=macos
PLATFORM=$MACOSTEST_FLAGS
elif [ "$OS" = "ios" ]; then
PLATFORM=$IOS_FLAGS
else
killProcess "Why are we here?"
fi
VPNMODE=
printn Y "VPN mode: "
if [[ "$NETWORKEXTENSION" ]]; then
print G network-extension
VPNMODE="CONFIG+=networkextension"
else
print G daemon
fi
printn Y "Web-Extension: "
WEMODE=
if [ "$OS" = "macos" ]; then
print G web-extension
WEMODE="CONFIG+=webextension"
else
print G none
fi
if [ "$OS" = "ios" ]; then
print Y "Prepare to build OpenVPNAdapter..."
prepare_to_build_vpn
print Y "Building OpenVPNAdapter..."
compile_openvpn_adapter
else
print Y "No OpenVPNAdapter will be built"
fi
if [ "$OS" = "ios" ]; then
print Y "Prepare to build ShadowSocks..."
prepare_to_build_ss
print Y "Patching the ShadowSocks project..."
patch_ss
ruby ../../scripts/ss_project_patcher.rb "ShadowSocks.xcodeproj"
print G "done."
print Y "Building ShadowSocks Framework..."
compile_ss_frameworks
else
print Y "No ShadowSocket Library will be built"
fi
if [ "$OS" = "ios" ]; then
print Y "Prepare to build CocoaAsyncSocket..."
prepare_to_build_cas
print Y "Building CocoaAsyncSocket Framework..."
compile_cocoa_async_socket
else
print Y "No CocoaAsyncSocket will be built"
fi
if [ "$OS" = "ios" ]; then
print Y "Prepare to build Tun2Socks..."
print Y "Building Tun2Socks Framework..."
compile_tun2socks
else
print Y "No Tun2Socks will be built"
fi
print Y "Creating the Xcode project via qmake..."
$QMAKE \
VERSION=$SHORTVERSION \
BUILD_ID=$FULLVERSION \
-spec macx-xcode \
$MODE \
$VPNMODE \
$WEMODE \
$PLATFORM \
./client.pro || killProcess "Compilation failed"
print Y "Patching the xcode project..."
ruby scripts/xcode_patcher.rb "AmneziaVPN.xcodeproj" "$SHORTVERSION" "$FULLVERSION" "$OSRUBY" "$NETWORKEXTENSION" || killProcess "Failed to merge xcode with wireguard"
print G "done."
if command -v "sed" &>/dev/null; then
sed -i '' '/<key>BuildSystemType<\/key>/d' AmneziaVPN.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
sed -i '' '/<string>Original<\/string>/d' AmneziaVPN.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
fi
print G "All done!"
print Y "Opening project in Xcode..."
open AmneziaVPN.xcodeproj
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# add `@executable_path/../../Frameworks` to Runpath Search Paths in Build Settings of extension
# put to run script phase in build phases for extension
# Type a script or drag a script file from your workspace to insert its path.
cd "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/"
if [[ -d "Frameworks" ]]; then
rm -fr Frameworks
fi
+18
View File
@@ -0,0 +1,18 @@
SUPPORTED_PLATFORMS = iphoneos
TARGETED_DEVICE_FAMILY = 1,2
HEADER_SEARCH_PATHS = $(inherited) $(SRCROOT)/Source
//CLANG_CXX_LANGUAGE_STANDARD = gnu++14
//CLANG_CXX_LIBRARY = libc++
////////////////////////////////////////////////////////////////////////////////
//
// iOS-specific settings
//
IPHONEOS_DEPLOYMENT_TARGET = 9.3
SDKROOT[arch=arm64] = iphoneos
SDKROOT[arch=armv7] = iphoneos
SDKROOT[arch=armv7s] = iphoneos
VALID_ARCHS[sdk=iphoneos*] = arm64
+18
View File
@@ -0,0 +1,18 @@
SUPPORTED_PLATFORMS = iphoneos
TARGETED_DEVICE_FAMILY = 1,2
HEADER_SEARCH_PATHS = $(inherited) $(SRCROOT)/Sources
//CLANG_CXX_LANGUAGE_STANDARD = gnu++14
//CLANG_CXX_LIBRARY = libc++
////////////////////////////////////////////////////////////////////////////////
//
// iOS-specific settings
//
IPHONEOS_DEPLOYMENT_TARGET = 9.3
SDKROOT[arch=arm64] = iphoneos
SDKROOT[arch=armv7] = iphoneos
SDKROOT[arch=armv7s] = iphoneos
VALID_ARCHS[sdk=iphoneos*] = arm64
+94
View File
@@ -0,0 +1,94 @@
#!/bin/sh
# WARNING: You may have to run Clean in Xcode after changing CODE_SIGN_IDENTITY!
# Verify that $CODE_SIGN_IDENTITY is set
if [ -z "${CODE_SIGN_IDENTITY}" ] ; then
echo "CODE_SIGN_IDENTITY needs to be set for framework code-signing!"
if [ "${CONFIGURATION}" = "Release" ] ; then
exit 1
else
# Code-signing is optional for non-release builds.
exit 0
fi
fi
if [ -z "${CODE_SIGN_ENTITLEMENTS}" ] ; then
echo "CODE_SIGN_ENTITLEMENTS needs to be set for framework code-signing!"
if [ "${CONFIGURATION}" = "Release" ] ; then
exit 1
else
# Code-signing is optional for non-release builds.
exit 0
fi
fi
ITEMS=""
FRAMEWORKS_DIR="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -d "$FRAMEWORKS_DIR" ] ; then
FRAMEWORKS=$(find "${FRAMEWORKS_DIR}" -depth -type d -name "*.framework" -or -name "*.dylib" -or -name "*.bundle" | sed -e "s/\(.*framework\)/\1\/Versions\/A\//")
RESULT=$?
if [[ $RESULT != 0 ]] ; then
exit 1
fi
ITEMS="${FRAMEWORKS}"
fi
LOGINITEMS_DIR="${TARGET_BUILD_DIR}/${CONTENTS_FOLDER_PATH}/Library/LoginItems/"
if [ -d "$LOGINITEMS_DIR" ] ; then
LOGINITEMS=$(find "${LOGINITEMS_DIR}" -depth -type d -name "*.app")
RESULT=$?
if [[ $RESULT != 0 ]] ; then
exit 1
fi
ITEMS="${ITEMS}"$'\n'"${LOGINITEMS}"
fi
# Prefer the expanded name, if available.
CODE_SIGN_IDENTITY_FOR_ITEMS="${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
if [ "${CODE_SIGN_IDENTITY_FOR_ITEMS}" = "" ] ; then
# Fall back to old behavior.
CODE_SIGN_IDENTITY_FOR_ITEMS="${CODE_SIGN_IDENTITY}"
fi
echo "Identity:"
echo "${CODE_SIGN_IDENTITY_FOR_ITEMS}"
echo "Entitlements:"
echo "${CODE_SIGN_ENTITLEMENTS}"
echo "Found:"
echo "${ITEMS}"
# Change the Internal Field Separator (IFS) so that spaces in paths will not cause problems below.
SAVED_IFS=$IFS
IFS=$(echo -en "\n\b")
# Loop through all items.
for ITEM in $ITEMS;
do
echo "Signing '${ITEM}'"
codesign --force --verbose --sign "${CODE_SIGN_IDENTITY_FOR_ITEMS}" --entitlements "${CODE_SIGN_ENTITLEMENTS}" "${ITEM}"
RESULT=$?
if [[ $RESULT != 0 ]] ; then
echo "Failed to sign '${ITEM}'."
IFS=$SAVED_IFS
exit 1
fi
done
# Restore $IFS.
IFS=$SAVED_IFS
# Save it to a file in your project.
# Mine is called codesign-frameworks.sh.
# Add a “Run Script” build phase right after your “Copy Embedded Frameworks” build phase.
# You can call it “Codesign Embedded Frameworks”.
# Paste ./codesign-frameworks.sh (or whatever you called your script above) into the script editor text field.
# Build your app. All bundled frameworks will be codesigned.
# from http://stackoverflow.com/questions/7697508/how-do-you-codesign-framework-bundles-for-the-mac-app-store
+148
View File
@@ -0,0 +1,148 @@
#!/bin/bash
printv() {
if [ -t 1 ]; then
NCOLORS=$(tput colors)
if test -n "$NCOLORS" && test "$NCOLORS" -ge 8; then
NORMAL="$(tput sgr0)"
RED="$(tput setaf 1)"
GREEN="$(tput setaf 2)"
YELLOW="$(tput setaf 3)"
fi
fi
if [[ $2 = 'G' ]]; then
# shellcheck disable=SC2086
echo $1 -e "${GREEN}$3${NORMAL}"
elif [[ $2 = 'Y' ]]; then
# shellcheck disable=SC2086
echo $1 -e "${YELLOW}$3${NORMAL}"
elif [[ $2 = 'N' ]]; then
# shellcheck disable=SC2086
echo $1 -e "$3"
else
# shellcheck disable=SC2086
echo $1 -e "${RED}$3${NORMAL}"
fi
}
print() {
printv '' "$1" "$2"
}
printn() {
printv "-n" "$1" "$2"
}
error() {
printv '' R "$1"
}
XCODEBUILD="/usr/bin/xcodebuild"
WORKINGDIR=`pwd`
PATCH="/usr/bin/patch"
export PATH=$GOPATH:$PATH
prepare_to_build_vpn() {
cat $WORKINGDIR/3rd/OpenVPNAdapter/Configuration/Project.xcconfig > $WORKINGDIR/3rd/OpenVPNAdapter/Configuration/amnezia.xcconfig
cat << EOF >> $WORKINGDIR/3rd/OpenVPNAdapter/Configuration/amnezia.xcconfig
PROJECT_TEMP_DIR = $WORKINGDIR/3rd/OpenVPNAdapter/build/OpenVPNAdapter.build
CONFIGURATION_BUILD_DIR = $WORKINGDIR/3rd/OpenVPNAdapter/build/Release-iphoneos
BUILT_PRODUCTS_DIR = $WORKINGDIR/3rd/OpenVPNAdapter/build/Release-iphoneos
EOF
}
compile_openvpn_adapter() {
cd 3rd/OpenVPNAdapter
if $XCODEBUILD -scheme OpenVPNAdapter -configuration Release -xcconfig Configuration/amnezia.xcconfig -sdk iphoneos -destination 'generic/platform=iOS' -project OpenVPNAdapter.xcodeproj ; then
print Y "OpenVPNAdapter built successfully"
else
killProcess "OpenVPNAdapter build failed"
fi
cd ../../
}
prepare_to_build_ss() {
cat $WORKINGDIR/scripts/ss_ios.xcconfig > $WORKINGDIR/3rd/ShadowSocks/ss_ios.xcconfig
cat << EOF >> $WORKINGDIR/3rd/ShadowSocks/ss_ios.xcconfig
PROJECT_TEMP_DIR = $WORKINGDIR/3rd/ShadowSocks/build/ShadowSocks.build
CONFIGURATION_BUILD_DIR = $WORKINGDIR/3rd/ShadowSocks/build/Release-iphoneos
BUILT_PRODUCTS_DIR = $WORKINGDIR/3rd/ShadowSocks/build/Release-iphoneos
EOF
}
patch_ss() {
cd 3rd/ShadowSocks
}
compile_ss_frameworks() {
if $XCODEBUILD -scheme ShadowSocks -configuration Release -xcconfig ss_ios.xcconfig -sdk iphoneos -destination 'generic/platform=iOS' -project ShadowSocks.xcodeproj ; then
print Y "ShadowSocks built successfully"
else
killProcess "ShadowSocks build failed"
fi
cd ../../
}
prepare_to_build_cas() {
cat $WORKINGDIR/scripts/cas_ios.xcconfig > $WORKINGDIR/3rd/CocoaAsyncSocket/cas_ios.xcconfig
cat << EOF >> $WORKINGDIR/3rd/CocoaAsyncSocket/cas_ios.xcconfig
PROJECT_TEMP_DIR = $WORKINGDIR/3rd/CocoaAsyncSocket/build/CocoaAsyncSocket.build
CONFIGURATION_BUILD_DIR = $WORKINGDIR/3rd/CocoaAsyncSocket/build/Release-iphoneos
BUILT_PRODUCTS_DIR = $WORKINGDIR/3rd/CocoaAsyncSocket/build/Release-iphoneos
EOF
}
compile_cocoa_async_socket() {
cd 3rd/CocoaAsyncSocket
if $XCODEBUILD -scheme 'iOS Framework' -configuration Release -xcconfig cas_ios.xcconfig -sdk iphoneos -destination 'generic/platform=iOS' -project CocoaAsyncSocket.xcodeproj ; then
print Y "CocoaAsyncSocket built successfully"
else
killProcess "CocoaAsyncSocket build failed"
fi
cd ../../
}
compile_tun2socks() {
cd 3rd/outline-go-tun2socks
go get -d ./...
go get -u golang.org/x/sys
if GOOS=ios GOARCH=arm64 GOFLAGS="-tags=ios" CC=iphoneos-clang CXX=iphoneos-clang++ CGO_CFLAGS="-isysroot iphoneos -miphoneos-version-min=12.0 -fembed-bitcode -arch arm64" CGO_CXXFLAGS="-isysroot iphoneos -miphoneos-version-min=12.0 -fembed-bitcode -arch arm64" CGO_LDFLAGS="-isysroot iphoneos -miphoneos-version-min=12.0 -fembed-bitcode -arch arm64" CGO_ENABLED=1 DARWIN_SDK=iphoneos gomobile bind -a -ldflags="-w -s" -bundleid org.amnezia.tun2socks -target=ios/arm64 -tags ios -o ./build/ios/Tun2Socks.xcframework github.com/Jigsaw-Code/outline-go-tun2socks/outline/apple github.com/Jigsaw-Code/outline-go-tun2socks/outline/shadowsocks ; then
print Y "Tun2Socks built successfully"
else
print "Please check that path to bin folder with gomobile is in your PATH"
print "Usually it's in GOPATH/bin, e.g. /usr/local/go/bin"
killProcess "Tun2Socks build failed"
fi
cd ../../
}
prepare_to_build_cl() {
cat $WORKINGDIR/scripts/cl_ios.xcconfig > $WORKINGDIR/3rd/CocoaLumberjack/cl_ios.xcconfig
cat << EOF >> $WORKINGDIR/3rd/CocoaLumberjack/cl_ios.xcconfig
PROJECT_TEMP_DIR = $WORKINGDIR/3rd/CocoaLumberjack/build/CocoaLumberjack.build
CONFIGURATION_BUILD_DIR = $WORKINGDIR/3rd/CocoaLumberjack/build/Release-iphoneos
BUILT_PRODUCTS_DIR = $WORKINGDIR/3rd/CocoaLumberjack/build/Release-iphoneos
EOF
}
compile_cocoalamberjack() {
cd 3rd/CocoaLumberjack
if $XCODEBUILD -scheme 'CocoaLumberjack' -configuration Release -xcconfig cl_ios.xcconfig -sdk iphoneos -destination 'generic/platform=iOS' -project Lumberjack.xcodeproj ; then
print Y "CocoaLumberjack built successfully"
else
killProcess "CocoaLumberjack build failed"
fi
cd ../../
}
killProcess() {
if [[ "$1" ]]; then
error "$1"
else
error Failed
fi
exit 1
}
+18
View File
@@ -0,0 +1,18 @@
SUPPORTED_PLATFORMS = iphoneos
TARGETED_DEVICE_FAMILY = 1,2
HEADER_SEARCH_PATHS = $(inherited) $(SRCROOT)/PacketProcessor
//CLANG_CXX_LANGUAGE_STANDARD = gnu++14
//CLANG_CXX_LIBRARY = libc++
////////////////////////////////////////////////////////////////////////////////
//
// iOS-specific settings
//
IPHONEOS_DEPLOYMENT_TARGET = 9.3
SDKROOT[arch=arm64] = iphoneos
SDKROOT[arch=armv7] = iphoneos
SDKROOT[arch=armv7s] = iphoneos
VALID_ARCHS[sdk=iphoneos*] = arm64
+20
View File
@@ -0,0 +1,20 @@
SUPPORTED_PLATFORMS = iphoneos
TARGETED_DEVICE_FAMILY = 1,2
HEADER_SEARCH_PATHS = $(inherited) $(SRCROOT)/ShadowSocks
//HEADER_SEARCH_PATHS = $(inherited) $(SRCROOT)/ShadowSocks $(SRCROOT)/ShadowSocks/libcares/include $(SRCROOT)/ShadowSocks/libev/arm64/include $(SRCROOT)/ShadowSocks/libsodium/include $(SRCROOT)/ShadowSocks/mbedtls/include $(SRCROOT)/ShadowSocks/pcre/arm64/include $(SRCROOT)/ShadowSocks/shadowsocks-libev/include
//CLANG_CXX_LANGUAGE_STANDARD = gnu++14
//CLANG_CXX_LIBRARY = libc++
////////////////////////////////////////////////////////////////////////////////
//
// iOS-specific settings
//
IPHONEOS_DEPLOYMENT_TARGET = 9.3
SDKROOT[arch=arm64] = iphoneos
SDKROOT[arch=armv7] = iphoneos
SDKROOT[arch=armv7s] = iphoneos
VALID_ARCHS[sdk=iphoneos*] = arm64
+87
View File
@@ -0,0 +1,87 @@
diff --git a/ShadowPath/Privoxy/pcre/pcreposix.c b/ShadowPath/Privoxy/pcre/pcreposix.c
--- a/ShadowPath/Privoxy/pcre/pcreposix.c
+++ b/ShadowPath/Privoxy/pcre/pcreposix.c
@@ -146,13 +146,13 @@ message = (errcode >= (int)(sizeof(pstring)/sizeof(char *)))?
length = strlen(message) + 1;
addmessage = " at offset ";
-addlength = (preg != NULL && (int)preg->re_erroffset != -1)?
+addlength = (preg != NULL && (int)preg->re_nsub != -1)?
strlen(addmessage) + 6 : 0;
if (errbuf_size > 0)
{
if (addlength > 0 && errbuf_size >= length + addlength)
- sprintf(errbuf, "%s%s%-6d", message, addmessage, (int)preg->re_erroffset);
+ sprintf(errbuf, "%s%s%-6d", message, addmessage, (int)preg->re_nsub);
else
{
strncpy(errbuf, message, errbuf_size - 1);
@@ -173,7 +173,7 @@ return length + addlength;
void
pcre_regfree(regex_t *preg)
{
-(pcre_free)(preg->re_pcre);
+(pcre_free)(preg->re_g);
}
@@ -203,12 +203,12 @@ int options = 0;
if ((cflags & REG_ICASE) != 0) options |= PCRE_CASELESS;
if ((cflags & REG_NEWLINE) != 0) options |= PCRE_MULTILINE;
-preg->re_pcre = pcre_compile(pattern, options, &errorptr, &erroffset, NULL);
-preg->re_erroffset = erroffset;
+preg->re_g = pcre_compile(pattern, options, &errorptr, &erroffset, NULL);
+preg->re_nsub = erroffset;
-if (preg->re_pcre == NULL) return pcre_posix_error_code(errorptr);
+if (preg->re_g == NULL) return pcre_posix_error_code(errorptr);
-preg->re_nsub = pcre_info(preg->re_pcre, NULL, NULL);
+preg->re_nsub = pcre_info(preg->re_g, NULL, NULL);
return 0;
}
@@ -235,7 +235,7 @@ int *ovector = NULL;
if ((eflags & REG_NOTBOL) != 0) options |= PCRE_NOTBOL;
if ((eflags & REG_NOTEOL) != 0) options |= PCRE_NOTEOL;
-preg->re_erroffset = (size_t)(-1); /* Only has meaning after compile */
+preg->re_nsub = (size_t)(-1); /* Only has meaning after compile */
if (nmatch > 0)
{
@@ -243,7 +243,7 @@ if (nmatch > 0)
if (ovector == NULL) return REG_ESPACE;
}
-rc = pcre_exec(preg->re_pcre, NULL, string, (int)strlen(string), 0, options,
+rc = pcre_exec(preg->re_g, NULL, string, (int)strlen(string), 0, options,
ovector, nmatch * 3);
if (rc == 0) rc = nmatch; /* All captured slots were filled in */
diff --git a/ShadowPath/shadowsocks-libev/src/http.h b/ShadowPath/shadowsocks-libev/src/http.h
index 914815a..e312dd3 100644
--- a/ShadowPath/shadowsocks-libev/src/http.h
+++ b/ShadowPath/shadowsocks-libev/src/http.h
@@ -29,6 +29,6 @@
#include <stdio.h>
#include "protocol.h"
-const protocol_t *const http_protocol;
+extern const protocol_t *const http_protocol;
#endif
diff --git a/ShadowPath/shadowsocks-libev/src/tls.h b/ShadowPath/shadowsocks-libev/src/tls.h
index 3998913..ddbee11 100644
--- a/ShadowPath/shadowsocks-libev/src/tls.h
+++ b/ShadowPath/shadowsocks-libev/src/tls.h
@@ -28,6 +28,6 @@
#include "protocol.h"
-const protocol_t *const tls_protocol;
+extern const protocol_t *const tls_protocol;
#endif
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/ruby
require 'xcodeproj'
class SSPatcher
attr :project
attr :target_main
def run(file)
open_project file
open_target_main
patch_main_target
@project.save
end
def open_project(file)
@project = Xcodeproj::Project.open(file)
die 'Failed to open the project file: ' + file if @project.nil?
end
def open_target_main
@target_main = @project.native_targets
.select { |target| target.name == 'ShadowSocks' }
.first
return @target_main if not @target_main.nil?
die 'Unable to open ShadowSocks target'
end
def patch_main_target
@target_main.resources_build_phase.files.each do |f|
puts f.display_name
if f.display_name === "LICENSE"
f.remove_from_project
end
end
end
def die(msg)
print $msg
exit 1
end
end
if ARGV.length < 1
puts "Usage: <script> project_file"
exit 1
end
r = SSPatcher.new
r.run ARGV[0]
exit 0
+624
View File
@@ -0,0 +1,624 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
require 'xcodeproj'
class XCodeprojPatcher
attr :project
attr :target_main
attr :target_extension
def run(file, shortVersion, fullVersion, platform, networkExtension, configHash)
open_project file
setup_project
open_target_main
die 'IOS requires networkExtension mode' if not networkExtension and platform == 'ios'
group = @project.main_group.new_group('Configuration')
@configFile = group.new_file('xcode.xconfig')
setup_target_main shortVersion, fullVersion, platform, networkExtension, configHash
if networkExtension
setup_target_extension shortVersion, fullVersion, platform, configHash
setup_target_gobridge platform
else
setup_target_wireguardgo
setup_target_wireguardtools
end
setup_target_balrog if platform == 'macos'
@project.save
end
def open_project(file)
@project = Xcodeproj::Project.open(file)
die 'Failed to open the project file: ' + file if @project.nil?
end
def setup_project
@project.build_configurations.each do |config|
config.build_settings['SYMROOT'] = 'build'
end
end
def open_target_main
@target_main = @project.targets.find { |target| target.to_s == 'AmneziaVPN' }
return @target_main if not @target_main.nil?
die 'Unable to open AmneziaVPN target'
end
def setup_target_main(shortVersion, fullVersion, platform, networkExtension, configHash)
@target_main.build_configurations.each do |config|
config.base_configuration_reference = @configFile
config.build_settings['LD_RUNPATH_SEARCH_PATHS'] ||= '"$(inherited) @executable_path/../Frameworks"'
config.build_settings['SWIFT_VERSION'] ||= '5.0'
config.build_settings['CLANG_ENABLE_MODULES'] ||= 'YES'
config.build_settings['SWIFT_OBJC_BRIDGING_HEADER'] ||= 'macos/app/WireGuard-Bridging-Header.h'
config.build_settings['FRAMEWORK_SEARCH_PATHS'] ||= [
"$(inherited)",
"$(PROJECT_DIR)/3rd",
"$(PROJECT_DIR)/3rd/OpenVPNAdapter/build/Release-iphoneos",
"$(PROJECT_DIR)/3rd/ShadowSocks/build/Release-iphoneos",
"$(PROJECT_DIR)/3rd/outline-go-tun2socks/build/ios",
"${PROJECT_DIR}/3rd/CocoaAsyncSocket/build/Release-iphoneos",
]
# Versions and names
config.build_settings['MARKETING_VERSION'] ||= shortVersion
config.build_settings['CURRENT_PROJECT_VERSION'] ||= fullVersion
config.build_settings['PRODUCT_BUNDLE_IDENTIFIER'] = configHash['APP_ID_MACOS'] if platform == 'macos'
config.build_settings['PRODUCT_BUNDLE_IDENTIFIER'] = configHash['APP_ID_IOS'] if platform == 'ios'
config.build_settings['PRODUCT_NAME'] = 'AmneziaVPN'
config.build_settings['SYMROOT'] = 'build'
config.build_settings['ASSETCATALOG_COMPILER_APPICON_NAME'] = 'AppIcon'
# other config
config.build_settings['INFOPLIST_FILE'] ||= platform + '/app/Info.plist'
if platform == 'ios'
config.build_settings['CODE_SIGN_ENTITLEMENTS'] ||= 'ios/app/main.entitlements'
elsif networkExtension
config.build_settings['CODE_SIGN_ENTITLEMENTS'] ||= 'macos/app/app.entitlements'
else
config.build_settings['CODE_SIGN_ENTITLEMENTS'] ||= 'macos/app/daemon.entitlements'
end
config.build_settings['CODE_SIGN_IDENTITY'] ||= 'Apple Development'
config.build_settings['ENABLE_BITCODE'] ||= 'NO' if platform == 'ios'
config.build_settings['SDKROOT'] = 'iphoneos' if platform == 'ios'
config.build_settings['SWIFT_PRECOMPILE_BRIDGING_HEADER'] = 'NO' if platform == 'ios'
config.build_settings['PATH'] = '${PATH}:/opt/local/bin:/usr/local/go/bin:/usr/local/bin:/opt/homebrew/bin'
groupId = "";
if (platform == 'macos')
groupId = configHash['DEVELOPMENT_TEAM'] + "." + configHash['GROUP_ID_MACOS']
config.build_settings['APP_ID_MACOS'] ||= configHash['APP_ID_MACOS']
else
groupId = configHash['GROUP_ID_IOS']
config.build_settings['GROUP_ID_IOS'] ||= configHash['GROUP_ID_IOS']
# Force xcode to not set QT_LIBRARY_SUFFIX to "_debug", which causes crash
config.build_settings['QT_LIBRARY_SUFFIX'] = ""
end
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'GROUP_ID=\"' + groupId + '\"',
"VPN_NE_BUNDLEID=\\\"" + (platform == 'macos' ? configHash['NETEXT_ID_MACOS'] : configHash['NETEXT_ID_IOS']) + "\\\"",
]
if config.name == 'Release'
config.build_settings['SWIFT_OPTIMIZATION_LEVEL'] ||= '-Onone'
end
end
# add assets to main target
assets_group = @project.main_group.new_group('Assets')
assets_path = 'ios/Media.xcassets'
assets_ref = assets_group.new_reference(assets_path, :group)
@target_main.add_resources([assets_ref])
if networkExtension
# WireGuard group
group = @project.main_group.new_group('WireGuard')
version_file_path = platform == 'ios' ? '3rd/wireguard-apple/Sources/WireGuardKitGo/wireguard-go-version.h' : 'macos/gobridge/wireguard-go-version.h'
[
version_file_path,
'3rd/wireguard-apple/Sources/Shared/Keychain.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/IPAddressRange.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/InterfaceConfiguration.swift',
'3rd/wireguard-apple/Sources/Shared/Model/NETunnelProviderProtocol+Extension.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/TunnelConfiguration.swift',
'3rd/wireguard-apple/Sources/Shared/Model/TunnelConfiguration+WgQuickConfig.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/Endpoint.swift',
'3rd/wireguard-apple/Sources/Shared/Model/String+ArrayConversion.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/PeerConfiguration.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/DNSServer.swift',
'3rd/wireguard-apple/Sources/WireGuardApp/LocalizationHelper.swift',
'3rd/wireguard-apple/Sources/Shared/FileManager+Extension.swift',
'3rd/wireguard-apple/Sources/WireGuardKitC/x25519.c',
'3rd/wireguard-apple/Sources/WireGuardKit/PrivateKey.swift',
].each { |filename|
file = group.new_file(filename)
@target_main.add_file_references([file])
}
# @target_main + swift integration
group = @project.main_group.new_group('SwiftMainIntegration')
[
'platforms/ios/iosvpnprotocol.swift',
'platforms/ios/ioslogger.swift',
].each { |filename|
file = group.new_file(filename)
@target_main.add_file_references([file])
}
end
if(platform == 'ios')
frameworks_group = @project.groups.find { |group| group.display_name == 'Frameworks' }
frameworks_build_phase = @target_main.build_phases.find { |build_phase| build_phase.to_s == 'FrameworksBuildPhase' }
embed_frameworks_build_phase = project.new(Xcodeproj::Project::Object::PBXCopyFilesBuildPhase)
embed_frameworks_build_phase.name = 'Embed Frameworks'
embed_frameworks_build_phase.symbol_dst_subfolder_spec = :frameworks
@target_main.build_phases << embed_frameworks_build_phase
framework_ref = frameworks_group.new_file('3rd/OpenVPNAdapter/build/Release-iphoneos/OpenVPNAdapter.framework')
build_file = embed_frameworks_build_phase.add_file_reference(framework_ref)
frameworks_build_phase.add_file_reference(framework_ref)
build_file.settings = { 'ATTRIBUTES' => ['CodeSignOnCopy', 'RemoveHeadersOnCopy'] }
end
end
def setup_target_extension(shortVersion, fullVersion, platform, configHash)
@target_extension = @project.new_target(:app_extension, 'WireGuardNetworkExtension', platform == 'macos' ? :osx : :ios)
@target_extension.build_configurations.each do |config|
config.base_configuration_reference = @configFile
config.build_settings['LD_RUNPATH_SEARCH_PATHS'] ||= [
'$(inherited)',
'@executable_path/../Frameworks',
'@executable_path/../../Frameworks'
]
config.build_settings['SWIFT_VERSION'] ||= '5.0'
config.build_settings['CLANG_ENABLE_MODULES'] ||= 'YES'
config.build_settings['SWIFT_OBJC_BRIDGING_HEADER'] ||= 'macos/networkextension/WireGuardNetworkExtension-Bridging-Header.h'
config.build_settings['SWIFT_PRECOMPILE_BRIDGING_HEADER'] = 'NO'
config.build_settings['APPLICATION_EXTENSION_API_ONLY'] = 'YES'
config.build_settings['STRIP_BITCODE_FROM_COPIED_FILES'] = 'NO'
config.build_settings['FRAMEWORK_SEARCH_PATHS'] ||= [
"$(inherited)",
"$(PROJECT_DIR)/3rd",
"$(PROJECT_DIR)/3rd/OpenVPNAdapter/build/Release-iphoneos",
"$(PROJECT_DIR)/3rd/libleaf/lib",
"$(PROJECT_DIR)/3rd/ShadowSocks/build/Release-iphoneos",
"$(PROJECT_DIR)/3rd/outline-go-tun2socks/build/ios",
"${PROJECT_DIR}/3rd/CocoaAsyncSocket/build/Release-iphoneos",
]
# Versions and names
config.build_settings['MARKETING_VERSION'] ||= shortVersion
config.build_settings['CURRENT_PROJECT_VERSION'] ||= fullVersion
config.build_settings['PRODUCT_BUNDLE_IDENTIFIER'] ||= configHash['NETEXT_ID_MACOS'] if platform == 'macos'
config.build_settings['PRODUCT_BUNDLE_IDENTIFIER'] ||= configHash['NETEXT_ID_IOS'] if platform == 'ios'
config.build_settings['PRODUCT_NAME'] = 'WireGuardNetworkExtension'
# other configs
config.build_settings['INFOPLIST_FILE'] ||= 'macos/networkextension/Info.plist'
config.build_settings['CODE_SIGN_ENTITLEMENTS'] ||= platform + '/networkextension/AmneziaVPNNetworkExtension.entitlements'
config.build_settings['CODE_SIGN_IDENTITY'] = 'Apple Development'
if platform == 'ios'
config.build_settings['ENABLE_BITCODE'] ||= 'NO'
config.build_settings['SDKROOT'] = 'iphoneos'
config.build_settings['OTHER_LDFLAGS'] ||= [
"-stdlib=libc++",
"-Wl,-rpath,@executable_path/Frameworks",
"-framework",
"AssetsLibrary",
"-framework",
"MobileCoreServices",
"-lm",
"-framework",
"UIKit",
"-lz",
"-framework",
"OpenGLES",
]
config.build_settings['PATH'] = '${PATH}:/opt/local/bin:/usr/local/go/bin'
end
groupId = "";
if (platform == 'macos')
groupId = configHash['DEVELOPMENT_TEAM'] + "." + configHash['GROUP_ID_MACOS']
else
groupId = configHash['GROUP_ID_IOS']
end
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
# This is needed to compile the iosglue without Qt.
'NETWORK_EXTENSION=1',
'GROUP_ID=\"' + groupId + '\"',
]
if config.name == 'Release'
config.build_settings['SWIFT_OPTIMIZATION_LEVEL'] ||= '-Onone'
end
end
group = @project.main_group.new_group('WireGuardExtension')
[
'3rd/wireguard-apple/Sources/WireGuardKit/WireGuardAdapter.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/PacketTunnelSettingsGenerator.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/DNSResolver.swift',
'3rd/wireguard-apple/Sources/WireGuardNetworkExtension/ErrorNotifier.swift',
'3rd/wireguard-apple/Sources/Shared/Keychain.swift',
'3rd/wireguard-apple/Sources/Shared/Model/TunnelConfiguration+WgQuickConfig.swift',
'3rd/wireguard-apple/Sources/Shared/Model/NETunnelProviderProtocol+Extension.swift',
'3rd/wireguard-apple/Sources/Shared/Model/String+ArrayConversion.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/TunnelConfiguration.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/IPAddressRange.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/Endpoint.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/DNSServer.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/InterfaceConfiguration.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/PeerConfiguration.swift',
'3rd/wireguard-apple/Sources/Shared/FileManager+Extension.swift',
'3rd/wireguard-apple/Sources/WireGuardKitC/x25519.c',
'3rd/wireguard-apple/Sources/WireGuardKit/Array+ConcurrentMap.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/IPAddress+AddrInfo.swift',
'3rd/wireguard-apple/Sources/WireGuardKit/PrivateKey.swift',
].each { |filename|
file = group.new_file(filename)
@target_extension.add_file_references([file])
}
# @target_extension + swift integration
group = @project.main_group.new_group('SwiftExtensionIntegration')
[
'platforms/ios/iostunnel.swift',
'platforms/ios/ioslogger.swift',
'platforms/ios/iosinterface.swift',
'platforms/ios/iosglue.mm',
].each { |filename|
file = group.new_file(filename)
@target_extension.add_file_references([file])
}
frameworks_group = @project.groups.find { |group| group.display_name == 'Frameworks' }
frameworks_build_phase = @target_extension.build_phases.find { |build_phase| build_phase.to_s == 'FrameworksBuildPhase' }
frameworks_build_phase.clear
framework_ref = frameworks_group.new_file('libwg-go.a')
frameworks_build_phase.add_file_reference(framework_ref)
framework_ref = frameworks_group.new_file('NetworkExtension.framework')
frameworks_build_phase.add_file_reference(framework_ref)
# This fails: @target_main.add_dependency @target_extension
container_proxy = @project.new(Xcodeproj::Project::PBXContainerItemProxy)
container_proxy.container_portal = @project.root_object.uuid
container_proxy.proxy_type = Xcodeproj::Constants::PROXY_TYPES[:native_target]
container_proxy.remote_global_id_string = @target_extension.uuid
container_proxy.remote_info = @target_extension.name
dependency = @project.new(Xcodeproj::Project::PBXTargetDependency)
dependency.name = @target_extension.name
dependency.target = @target_main
dependency.target_proxy = container_proxy
@target_main.dependencies << dependency
copy_appex = @target_main.new_copy_files_build_phase
copy_appex.name = 'Copy Network-Extension plugin'
copy_appex.symbol_dst_subfolder_spec = :plug_ins
appex_file = copy_appex.add_file_reference @target_extension.product_reference
appex_file.settings = { "ATTRIBUTES" => ['RemoveHeadersOnCopy'] }
end
def setup_target_gobridge(platform)
target_gobridge = legacy_target = @project.new(Xcodeproj::Project::PBXLegacyTarget)
bridge_platform = platform == 'ios' ? 'iOS' : 'macOS'
target_gobridge.build_working_directory = platform == 'ios' ? '3rd/wireguard-apple/Sources/WireGuardKitGo' : 'macos/gobridge'
target_gobridge.build_tool_path = 'make'
target_gobridge.pass_build_settings_in_environment = '1'
target_gobridge.build_arguments_string = '$(ACTION)'
target_gobridge.name = "WireGuardGoBridge<#{bridge_platform}>"
target_gobridge.product_name = "WireGuardGoBridge<#{bridge_platform}>"
@project.targets << target_gobridge
@target_extension.add_dependency target_gobridge
end
def setup_target_balrog
target_balrog = legacy_target = @project.new(Xcodeproj::Project::PBXLegacyTarget)
target_balrog.build_working_directory = 'balrog'
target_balrog.build_tool_path = 'make'
target_balrog.pass_build_settings_in_environment = '1'
target_balrog.build_arguments_string = '$(ACTION)'
target_balrog.name = 'WireGuardBalrog'
target_balrog.product_name = 'WireGuardBalrog'
@project.targets << target_balrog
frameworks_group = @project.groups.find { |group| group.display_name == 'Frameworks' }
frameworks_build_phase = @target_main.build_phases.find { |build_phase| build_phase.to_s == 'FrameworksBuildPhase' }
framework_ref = frameworks_group.new_file('balrog/balrog.a')
frameworks_build_phase.add_file_reference(framework_ref)
# This fails: @target_main.add_dependency target_balrog
container_proxy = @project.new(Xcodeproj::Project::PBXContainerItemProxy)
container_proxy.container_portal = @project.root_object.uuid
container_proxy.proxy_type = Xcodeproj::Constants::PROXY_TYPES[:native_target]
container_proxy.remote_global_id_string = target_balrog.uuid
container_proxy.remote_info = target_balrog.name
dependency = @project.new(Xcodeproj::Project::PBXTargetDependency)
dependency.name = target_balrog.name
dependency.target = @target_main
dependency.target_proxy = container_proxy
@target_main.dependencies << dependency
end
def setup_target_wireguardtools
target_wireguardtools = legacy_target = @project.new(Xcodeproj::Project::PBXLegacyTarget)
target_wireguardtools.build_working_directory = '3rd/wireguard-tools/src'
target_wireguardtools.build_tool_path = 'make'
target_wireguardtools.pass_build_settings_in_environment = '1'
target_wireguardtools.build_arguments_string = '$(ACTION)'
target_wireguardtools.name = 'WireGuardTools'
target_wireguardtools.product_name = 'WireGuardTools'
@project.targets << target_wireguardtools
# This fails: @target_main.add_dependency target_wireguardtools
container_proxy = @project.new(Xcodeproj::Project::PBXContainerItemProxy)
container_proxy.container_portal = @project.root_object.uuid
container_proxy.proxy_type = Xcodeproj::Constants::PROXY_TYPES[:native_target]
container_proxy.remote_global_id_string = target_wireguardtools.uuid
container_proxy.remote_info = target_wireguardtools.name
dependency = @project.new(Xcodeproj::Project::PBXTargetDependency)
dependency.name = target_wireguardtools.name
dependency.target = @target_main
dependency.target_proxy = container_proxy
@target_main.dependencies << dependency
copy_wireguardTools = @target_main.new_copy_files_build_phase
copy_wireguardTools.name = 'Copy wireguard-tools'
copy_wireguardTools.symbol_dst_subfolder_spec = :wrapper
copy_wireguardTools.dst_path = 'Contents/Resources/utils'
group = @project.main_group.new_group('WireGuardTools')
file = group.new_file '3rd/wireguard-tools/src/wg'
wireguardTools_file = copy_wireguardTools.add_file_reference file
wireguardTools_file.settings = { "ATTRIBUTES" => ['RemoveHeadersOnCopy'] }
end
def setup_target_wireguardgo
target_wireguardgo = legacy_target = @project.new(Xcodeproj::Project::PBXLegacyTarget)
target_wireguardgo.build_working_directory = '3rd/wireguard-go'
target_wireguardgo.build_tool_path = 'make'
target_wireguardgo.pass_build_settings_in_environment = '1'
target_wireguardgo.build_arguments_string = '$(ACTION)'
target_wireguardgo.name = 'WireGuardGo'
target_wireguardgo.product_name = 'WireGuardGo'
@project.targets << target_wireguardgo
# This fails: @target_main.add_dependency target_wireguardgo
container_proxy = @project.new(Xcodeproj::Project::PBXContainerItemProxy)
container_proxy.container_portal = @project.root_object.uuid
container_proxy.proxy_type = Xcodeproj::Constants::PROXY_TYPES[:native_target]
container_proxy.remote_global_id_string = target_wireguardgo.uuid
container_proxy.remote_info = target_wireguardgo.name
dependency = @project.new(Xcodeproj::Project::PBXTargetDependency)
dependency.name = target_wireguardgo.name
dependency.target = @target_main
dependency.target_proxy = container_proxy
@target_main.dependencies << dependency
copy_wireguardGo = @target_main.new_copy_files_build_phase
copy_wireguardGo.name = 'Copy wireguard-go'
copy_wireguardGo.symbol_dst_subfolder_spec = :wrapper
copy_wireguardGo.dst_path = 'Contents/Resources/utils'
group = @project.main_group.new_group('WireGuardGo')
file = group.new_file '3rd/wireguard-go/wireguard-go'
wireguardGo_file = copy_wireguardGo.add_file_reference file
wireguardGo_file.settings = { "ATTRIBUTES" => ['RemoveHeadersOnCopy'] }
end
def setup_target_loginitem(shortVersion, fullVersion, configHash)
@target_loginitem = @project.new_target(:application, 'AmneziaVPNLoginItem', :osx)
@target_loginitem.build_configurations.each do |config|
config.base_configuration_reference = @configFile
config.build_settings['LD_RUNPATH_SEARCH_PATHS'] ||= '"$(inherited) @executable_path/../Frameworks"'
# Versions and names
config.build_settings['MARKETING_VERSION'] ||= shortVersion
config.build_settings['CURRENT_PROJECT_VERSION'] ||= fullVersion
config.build_settings['PRODUCT_BUNDLE_IDENTIFIER'] ||= configHash['LOGIN_ID_MACOS']
config.build_settings['PRODUCT_NAME'] = 'AmneziaVPNLoginItem'
# other configs
config.build_settings['INFOPLIST_FILE'] ||= 'macos/loginitem/Info.plist'
config.build_settings['CODE_SIGN_ENTITLEMENTS'] ||= 'macos/loginitem/MozillaVPNLoginItem.entitlements' #TODO need to check this
config.build_settings['CODE_SIGN_IDENTITY'] = 'Apple Development'
config.build_settings['SKIP_INSTALL'] = 'YES'
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'APP_ID=\"' + configHash['APP_ID_MACOS'] + '\"',
]
if config.name == 'Release'
config.build_settings['SWIFT_OPTIMIZATION_LEVEL'] ||= '-Onone'
end
end
group = @project.main_group.new_group('LoginItem')
[
'macos/loginitem/main.m',
].each { |filename|
file = group.new_file(filename)
@target_loginitem.add_file_references([file])
}
# This fails: @target_main.add_dependency @target_loginitem
container_proxy = @project.new(Xcodeproj::Project::PBXContainerItemProxy)
container_proxy.container_portal = @project.root_object.uuid
container_proxy.proxy_type = Xcodeproj::Constants::PROXY_TYPES[:native_target]
container_proxy.remote_global_id_string = @target_loginitem.uuid
container_proxy.remote_info = @target_loginitem.name
dependency = @project.new(Xcodeproj::Project::PBXTargetDependency)
dependency.name = @target_loginitem.name
dependency.target = @target_main
dependency.target_proxy = container_proxy
@target_main.dependencies << dependency
copy_app = @target_main.new_copy_files_build_phase
copy_app.name = 'Copy LoginItem'
copy_app.symbol_dst_subfolder_spec = :wrapper
copy_app.dst_path = 'Contents/Library/LoginItems'
app_file = copy_app.add_file_reference @target_loginitem.product_reference
app_file.settings = { "ATTRIBUTES" => ['RemoveHeadersOnCopy'] }
end
def setup_target_nativemessaging(shortVersion, fullVersion, configHash)
@target_nativemessaging = @project.new_target(:application, 'AmneziaVPNNativeMessaging', :osx)
@target_nativemessaging.build_configurations.each do |config|
config.base_configuration_reference = @configFile
config.build_settings['LD_RUNPATH_SEARCH_PATHS'] ||= '"$(inherited) @executable_path/../Frameworks"'
# Versions and names
config.build_settings['MARKETING_VERSION'] ||= shortVersion
config.build_settings['CURRENT_PROJECT_VERSION'] ||= fullVersion
config.build_settings['PRODUCT_BUNDLE_IDENTIFIER'] ||= configHash['NATIVEMESSAGING_ID_MACOS']
config.build_settings['PRODUCT_NAME'] = 'AmneziaVPNNativeMessaging'
# other configs
config.build_settings['INFOPLIST_FILE'] ||= 'macos/nativeMessaging/Info.plist'
config.build_settings['CODE_SIGN_ENTITLEMENTS'] ||= 'macos/nativeMessaging/MozillaVPNNativeMessaging.entitlements'
config.build_settings['CODE_SIGN_IDENTITY'] = 'Apple Development'
config.build_settings['SKIP_INSTALL'] = 'YES'
end
group = @project.main_group.new_group('NativeMessaging')
[
'extension/app/constants.h',
'extension/app/handler.cpp',
'extension/app/handler.h',
'extension/app/json.hpp',
'extension/app/logger.cpp',
'extension/app/logger.h',
'extension/app/main.cpp',
'extension/app/vpnconnection.cpp',
'extension/app/vpnconnection.h',
].each { |filename|
file = group.new_file(filename)
@target_nativemessaging.add_file_references([file])
}
# This fails: @target_main.add_dependency @target_nativemessaging
container_proxy = @project.new(Xcodeproj::Project::PBXContainerItemProxy)
container_proxy.container_portal = @project.root_object.uuid
container_proxy.proxy_type = Xcodeproj::Constants::PROXY_TYPES[:native_target]
container_proxy.remote_global_id_string = @target_nativemessaging.uuid
container_proxy.remote_info = @target_nativemessaging.name
dependency = @project.new(Xcodeproj::Project::PBXTargetDependency)
dependency.name = @target_nativemessaging.name
dependency.target = @target_main
dependency.target_proxy = container_proxy
@target_main.dependencies << dependency
copy_app = @target_main.new_copy_files_build_phase
copy_app.name = 'Copy LoginItem'
copy_app.symbol_dst_subfolder_spec = :wrapper
copy_app.dst_path = 'Contents/Library/NativeMessaging'
app_file = copy_app.add_file_reference @target_nativemessaging.product_reference
app_file.settings = { "ATTRIBUTES" => ['RemoveHeadersOnCopy'] }
copy_nativeMessagingManifest = @target_main.new_copy_files_build_phase
copy_nativeMessagingManifest.name = 'Copy native messaging manifest'
copy_nativeMessagingManifest.symbol_dst_subfolder_spec = :wrapper
copy_nativeMessagingManifest.dst_path = 'Contents/Resources/utils'
group = @project.main_group.new_group('WireGuardHelper')
file = group.new_file 'extension/app/manifests/macos/mozillavpn.json' #TODO Need to check this
nativeMessagingManifest_file = copy_nativeMessagingManifest.add_file_reference file
nativeMessagingManifest_file.settings = { "ATTRIBUTES" => ['RemoveHeadersOnCopy'] }
end
def die(msg)
print $msg
exit 1
end
end
if ARGV.length < 4 || (ARGV[3] != "ios" && ARGV[3] != "macos")
puts "Usage: <script> project_file shortVersion fullVersion ios/macos"
exit 1
end
if !File.exist?("xcode.xconfig")
puts "xcode.xconfig file is required! See the template file."
exit 1
end
config = Hash.new
configFile = File.read("xcode.xconfig").split("\n")
configFile.each { |line|
next if line[0] == "#"
if line.include? "="
keys = line.split("=")
config[keys[0].strip] = keys[1].strip
end
}
platform = "macos"
platform = "ios" if ARGV[3] == "ios"
networkExtension = true if ARGV[4] == "1"
r = XCodeprojPatcher.new
r.run ARGV[0], ARGV[1], ARGV[2], platform, networkExtension, config
exit 0
+1 -1
View File
@@ -1,4 +1,4 @@
#include "version.h"
#include "defines.h"
#include "settings.h"
#include "utilities.h"
+1 -1
View File
@@ -1,7 +1,7 @@
#include "AppSettingsLogic.h"
#include "logger.h"
#include "version.h"
#include "defines.h"
#include "ui/qautostart.h"
#include "ui/uilogic.h"
+1 -1
View File
@@ -2,7 +2,7 @@
#include <QMessageBox>
#include "version.h"
#include "defines.h"
#include "core/errorstrings.h"
#include "core/servercontroller.h"
#include "ui/models/clientManagementModel.h"
@@ -2,7 +2,7 @@
#include <QMessageBox>
#include "version.h"
#include "defines.h"
#include "core/errorstrings.h"
#include "core/servercontroller.h"
#include "ui/pages_logic/ClientInfoLogic.h"
@@ -1,6 +1,6 @@
#include "NetworkSettingsLogic.h"
#include "version.h"
#include "defines.h"
#include "utilities.h"
#include "settings.h"
@@ -1,5 +1,5 @@
#include "ServerConfiguringProgressLogic.h"
#include "version.h"
#include "defines.h"
#include "core/errorstrings.h"
#include <QTimer>
#include <QEventLoop>
@@ -14,7 +14,7 @@
#include "configurators/ikev2_configurator.h"
#include "configurators/ssh_configurator.h"
#include "version.h"
#include "defines.h"
#include "core/defs.h"
#include "core/errorstrings.h"
#include "core/servercontroller.h"
+1 -1
View File
@@ -7,7 +7,7 @@
#include <QTimer>
#include <functional>
#include "../uilogic.h"
#include "version.h"
#include "defines.h"
#include <configurators/vpn_configurator.h>
+1 -1
View File
@@ -15,7 +15,7 @@
#include <QIcon>
#include <QWindow>
#include "version.h"
#include "defines.h"
SystemTrayNotificationHandler::SystemTrayNotificationHandler(QObject* parent) :
+1 -1
View File
@@ -34,7 +34,7 @@
#include "ui/qautostart.h"
#include "logger.h"
#include "version.h"
#include "defines.h"
#include "uilogic.h"
#include "utilities.h"
#include "vpnconnection.h"
+1 -1
View File
@@ -8,7 +8,7 @@
#include <QRegularExpression>
#include <QStandardPaths>
#include "version.h"
#include "defines.h"
#include "utilities.h"
QString Utils::getRandomString(int len)
+6
View File
@@ -0,0 +1,6 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# current version 2.0.10
!defined(VERSION, var):VERSION = 2.0.10
+2
View File
@@ -0,0 +1,2 @@
# current build 6
!defined(BUILDVERSION, var):BUILDVERSION = 7
+5
View File
@@ -0,0 +1,5 @@
DEVELOPMENT_TEAM = X7UJ388FXK
GROUP_ID_IOS = group.org.amnezia.AmneziaVPN
APP_ID_IOS = org.amnezia.AmneziaVPN
NETEXT_ID_IOS = org.amnezia.AmneziaVPN.network-extension
+1 -3
View File
@@ -79,8 +79,6 @@ rm -f $INSTALLER_DATA_DIR/data.7z
ldd $CQTDEPLOYER_DIR/bin/binarycreator
cp -r $PROJECT_DIR/deploy/installer $BUILD_DIR
$CQTDEPLOYER_DIR/binarycreator.sh --offline-only -v -c $BUILD_DIR/installer/config/linux.xml -p $BUILD_DIR/installer/packages -f $PROJECT_DIR/deploy/AmneziaVPN_Linux_Installer
$CQTDEPLOYER_DIR/binarycreator.sh --offline-only -v -c $PROJECT_DIR/deploy/installer/config/linux.xml -p $PROJECT_DIR/deploy/installer/packages/ -f $PROJECT_DIR/deploy/AmneziaVPN_Linux_Installer
Binary file not shown.
-23
View File
@@ -1,23 +0,0 @@
if(WIN32)
set(RootDir "@RootDir@")
configure_file(
${CMAKE_CURRENT_LIST_DIR}/config/windows.xml.in
${CMAKE_BINARY_DIR}/installer/config/windows.xml
)
elseif(APPLE AND NOT IOS)
configure_file(
${CMAKE_CURRENT_LIST_DIR}/config/macos.xml.in
${CMAKE_BINARY_DIR}/installer/config/macos.xml
)
elseif(LINUX)
set(ApplicationsDir "@ApplicationsDir@")
configure_file(
${CMAKE_CURRENT_LIST_DIR}/config/linux.xml.in
${CMAKE_BINARY_DIR}/installer/config/linux.xml
)
endif()
configure_file(
${CMAKE_CURRENT_LIST_DIR}/packages/org.amneziavpn.package/meta/package.xml.in
${CMAKE_BINARY_DIR}/installer/packages/org.amneziavpn.package/meta/package.xml
)
@@ -18,10 +18,10 @@
<SupportsModify>false</SupportsModify>
<DisableAuthorizationFallback>true</DisableAuthorizationFallback>
<RemoteRepositories>
<Repository>
<Url>https://amneziavpn.org/updates/linux</Url>
<Enabled>true</Enabled>
<DisplayName>AmneziaVPN - repository for Linux</DisplayName>
</Repository>
<Repository>
<Url>https://amneziavpn.org/updates/linux</Url>
<Enabled>true</Enabled>
<DisplayName>AmneziaVPN - repository for Linux</DisplayName>
</Repository>
</RemoteRepositories>
</Installer>
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Installer>
<Name>AmneziaVPN</Name>
<Version>@CMAKE_PROJECT_VERSION@</Version>
<Version>1.6.0.0</Version>
<Title>AmneziaVPN</Title>
<Publisher>AmneziaVPN</Publisher>
<StartMenuDir>AmneziaVPN</StartMenuDir>
@@ -18,10 +18,10 @@
<SupportsModify>false</SupportsModify>
<DisableAuthorizationFallback>true</DisableAuthorizationFallback>
<RemoteRepositories>
<Repository>
<Url>https://amneziavpn.org/updates/macos</Url>
<Enabled>true</Enabled>
<DisplayName>AmneziaVPN - repository for macOS</DisplayName>
</Repository>
<Repository>
<Url>https://amneziavpn.org/updates/macos</Url>
<Enabled>true</Enabled>
<DisplayName>AmneziaVPN - repository for macOS</DisplayName>
</Repository>
</RemoteRepositories>
</Installer>
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Installer>
<Name>AmneziaVPN</Name>
<Version>@CMAKE_PROJECT_VERSION@</Version>
<Version>2.0.0.0</Version>
<Title>AmneziaVPN</Title>
<Publisher>AmneziaVPN</Publisher>
<StartMenuDir>AmneziaVPN</StartMenuDir>
@@ -2,10 +2,11 @@
<Package>
<DisplayName>AmneziaVPN</DisplayName>
<Description>Installation package for AmneziaVPN</Description>
<Version>@CMAKE_PROJECT_VERSION@</Version>
<ReleaseDate>@RELEASE_DATE@</ReleaseDate>
<Version>2.0.0.0</Version>
<ReleaseDate>2022-02-02</ReleaseDate>
<Default>true</Default>
<ForcedInstallation>true</ForcedInstallation>
<RequiresAdminRights>true</RequiresAdminRights>
<Script>componentscript.js</Script>
</Package>
+13
View File
@@ -0,0 +1,13 @@
TEMPLATE=lib
CONFIG += qt dll qtservice-buildlib
mac:CONFIG += absolute_library_soname
win32|mac:!wince*:!win32-msvc:!macx-xcode:CONFIG += debug_and_release build_all
include(../src/qtservice.pri)
TARGET = $$QTSERVICE_LIBNAME
DESTDIR = $$QTSERVICE_LIBDIR
win32 {
DLLDESTDIR = $$[QT_INSTALL_BINS]
QMAKE_DISTCLEAN += $$[QT_INSTALL_BINS]\\$${QTSERVICE_LIBNAME}.dll
}
target.path = $$DESTDIR
INSTALLS += target
+10
View File
@@ -0,0 +1,10 @@
#exists(config.pri):infile(config.pri, SOLUTIONS_LIBRARY, yes): CONFIG += qtservice-uselib
TEMPLATE += fakelib
QTSERVICE_LIBNAME = QtSolutions_Service-head
CONFIG(debug, debug|release) {
mac:QTSERVICE_LIBNAME = $$member(QTSERVICE_LIBNAME, 0)_debug
else:win32:QTSERVICE_LIBNAME = $$member(QTSERVICE_LIBNAME, 0)d
}
TEMPLATE -= fakelib
QTSERVICE_LIBDIR = $$PWD/lib
unix:qtservice-uselib:!qtservice-buildlib:QMAKE_RPATHDIR += $$QTSERVICE_LIBDIR
-3
View File
@@ -9,8 +9,6 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Qt6 REQUIRED COMPONENTS Core Network RemoteObjects Core5Compat)
qt_standard_project_setup()
configure_file(${CMAKE_SOURCE_DIR}/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/version.h)
set(HEADERS
${CMAKE_CURRENT_LIST_DIR}/../../client/utilities.h
${CMAKE_CURRENT_LIST_DIR}/../../ipc/ipc.h
@@ -20,7 +18,6 @@ set(HEADERS
${CMAKE_CURRENT_LIST_DIR}/logger.h
${CMAKE_CURRENT_LIST_DIR}/router.h
${CMAKE_CURRENT_LIST_DIR}/systemservice.h
${CMAKE_CURRENT_BINARY_DIR}/version.h
)
set(SOURCES
+1 -1
View File
@@ -5,7 +5,7 @@
#include <iostream>
#include "version.h"
#include "defines.h"
#include "utilities.h"
QFile Logger::m_file;
+1 -1
View File
@@ -1,6 +1,6 @@
#include <QDir>
#include "version.h"
#include "defines.h"
#include "localserver.h"
#include "logger.h"
#include "systemservice.h"
+71
View File
@@ -0,0 +1,71 @@
TARGET = AmneziaVPN-service
TEMPLATE = app
CONFIG += console qt no_batch
QT += core network remoteobjects
equals(QT_MAJOR_VERSION, 6): QT += core5compat
HEADERS = \
../../client/utilities.h \
../../ipc/ipc.h \
../../ipc/ipcserver.h \
../../ipc/ipcserverprocess.h \
localserver.h \
logger.h \
router.h \
systemservice.h
SOURCES = \
../../client/utilities.cpp \
../../ipc/ipcserver.cpp \
../../ipc/ipcserverprocess.cpp \
localserver.cpp \
logger.cpp \
main.cpp \
router.cpp \
systemservice.cpp
win32 {
HEADERS += \
tapcontroller_win.h \
router_win.h
SOURCES += \
tapcontroller_win.cpp \
router_win.cpp
LIBS += \
-luser32 \
-lrasapi32 \
-lshlwapi \
-liphlpapi \
-lws2_32 \
-liphlpapi \
-lgdi32 \
-lAdvapi32 \
-lKernel32
}
macx {
HEADERS += \
router_mac.h \
helper_route_mac.h
SOURCES += \
router_mac.cpp \
helper_route_mac.c
}
linux {
HEADERS += \
router_linux.h
SOURCES += \
router_linux.cpp
}
include(../src/qtservice.pri)
INCLUDEPATH += "$$PWD/../../client"
REPC_SOURCE += ../../ipc/ipc_interface.rep
!ios: REPC_SOURCE += ../../ipc/ipc_process_interface.rep
+1 -1
View File
@@ -1,4 +1,4 @@
#include "version.h"
#include "defines.h"
#include "localserver.h"
#include "systemservice.h"
+10
View File
@@ -0,0 +1,10 @@
!ios:!android {
TEMPLATE=subdirs
CONFIG += ordered
include(common.pri)
qtservice-uselib:SUBDIRS=buildlib
SUBDIRS+=server
}
win32 {
SUBDIRS+=wireguard-service
}
+21
View File
@@ -0,0 +1,21 @@
include(../common.pri)
INCLUDEPATH += $$PWD
DEPENDPATH += $$PWD
!win32:QT += network
win32:LIBS += -luser32
qtservice-uselib:!qtservice-buildlib {
LIBS += -L$$QTSERVICE_LIBDIR -l$$QTSERVICE_LIBNAME
} else {
HEADERS += $$PWD/qtservice.h \
$$PWD/qtservice_p.h
SOURCES += $$PWD/qtservice.cpp
win32:SOURCES += $$PWD/qtservice_win.cpp
unix:HEADERS += $$PWD/qtunixsocket.h $$PWD/qtunixserversocket.h
unix:SOURCES += $$PWD/qtservice_unix.cpp $$PWD/qtunixsocket.cpp $$PWD/qtunixserversocket.cpp
}
win32 {
qtservice-buildlib:shared:DEFINES += QT_QTSERVICE_EXPORT
else:qtservice-uselib:DEFINES += QT_QTSERVICE_IMPORT
}
@@ -0,0 +1,23 @@
TARGET = wireguard-service
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt
LIBS += \
-luser32 \
-lrasapi32 \
-lshlwapi \
-liphlpapi \
-lws2_32 \
-liphlpapi \
-lgdi32 \
-lAdvapi32 \
-lKernel32
HEADERS = \
wireguardtunnelservice.h
SOURCES = \
main.cpp \
wireguardtunnelservice.cpp
-16
View File
@@ -1,16 +0,0 @@
#ifndef VERSION_H
#define VERSION_H
#ifndef APP_VERSION
#define APP_VERSION "@CMAKE_PROJECT_VERSION@"
#endif
#ifndef APP_MAJOR_VERSION
#define APP_MAJOR_VERSION "@APP_MAJOR_VERSION@"
#endif
#define APPLICATION_NAME "AmneziaVPN"
#define SERVICE_NAME "AmneziaVPN-service"
#define ORGANIZATION_NAME "AmneziaVPN.ORG"
#endif // VERSION_H