From d9a6a42bf17bad85993f593ff95b25fc52114180 Mon Sep 17 00:00:00 2001 From: Flyingblu Date: Tue, 9 Apr 2019 21:45:03 +0800 Subject: [PATCH] Add VPN state handler for iOS --- example/ios/Flutter/Debug.xcconfig | 1 + example/ios/Flutter/Release.xcconfig | 1 + example/ios/Podfile | 71 +++++++++++ example/ios/Podfile.lock | 22 ++++ example/ios/Runner.xcodeproj/project.pbxproj | 83 ++++++++++++- .../xcshareddata/xcschemes/Runner.xcscheme | 4 +- .../contents.xcworkspacedata | 3 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 ++ .../xcshareddata/WorkspaceSettings.xcsettings | 8 ++ ios/Classes/SwiftFlutterVpnPlugin.swift | 42 ++++--- ios/Classes/VPNHandler.swift | 113 +++++++++--------- ios/Classes/VPNStateHandler.swift | 35 ++++++ 12 files changed, 316 insertions(+), 75 deletions(-) create mode 100644 example/ios/Podfile create mode 100644 example/ios/Podfile.lock create mode 100644 example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings create mode 100644 ios/Classes/VPNStateHandler.swift diff --git a/example/ios/Flutter/Debug.xcconfig b/example/ios/Flutter/Debug.xcconfig index 592ceee..e8efba1 100644 --- a/example/ios/Flutter/Debug.xcconfig +++ b/example/ios/Flutter/Debug.xcconfig @@ -1 +1,2 @@ +#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/example/ios/Flutter/Release.xcconfig b/example/ios/Flutter/Release.xcconfig index 592ceee..399e934 100644 --- a/example/ios/Flutter/Release.xcconfig +++ b/example/ios/Flutter/Release.xcconfig @@ -1 +1,2 @@ +#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/example/ios/Podfile b/example/ios/Podfile new file mode 100644 index 0000000..64eddc6 --- /dev/null +++ b/example/ios/Podfile @@ -0,0 +1,71 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '9.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def parse_KV_file(file, separator='=') + file_abs_path = File.expand_path(file) + if !File.exists? file_abs_path + return []; + end + pods_ary = [] + skip_line_start_symbols = ["#", "/"] + File.foreach(file_abs_path) { |line| + next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ } + plugin = line.split(pattern=separator) + if plugin.length == 2 + podname = plugin[0].strip() + path = plugin[1].strip() + podpath = File.expand_path("#{path}", file_abs_path) + pods_ary.push({:name => podname, :path => podpath}); + else + puts "Invalid plugin specification: #{line}" + end + } + return pods_ary +end + +target 'Runner' do + use_frameworks! + + # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock + # referring to absolute paths on developers' machines. + system('rm -rf .symlinks') + system('mkdir -p .symlinks/plugins') + + # Flutter Pods + generated_xcode_build_settings = parse_KV_file('./Flutter/Generated.xcconfig') + if generated_xcode_build_settings.empty? + puts "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter packages get is executed first." + end + generated_xcode_build_settings.map { |p| + if p[:name] == 'FLUTTER_FRAMEWORK_DIR' + symlink = File.join('.symlinks', 'flutter') + File.symlink(File.dirname(p[:path]), symlink) + pod 'Flutter', :path => File.join(symlink, File.basename(p[:path])) + end + } + + # Plugin Pods + plugin_pods = parse_KV_file('../.flutter-plugins') + plugin_pods.map { |p| + symlink = File.join('.symlinks', 'plugins', p[:name]) + File.symlink(p[:path], symlink) + pod p[:name], :path => File.join(symlink, 'ios') + } +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + target.build_configurations.each do |config| + config.build_settings['ENABLE_BITCODE'] = 'NO' + end + end +end diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock new file mode 100644 index 0000000..a0cdee2 --- /dev/null +++ b/example/ios/Podfile.lock @@ -0,0 +1,22 @@ +PODS: + - Flutter (1.0.0) + - flutter_vpn (0.1.0): + - Flutter + +DEPENDENCIES: + - Flutter (from `.symlinks/flutter/ios`) + - flutter_vpn (from `.symlinks/plugins/flutter_vpn/ios`) + +EXTERNAL SOURCES: + Flutter: + :path: ".symlinks/flutter/ios" + flutter_vpn: + :path: ".symlinks/plugins/flutter_vpn/ios" + +SPEC CHECKSUMS: + Flutter: 9d0fac939486c9aba2809b7982dfdbb47a7b0296 + flutter_vpn: 2423d8360239be253098ab638860f2b0c526b6da + +PODFILE CHECKSUM: ebd43b443038e611b86ede96e613bd6033c49497 + +COCOAPODS: 1.5.3 diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index df93226..b89c45c 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -11,10 +11,10 @@ 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 3B80C3941E831B6300D905FE /* App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; }; 3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + 6404F1B9F0CE877A8EF94856 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D78E0BF63C8161A5BA7DF23 /* Pods_Runner.framework */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; }; 9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - 9740EEB41CF90195004384FC /* Debug.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 9740EEB21CF90195004384FC /* Debug.xcconfig */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; @@ -38,6 +38,7 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 1D78E0BF63C8161A5BA7DF23 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 3B80C3931E831B6300D905FE /* App.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = App.framework; path = Flutter/App.framework; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; @@ -60,6 +61,7 @@ files = ( 9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */, 3B80C3941E831B6300D905FE /* App.framework in Frameworks */, + 6404F1B9F0CE877A8EF94856 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -85,6 +87,8 @@ 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, + AE370A710B271AC0951D0476 /* Pods */, + A2AB7D390AA9A9F8ACD2CF62 /* Frameworks */, ); sourceTree = ""; }; @@ -119,6 +123,21 @@ name = "Supporting Files"; sourceTree = ""; }; + A2AB7D390AA9A9F8ACD2CF62 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 1D78E0BF63C8161A5BA7DF23 /* Pods_Runner.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + AE370A710B271AC0951D0476 /* Pods */ = { + isa = PBXGroup; + children = ( + ); + name = Pods; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -126,12 +145,14 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( + 71E681E13CF2EA3D18488A30 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 61C04C8E035088663FB6CF9A /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -148,7 +169,7 @@ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 0910; + LastUpgradeCheck = 1020; ORGANIZATIONNAME = "The Chromium Authors"; TargetAttributes = { 97C146ED1CF9000F007C117D = { @@ -162,6 +183,7 @@ developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( + English, en, Base, ); @@ -182,7 +204,6 @@ files = ( 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, - 9740EEB41CF90195004384FC /* Debug.xcconfig in Resources */, 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, ); @@ -205,6 +226,52 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" thin"; }; + 61C04C8E035088663FB6CF9A /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${SRCROOT}/Pods/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", + "${PODS_ROOT}/../.symlinks/flutter/ios/Flutter.framework", + "${BUILT_PRODUCTS_DIR}/flutter_vpn/flutter_vpn.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + ); + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Flutter.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/flutter_vpn.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 71E681E13CF2EA3D18488A30 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -258,6 +325,7 @@ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -267,12 +335,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -331,6 +401,7 @@ baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -340,12 +411,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -385,6 +458,7 @@ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -394,12 +468,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -508,7 +584,6 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ - }; rootObject = 97C146E61CF9000F007C117D /* Project object */; } diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 786d6aa..a28140c 100644 --- a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -1,6 +1,6 @@ @@ -46,7 +45,6 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" diff --git a/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcworkspace/contents.xcworkspacedata index 1d526a1..21a3cc1 100644 --- a/example/ios/Runner.xcworkspace/contents.xcworkspacedata +++ b/example/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -4,4 +4,7 @@ + + diff --git a/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..949b678 --- /dev/null +++ b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + BuildSystemType + Original + + diff --git a/ios/Classes/SwiftFlutterVpnPlugin.swift b/ios/Classes/SwiftFlutterVpnPlugin.swift index 4afc436..f5e330d 100644 --- a/ios/Classes/SwiftFlutterVpnPlugin.swift +++ b/ios/Classes/SwiftFlutterVpnPlugin.swift @@ -1,3 +1,17 @@ +/** + * Copyright (C) 2019 Jerry Wang, Jason C.H + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + import Flutter import UIKit @@ -5,24 +19,24 @@ import UIKit public class SwiftFlutterVpnPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "flutter_vpn", binaryMessenger: registrar.messenger()) - let stateChannel = FlutterEventChannel(name: "flutter_vpn_state", binaryMessenger:registrar.messenger()) + let stateChannel = FlutterEventChannel(name: "flutter_vpn_state", binaryMessenger: registrar.messenger()) let instance = SwiftFlutterVpnPlugin() registrar.addMethodCallDelegate(instance, channel: channel) - channel.setMethodCallHandler({ - (call: FlutterMethodCall, result: FlutterResult) -> Void in - if ("connect" == call.method) { - let args = call.arguments! as! Dictionary - - connectVPN(result: result, usrname: args["username"]!, pwd: args["password"]!, add: args["address"]!) - } else if ("disconnect" == call.method) { - stopVPN(result: result) - } else if ("getCurrentState" == call.method) { - getVPNState(result: result) - } - }) + stateChannel.setStreamHandler(VPNStateHandler() as! FlutterStreamHandler & NSObjectProtocol) + channel.setMethodCallHandler { + (call: FlutterMethodCall, result: FlutterResult) -> Void in + if call.method == "connect" { + let args = call.arguments! as! [NSString: NSString] + connectVPN(result: result, usrname: args["username"]!, pwd: args["password"]!, add: args["address"]!) + } else if call.method == "disconnect" { + stopVPN(result: result) + } else if call.method == "getCurrentState" { + getVPNState(result: result) + } + } } - public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + public func handle(_: FlutterMethodCall, result: @escaping FlutterResult) { result("iOS " + UIDevice.current.systemVersion) } } diff --git a/ios/Classes/VPNHandler.swift b/ios/Classes/VPNHandler.swift index 8afab58..1dfb007 100644 --- a/ios/Classes/VPNHandler.swift +++ b/ios/Classes/VPNHandler.swift @@ -1,3 +1,17 @@ +/** + * Copyright (C) 2019 Jerry Wang, Jason C.H + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + import Foundation import NetworkExtension import Security @@ -22,26 +36,25 @@ let kSecAttrGenericValue = kSecAttrGeneric as CFString let kSecAttrAccessibleValue = kSecAttrAccessible as CFString class KeychainService: NSObject { - func save(key:String, value:String) { + func save(key: String, value: String) { let keyData: Data = key.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: false)! let valueData: Data = value.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: false)! - - let keychainQuery = NSMutableDictionary(); + + let keychainQuery = NSMutableDictionary() keychainQuery[kSecClassValue as! NSCopying] = kSecClassGenericPasswordValue keychainQuery[kSecAttrGenericValue as! NSCopying] = keyData keychainQuery[kSecAttrAccountValue as! NSCopying] = keyData keychainQuery[kSecAttrServiceValue as! NSCopying] = "VPN" keychainQuery[kSecAttrAccessibleValue as! NSCopying] = kSecAttrAccessibleAlwaysThisDeviceOnly - keychainQuery[kSecValueData as! NSCopying] = valueData; + keychainQuery[kSecValueData as! NSCopying] = valueData // Delete any existing items SecItemDelete(keychainQuery as CFDictionary) SecItemAdd(keychainQuery as CFDictionary, nil) } - - func load(key: String)->Data { - + + func load(key: String) -> Data { let keyData: Data = key.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: false)! - let keychainQuery = NSMutableDictionary(); + let keychainQuery = NSMutableDictionary() keychainQuery[kSecClassValue as! NSCopying] = kSecClassGenericPasswordValue keychainQuery[kSecAttrGenericValue as! NSCopying] = keyData keychainQuery[kSecAttrAccountValue as! NSCopying] = keyData @@ -49,82 +62,78 @@ class KeychainService: NSObject { keychainQuery[kSecAttrAccessibleValue as! NSCopying] = kSecAttrAccessibleAlwaysThisDeviceOnly keychainQuery[kSecMatchLimit] = kSecMatchLimitOne keychainQuery[kSecReturnPersistentRef] = kCFBooleanTrue - + var result: AnyObject? let status = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(keychainQuery, UnsafeMutablePointer($0)) } - - + if status == errSecSuccess { if let data = result as! NSData? { - if let value = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) { - } - return data as Data; + if let value = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) {} + return data as Data } } - return "".data(using: .utf8)!; + return "".data(using: .utf8)! } } @available(iOS 9.0, *) -func connectVPN(result: FlutterResult, usrname: NSString, pwd: NSString, add: NSString){ +func connectVPN(result: FlutterResult, usrname: NSString, pwd: NSString, add: NSString) { let vpnManager = NEVPNManager.shared() let kcs = KeychainService() + result(nil) + vpnManager.loadFromPreferences { (error) -> Void in - - if((error) != nil) { + + if error != nil { print("VPN Preferences error: 1") - } - else { - + VPNStateHandler.updateState(4) + } else { + VPNStateHandler.updateState(1) let p = NEVPNProtocolIKEv2() - + p.username = usrname as String p.remoteIdentifier = add as String p.serverAddress = add as String - + kcs.save(key: "password", value: pwd as String) p.passwordReference = kcs.load(key: "password") p.authenticationMethod = NEVPNIKEAuthenticationMethod.none - + p.useExtendedAuthentication = true p.disconnectOnSleep = false - + vpnManager.protocolConfiguration = p vpnManager.isEnabled = true - + vpnManager.saveToPreferences(completionHandler: { (error) -> Void in - if((error) != nil) { + if error != nil { print("VPN Preferences error: 2") - } - else { - - vpnManager.loadFromPreferences(completionHandler: { (error) in - - if((error) != nil) { - + VPNStateHandler.updateState(4) + } else { + vpnManager.loadFromPreferences(completionHandler: { error in + + if error != nil { print("VPN Preferences error: 2") - } - else { - + VPNStateHandler.updateState(4) + } else { var startError: NSError? - + do { try vpnManager.connection.startVPNTunnel() - } - catch let error as NSError { + } catch let error as NSError { startError = error + VPNStateHandler.updateState(4) print(startError) - } - catch { + } catch { print("Fatal Error") fatalError() } - if((startError) != nil) { + if startError != nil { print("VPN Preferences error: 3") print(startError) - } - else { + } else { print("VPN started successfully..") + VPNStateHandler.updateState(2) } } }) @@ -134,10 +143,12 @@ func connectVPN(result: FlutterResult, usrname: NSString, pwd: NSString, add: NS } } -func stopVPN(result: FlutterResult){ +func stopVPN(result: FlutterResult) { let vpnManager = NEVPNManager.shared() + result(nil) + VPNStateHandler.updateState(3) vpnManager.connection.stopVPNTunnel() - result(0) + VPNStateHandler.updateState(0) } func getVPNState(result: FlutterResult) { @@ -146,21 +157,15 @@ func getVPNState(result: FlutterResult) { switch status { case .connecting: result(1) - break case .connected: result(2) - break case .disconnecting: result(3) - break case .disconnected: result(0) - break case .invalid: - result(4) - break + result(0) case .reasserting: result(4) - break } } diff --git a/ios/Classes/VPNStateHandler.swift b/ios/Classes/VPNStateHandler.swift new file mode 100644 index 0000000..b23883a --- /dev/null +++ b/ios/Classes/VPNStateHandler.swift @@ -0,0 +1,35 @@ +/** + * Copyright (C) 2019 Jerry Wang, Jason C.H + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +import Foundation + +class VPNStateHandler: FlutterStreamHandler { + static var _sink: FlutterEventSink? + + static func updateState(_ newState: Int) { + if let sink = _sink { + sink(newState) + } + } + + func onListen(withArguments _: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { + VPNStateHandler._sink = events + return nil + } + + func onCancel(withArguments _: Any?) -> FlutterError? { + VPNStateHandler._sink = nil + return nil + } +}