如何将网络扩展NEPacketTunnelProvider类从Obj-C / Swift移植到Xamarin C#?

时间:2019-02-09 17:35:49

标签: xamarin openvpn networkextension

我试图弄清楚如何进行网络扩展,以便我的iOS应用可以以C#方式以编程方式打开自定义VPN隧道,但查看一些类似的Obj-C项目,我不确定在Xamarin中是否可行(因为我没有在Visual Studio中看到网络扩展项目),以及如何移植我收集的内容是必需的PacketTunnelProvider类,我认为该类必须存在并首先在plist.info中列出为扩展...我' m特别麻烦的是如何移植该类的末尾部分作为扩展名和某些事件处理程序,例如 func Adapter(adapter:Adapter,configureTunnelWithNetworkSettings networkSettings:NEPacketTunnelNetworkSettings,completeHandler:@escaping( AdapterPacketFlow?)->无效) func Adapter(adapter:Adapter,handleEvent event:AdapterEvent,message:String?)因为它们都具有与C#中的事件处理程序不同的签名接受sender和eventArgs(或派生的东西)…如果有人在C#中做到了这一点,我想至少知道是否有可能如何移植这样的类?

我找到了这个项目https://github.com/ss-abramchuk/OpenVPNAdapter(因为它似乎完成了我想要的大部分工作),因此我设法将其转换为Xamarin绑定库,但是我不确定如何以及是否合并其PacketTunnelProvider类在Xamarin中(这是自述文件,您应该使用它来整合诸如该适配器之类的东西)...我首先收集到这样一个东西应添加到plist.info中:

<key>NSExtension</key>
<dict>
    <key>NSExtensionPointIdentifier</key>
    <string>com.apple.networkextension.packet-tunnel</string>
    <key>NSExtensionPrincipalClass</key>
    <string>$(PRODUCT_MODULE_NAME).PacketTunnelProvider</string>
</dict>

但是您从那里开始使用绑定库?这是Obj-C代码,它似乎在执行我想做的事情,即使用该库将自定义VPN协议隧道添加到应用程序中:

import NetworkExtension
import OpenVPNAdapter

class PacketTunnelProvider : NEPacketTunnelProvider
{

    lazy var vpnAdapter: OpenVPNAdapter = {
        let adapter = OpenVPNAdapter()
        adapter.delegate = self

        return adapter
    }
()

let vpnReachability = OpenVPNReachability()

    var startHandler: ((Error?) -> Void)?
    var stopHandler: (() -> Void)?

    override func startTunnel(options: [String: NSObject]?, completionHandler: @escaping (Error?) -> Void)
{
    // There are many ways to provide OpenVPN settings to the tunnel provider. For instance,
    // you can use `options` argument of `startTunnel(options:completionHandler:)` method or get
    // settings from `protocolConfiguration.providerConfiguration` property of `NEPacketTunnelProvider`
    // class. Also you may provide just content of a ovpn file or use key:value pairs
    // that may be provided exclusively or in addition to file content.

    // In our case we need providerConfiguration dictionary to retrieve content
    // of the OpenVPN configuration file. Other options related to the tunnel
    // provider also can be stored there.
    guard
        let protocolConfiguration = protocolConfiguration as? NETunnelProviderProtocol,
            let providerConfiguration = protocolConfiguration.providerConfiguration
        else
    {
        fatalError()
        }

    guard let ovpnFileContent: Data = providerConfiguration["ovpn"] as? Data else
    {
        fatalError()
        }

    let configuration = OpenVPNConfiguration()
        configuration.fileContent = ovpnFileContent
        configuration.settings = [
            // Additional parameters as key:value pairs may be provided here
        ]

        // Apply OpenVPN configuration
    let properties: OpenVPNProperties
        do
    {
        properties = try vpnAdapter.apply(configuration: configuration)
        }
        catch
        {
            completionHandler(error)
            return
        }

        // Provide credentials if needed
        if !properties.autologin {
            // If your VPN configuration requires user credentials you can provide them by
            // `protocolConfiguration.username` and `protocolConfiguration.passwordReference`
            // properties. It is recommended to use persistent keychain reference to a keychain
            // item containing the password.

            guard let username: String = protocolConfiguration.username else
            {
                fatalError()
            }

            // Retrieve a password from the keychain
            guard let password: String = ... {
                fatalError()
            }

            let credentials = OpenVPNCredentials()
            credentials.username = username
            credentials.password = password

            do
            {
                try vpnAdapter.provide(credentials: credentials)
            }
                catch
                {
                    completionHandler(error)
                  return
              }
            }

        // Checking reachability. In some cases after switching from cellular to
        // WiFi the adapter still uses cellular data. Changing reachability forces
        // reconnection so the adapter will use actual connection.
        vpnReachability.startTracking { [weak self] status in
            guard status != .notReachable else { return }
    self?.vpnAdapter.reconnect(interval: 5)
        }

// Establish connection and wait for .connected event
startHandler = completionHandler
vpnAdapter.connect()
    }

    override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void)
{
    stopHandler = completionHandler

        if vpnReachability.isTracking {
        vpnReachability.stopTracking()
        }

    vpnAdapter.disconnect()
    }

}

extension PacketTunnelProvider: OpenVPNAdapterDelegate {

