VpnService

package com.ly.packetcapture.vpn.service

import android.content.Intent
import android.net.VpnService
import android.os.ParcelFileDescriptor
import com.ly.packetcapture.R
import com.ly.packetcapture.vpn.bio.BioUdpHandler
import com.ly.packetcapture.vpn.bio.NioSingleThreadTcpHandler
import com.ly.packetcapture.config.Config
import com.ly.packetcapture.config.Config.dns
import com.ly.packetcapture.vpn.protocol.tcpip.Packet
import com.ly.packetcapture.util.LogUtil
import com.ly.packetcapture.util.SharePrefUtil
import java.io.*
import java.lang.Exception
import java.nio.ByteBuffer
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlin.system.exitProcess

class LocalVPNService : VpnService() {
    //设备到网络UDP队列
    private var deviceToNetworkUDPQueue: BlockingQueue<Packet>? = null
    //设备到网络TCP队列
    private var deviceToNetworkTCPQueue: BlockingQueue<Packet>? = null
    //网络到设备的队列
    private var networkToDeviceQueue: BlockingQueue<ByteBuffer>? = null
    private lateinit var executorService: ExecutorService
    override fun onCreate() {
        super.onCreate()
        setupVPN()
        deviceToNetworkUDPQueue = ArrayBlockingQueue(1000)
        deviceToNetworkTCPQueue = ArrayBlockingQueue(1000)
        networkToDeviceQueue = ArrayBlockingQueue(1000)
        executorService = Executors.newFixedThreadPool(10)
        executorService.submit(BioUdpHandler(deviceToNetworkUDPQueue!!, networkToDeviceQueue!!, this))
        executorService.submit(NioSingleThreadTcpHandler(deviceToNetworkTCPQueue!!, networkToDeviceQueue!!, this))

        deviceToNetworkUDPQueue!!
        deviceToNetworkTCPQueue!!
        networkToDeviceQueue!!
        vpnInterface!!

        executorService.submit(VPNRunnable(vpnInterface!!.fileDescriptor, deviceToNetworkUDPQueue!!, deviceToNetworkTCPQueue!!, networkToDeviceQueue!!))
    }

    /**
     * 设置VPNService属性并获取对象
     */
    private fun setupVPN() {
        try {
            if (vpnInterface == null) {
                val builder = Builder()
                builder.addAddress(VPN_ADDRESS, 32)
                builder.addRoute(VPN_ROUTE, 0)
                builder.addDnsServer(dns)
                val selList = SharePrefUtil.getString(Config.SEL_KEY)
                if (selList.isNotEmpty()) {
                    val appList = selList.split(",").toTypedArray()
                    for (app in appList) {
                        LogUtil.e("拦截的APP:$app")
                        builder.addAllowedApplication(app)
                    }
                }
                builder.addAllowedApplication("com.android.systemui")
                vpnInterface = builder.setSession(getString(R.string.app_name)).establish()
            }
        } catch (e: Exception) {
            LogUtil.e("设置VPNService失败 : $e")
            exitProcess(0)
        }
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        //判断是否要关闭
        if (intent.getBooleanExtra("exit", false)) {
            executorService.shutdownNow()
            cleanup()
            stopSelf()
        }
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        executorService.shutdownNow()
        cleanup()
    }

    private fun cleanup() {
        deviceToNetworkTCPQueue = null
        deviceToNetworkUDPQueue = null
        networkToDeviceQueue = null
        vpnInterface?.let {
            closeResources(it)
            vpnInterface = null
        }
    }

    /**
     * 回写网卡线程
     */

    companion object {
        private const val VPN_ADDRESS = "10.0.0.2" // Only IPv4 support for now
        private const val VPN_ROUTE = "0.0.0.0" // Intercept everything
        var vpnInterface: ParcelFileDescriptor? = null

        // TODO: Move this to a "utils" class for reuse
        private fun closeResources(vararg resources: Closeable) {
            for (resource in resources) {
                try {
                    resource.close()
                } catch (e: Exception) {
                    // Ignore
                }
            }
        }
    }

}
实现 SSTP VPN 可以使用 Android 中的 VPNService 类。以下是实现步骤: 1. 首先,需要在 AndroidManifest.xml 文件中声明 VPNService 的服务。 ``` <service android:name=".SstpVpnService" android:permission="android.permission.BIND_VPN_SERVICE" android:exported="false"> </service> ``` 2. 创建 SstpVpnService 类并继承 VPNService 类,实现必要的方法。 ``` public class SstpVpnService extends VpnService { // 实现必要的方法 } ``` 3. 在 onCreate() 方法中,创建一个 Builder 对象并设置 VPN 的配置。 ``` @Override public void onCreate() { super.onCreate(); Builder builder = new Builder(); builder.setSession("SSTP VPN"); builder.setMtu(1400); builder.addAddress("10.0.0.2", 24); builder.addRoute("0.0.0.0", 0); builder.addDnsServer("8.8.8.8"); builder.setBlocking(true); builder.setUnderlyingNetworks(null); builder.setConfigureIntent(null); try { mInterface = builder.establish(); } catch (Exception e) { e.printStackTrace(); } } ``` 4. 实现 onRevoke() 方法,在 VPN 被撤销时进行清理工作。 ``` @Override public void onRevoke() { super.onRevoke(); if (mInterface != null) { try { mInterface.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 5. 在 onStartCommand() 方法中,启动 VPN。 ``` @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } ``` 6. 最后,在应用程序中启动 SSTP VPN 服务。 ``` Intent vpnIntent = VpnService.prepare(this); if (vpnIntent != null) { startActivityForResult(vpnIntent, VPN_REQUEST_CODE); } else { startVpnService(); } ``` 这样,就可以在 Android 应用程序中实现 SSTP VPN 服务。需要注意的是,SSTP VPN 协议是基于 SSL/TLS 的,需要使用 SSL/TLS 协议进行加密。在实现过程中,需要配置 SSL/TLS 相关的参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GodCodeApps

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值