0

我正在尝试弄清楚如何进行网络扩展,以便我的 iOS 应用程序可以在 C# 中以编程方式打开自定义 VPN 隧道,但是查看一些类似的 Obj-C 项目我不确定在 Xamarin 中是否可行(因为我在 Visual Studio 中看不到网络扩展项目)以及如何移植我收集的是必需的 PacketTunnelProvider 类,我认为该类必须存在并首先在 plist.info 中列为扩展...我特别在如何移植该类的最后作为扩展名出现的部分和一些事件处理程序时遇到最大的麻烦func Adapter(adapter: Adapter, configureTunnelWithNetworkSettings networkSettings: NEPacketTunnelNetworkSettings, completionHandler: @escaping (AdapterPacketFlow?) -> Void )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 隧道并像往常一样从那里继续(因为我还发现了一个项目/应用程序https://github.com/passepartoutvpn它使用TunnelKit cocoapod,但该应用程序的库不能与 Sharpie 一起使用来制作绑定库,如果是这样,这样的应用程序甚至可以被 AppStore 接受吗)?感谢您提前提供任何帮助。


根据@SushiHangover 的建议,我已经尝试绑定 TunnelKit,因为该项目看起来更小,并且部分成功......我已经设法构建了 ~3MB dll,它似乎比 21MB OpenVPNAdapter 小得多,我想我几乎那里有 NetworkExtension 项目......我只是想弄清楚我对@escaping 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);
    }

我现在已经注释掉了 groupcontants 但至少我希望这是对 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 的项目:/

4

1 回答 1

0

我实际上是否应该只是使用自定义 VPN 库来打开 VPN 隧道并从那里开始,但是该应用程序会被 AppStore 接纳吗?

对于 iOS 12+,您绝对必须使用网络扩展框架才能获得商店资格。

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

您是正确的,VS 没有用于 Network Provider.appex的隧道、dns 代理、过滤控制|数据、代理类型的内置模板,但这并不意味着您不能只使用另一个模板(或创建从头开始项目)并修改它(我创建了一个 Xcode iOS 项目并开始添加扩展目标并在 VS 中镜像这些更改)。

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

现在由于.appex大小限制(以及某些情况下的性能问题),很多扩展都很难通过 Xamarin.iOS 完成。大多数遇到这种情况的开发人员,至少使用 ObjC/Swift 进行原生应用程序开发......

于 2019-02-09T18:37:45.273 回答