    // OpenVPNAdapter calls this delegate method to configure a VPN tunnel.
    // `completionHandler` callback requires an object conforming to `OpenVPNAdapterPacketFlow`
    // protocol if the tunnel is configured without errors. Otherwise send nil.
    // `OpenVPNAdapterPacketFlow` method signatures are similar to `NEPacketTunnelFlow` so
    // you can just extend that class to adopt `OpenVPNAdapterPacketFlow` protocol and
    // send `self.packetFlow` to `completionHandler` callback.
    func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, configureTunnelWithNetworkSettings networkSettings: NEPacketTunnelNetworkSettings, completionHandler: @escaping (OpenVPNAdapterPacketFlow?) -> Void)
{
    setTunnelNetworkSettings(settings) {
        (error) in
            completionHandler(error == nil ? self.packetFlow : nil)
        }
}

// Process events returned by the OpenVPN library
func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleEvent event: OpenVPNAdapterEvent, message: String?)
{
    switch event {
        case .connected:
        if reasserting {
            reasserting = false
            }

        guard let startHandler = startHandler else { return }

        startHandler(nil)
            self.startHandler = nil

        case .disconnected:
        guard let stopHandler = stopHandler else { return }

        if vpnReachability.isTracking {
            vpnReachability.stopTracking()
            }

        stopHandler()
            self.stopHandler = nil

        case .reconnecting:
        reasserting = true

        default:
            break
        }
}

// Handle errors thrown by the OpenVPN library
func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleError error: Error)
{
    // Handle only fatal errors
    guard let fatal = (error as NSError).userInfo[OpenVPNAdapterErrorFatalKey] as? Bool, fatal == true else
    {
        return
        }

    if vpnReachability.isTracking {
        vpnReachability.stopTracking()
        }

    if let startHandler = startHandler {
        startHandler(error)
            self.startHandler = nil
        } else
    {
        cancelTunnelWithError(error)
        }
}

// Use this method to process any log message returned by OpenVPN library.
func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleLogMessage logMessage: String)
{
    // Handle log messages
}

}

// Extend NEPacketTunnelFlow to adopt OpenVPNAdapterPacketFlow protocol so that
// `self.packetFlow` could be sent to `completionHandler` callback of OpenVPNAdapterDelegate
// method openVPNAdapter(openVPNAdapter:configureTunnelWithNetworkSettings:completionHandler).
extension NEPacketTunnelFlow: OpenVPNAdapterPacketFlow {}

然后我该如何移植到C#,或者我做错了所有事(由于注释如下-绑定dll大于15MB-还是与内存使用无关的限制?文件大小)?实际上,我是否应该仅引用自定义VPN库从代码直接打开VPN隧道,然后像往常一样从那里继续操作(因为我还发现了一个使用TunnelKit cocoapod的项目/应用https://github.com/passepartoutvpn,该应用程序的库无法与Sharpie配合使用来创建绑定库,如果是这样的话,该应用程序甚至可以被AppStore接受)?谢谢您的提前帮助。


根据@SushiHangover的建议,我尝试绑定TunnelKit,因为该项目看起来较小,并且成功了,部分成功了……我设法构建了大约3MB的dll,该文件似乎比21MB OpenVPNAdapter,我想我已经在NetworkExtension项目中了... 我只想弄清楚我使用@转义completionHandler做得如何,以及如何获取一些我认为应该是的组常量在主机应用程序中进行设置?

public override void StartTunnel(NSDictionary<NSString, NSObject> options, Action<NSError> completionHandler)
    {
        //appVersion = "\(GroupConstants.App.name) \(GroupConstants.App.versionString)";
        //dnsTimeout = GroupConstants.VPN.dnsTimeout;
        //logSeparator = GroupConstants.VPN.sessionMarker;
        base.StartTunnel(options, completionHandler);
    }

我现在已经注释掉了组竞争者,但至少我希望这足以移植Swift3:

override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {
    appVersion = "\(GroupConstants.App.name) \(GroupConstants.App.versionString)"
    dnsTimeout = GroupConstants.VPN.dnsTimeout
    logSeparator = GroupConstants.VPN.sessionMarker
    super.startTunnel(options: options, completionHandler: completionHandler)
}

如果其他任何人都知道组常量以及如何获取它们,我将不胜感激(但我也应注意, sharpie pod 并没有给出/公开任何这些字段我应该分配。也许我做错了,因为TunnelKit是与OpenVPNAdapter不同的完全Swift3项目:/

1 个答案:

答案 0 :(得分:0)

  

我实际上应该只使用自定义VPN库打开VPN隧道并从那里去吗,但是该应用程序可以被AppStore接受吗?

对于iOS 12或更高版本,您绝对必须使用Network Extension框架才有资格进行商店购买。

Xamarin.iOS构建任务(ValidateAppBundle)正确地将com.apple.networkextension.packet-tunnel标识为有效扩展名(.appex),因此可以构建NEPacketTunnelProvider扩展名。

您是正确的,VS没有针对隧道,dns代理,过滤器控件|数据,代理类型的网络提供商.appex的内置模板,但这并不意味着您不能仅使用其他模板模板之一(或从头开始创建项目)并对其进行修改(我创建一个Xcode iOS项目并开始添加扩展目标,然后在VS中镜像这些更改)。

(仅供参考:在您的示例中,这是Swift代码,而不是ObjC ...)

现在由于.appex大小的限制(在某些情况下还存在性能问题),通过Xamarin.iOS很难完成许多扩展。大多数遇到此问题的开发人员,至少可以使用ObjC / Swift来进行appex开发...