我正在尝试使用Android4.x VPN服务与内部以太网服务器建立VPN隧道.IP地址是Internet上的一个全局IP,这是问题所在:

1.我使用TCP dump来捕获数据包,在建立VPN Service.build之后,无法在以前连接到服务器的隧道中传输任何tcp数据包。

2.建立建立后,我得到一个fileDescriptor,它不能写任何字节(EINVAL错误),也不能读任何字节(长度= 0)。

3.我使用套接字隧道与服务器通信并发送PPTP数据包,在启动控制请求,呼出调用请求之后,服务器返回正确的信息,然后通过PPP LCP协议(protocol)传输配置信息。但是,我不知道下一步该怎么做,如何获取PPP LCP数据包,它不是来自套接字,文件描述符无法读取或写入任何内容。

请帮忙,谢谢大家!

private static ParcelFileDescriptor tunPFD;

private boolean run(InetSocketAddress server) throws Exception {
    SocketChannel tunnel = null;
    boolean connected = false;
    try {

        // Create a DatagramChannel as the VPN tunnel.
        tunnel = SocketChannel.open();

        // Protect the tunnel before connecting to avoid loopback.
        if (!protect(tunnel.socket())) {

            // throw new IllegalStateException("Cannot protect the tunnel");
            System.out.println("can't protected");
        }

        // Connect to the server.
        tunnel.connect(server);
        System.out.println("connected");

        // For simplicity, we use the same thread for both reading and
        // writing. Here we put the tunnel into non-blocking mode.
        tunnel.configureBlocking(true);

        System.out.println("PFD success");

        // Authenticate and configure the virtual network interface.
        handshake(tunnel);
        System.out.println("handshake");
        Thread.sleep(1000);
        ToyVpnService.Builder builder = new ToyVpnService.Builder();
        builder.setSession("ToyVPN").addAddress("xxx.xxx.xxx.xxx", 32)
                                    .addRoute("1.0.0.0", 8)
                                    .addRoute("2.0.0.0", 7)
                                    .addRoute("4.0.0.0", 6)
                                    .addRoute("8.0.0.0", 7)
                                    .addRoute("11.0.0.0", 8)
                                    .addRoute("12.0.0.0", 6)
                                    .addRoute("16.0.0.0", 4)
                                    .addRoute("32.0.0.0", 3)
                                    .addRoute("64.0.0.0", 2)
                                    .addRoute("139.0.0.0", 8)
                                    .addRoute("140.0.0.0", 6)
                                    .addRoute("144.0.0.0", 4)
                                    .addRoute("160.0.0.0", 5)
                                    .addRoute("168.0.0.0", 6)
                                    .addRoute("172.0.0.0", 12)
                                    .addRoute("172.32.0.0", 11)
                                    .addRoute("172.64.0.0", 10)
                                    .addRoute("172.128.0.0", 9)
                                    .addRoute("173.0.0.0", 8)
                                    .addRoute("174.0.0.0", 7)
                                    .addRoute("176.0.0.0", 4)
                                    .addRoute("192.0.0.0", 9)
                                    .addRoute("192.128.0.0", 11)
                                    .addRoute("192.160.0.0", 13)
                                    .addRoute("192.169.0.0", 16)
                                    .addRoute("192.170.0.0", 15)
                                    .addRoute("192.172.0.0", 14)
                                    .addRoute("192.176.0.0", 12)
                                    .addRoute("192.192.0.0", 10)
                                    .addRoute("193.0.0.0", 8)
                                    .addRoute("194.0.0.0", 7)
                                    .addRoute("196.0.0.0", 6)
                                    .addRoute("200.0.0.0", 5)
                                    .addRoute("208.0.0.0", 4)
                                    .addRoute("224.0.0.0", 4)
                                    .addRoute("240.0.0.0", 5)
                                    .addRoute("248.0.0.0", 6)
                                    .addRoute("252.0.0.0", 7)
                                    .addRoute("254.0.0.0",8)
                                    .addDnsServer("xxx.xxx.xxx.xxx")
                                    .establish();

        if (tunPFD == null) {
            tunPFD = builder.establish();
            if (tunPFD == null) {
               System.out.println("stop");
               stopSelf();
            }
        }

        // Now we are connected. Set the flag and show the message.
        connected = true;
        mHandler.sendEmptyMessage(R.string.connected);
        tunnel.configureBlocking(false);

        // Packets to be sent are queued in this input stream.
       FileInputStream in = new FileInputStream(tunPFD.getFileDescriptor());

       // Packets received need to be written to this output stream.
       FileOutputStream out = new FileOutputStream(tunPFD.getFileDescriptor());
       int length = 0;
       int count = 0;

       while ((length == 0) && (count < 5000)) {
           length = in.read(pptp.dataPack);
           Thread.sleep(200);
           count += 200;
           System.out.println(count);
       }

       System.out.printf("read fd%d\n", tunPFD.getFd());
       System.out.println(length);

       System.out.println("write fd");
       tunnel.write(pptp.packet);

       Thread.sleep(2000);


        } catch (InterruptedException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                tunnel.close();
        } catch (Exception e) {
            // ignore
        }
    }
    return connected;
}
    private void handshake(SocketChannel tunnel) throws Exception {
    // To build a secured tunnel, we should perform mutual authentication
    // and exchange session keys for encryption. To keep things simple in
    // this demo, we just send the shared secret in plaintext and wait
    // for the server to send the parameters.

    // Allocate the buffer for handshaking.

    // Control messages always start with zero.

    tunnel.write(pptp.Start_Control_Req_Package());

    // Wait for the parameters within a limited time.
    Thread.sleep(100);
    // Normally we should not receive random packets.
    int length = tunnel.read(pptp.getEmptyPackage());
    if (length <= 0 || pptp.getPacketType() != 2) {
        System.out.println("start reply fail");
        return;
    }

    tunnel.write(pptp.Outgoing_Call_Req_Package());
    Thread.sleep(100);
    length = tunnel.read(pptp.getEmptyPackage());
    if (length <= 0 || pptp.getPacketType() != 8) {
        System.out.println("outgoing reply fail");
        return;
    }
    System.out.println("succeed");
}

pptp.Start_Control_Req_Package()保证生成一个Start-Control-Request数据包,该数据包可以由服务器答复。我已经从tcpdump确认了。 Outgoing_Call相同。然后服务器发回PPP_LCP数据包以请求配置,我不知道如何捕获它并发回配置。

最佳答案

看着您的代码片段,我看到了几件事。您是否修改了握手调用?如果不是这样,则可能会在构建器上两次调用Establishment()。假设未修改toyvpn示例中的握手和配置方法时,您在代码段中调用“建立”时,您可能会吹掉正确配置的接口(interface),至少与我所看到的看似与 Vanilla 交谈的接口(interface)与服务器通信toyvpn应用程序的服务器配置为向其发送正确的配置。因此,您正在尝试从配置错误的调谐设备中进行读取和写入。

private void handshake(DatagramChannel tunnel) throws Exception {
    // To build a secured tunnel, we should perform mutual authentication
    // and exchange session keys for encryption. To keep things simple in
    // this demo, we just send the shared secret in plaintext and wait
    // for the server to send the parameters.
    // Allocate the buffer for handshaking.
    ByteBuffer packet = ByteBuffer.allocate(1024);

    // Control messages always start with zero.
    packet.put((byte) 0).put(mSharedSecret).flip();

    // Send the secret several times in case of packet loss.
    for (int i = 0; i < 3; ++i) {
        packet.position(0);
        tunnel.write(packet);
    }
    packet.clear();

    // Wait for the parameters within a limited time.
    for (int i = 0; i < 50; ++i) {
        Thread.sleep(100);

        // Normally we should not receive random packets.
        int length = tunnel.read(packet);
        if (length > 0 && packet.get(0) == 0) {
            configure(new String(packet.array(), 1, length - 1).trim());
            return;
        }
    }
    throw new IllegalStateException("Timed out");
}

private void configure(String parameters) throws Exception {
    // If the old interface has exactly the same parameters, use it!
    if (mInterface != null && parameters.equals(mParameters)) {
        Log.i(TAG, "Using the previous interface");
        return;
    }

    // Configure a builder while parsing the parameters.
    Builder builder = new Builder();
    for (String parameter : parameters.split(" ")) {
        String[] fields = parameter.split(",");
        try {
            switch (fields[0].charAt(0)) {
                case 'm':
                    builder.setMtu(Short.parseShort(fields[1]));
                    break;
                case 'a':
                    builder.addAddress(fields[1], Integer.parseInt(fields[2]));
                    break;
                case 'r':
                    builder.addRoute(fields[1], Integer.parseInt(fields[2]));
                    break;
                case 'd':
                    builder.addDnsServer(fields[1]);
                    break;
                case 's':
                    builder.addSearchDomain(fields[1]);
                    break;
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("Bad parameter: " + parameter);
        }
    }

    // Close the old interface since the parameters have been changed.
    try {
        mInterface.close();
    } catch (Exception e) {
        // ignore
    }
    // Create a new interface using the builder and save the parameters.
        mInterface = builder.setSession(mServerAddress)
            .setConfigureIntent(mConfigureIntent)
            .establish();
        mParameters = parameters;
        Log.i(TAG, "New interface: " + parameters);
    }
}

可能有三次,因为第二次未使用构建器的返回值,但根据文档,它将为tun设备返回新的fd。我可能会建议将为配置vpn接口(interface)添加的更改移到ToyVpnService示例中的configure方法中。在大多数情况下,您所做的大部分更改似乎都集中在配置上。您可以尝试从ParcelFileDescriptor接口(interface)添加对canCheckError/checkError的调用,也可以使用getFd()并调用valid以在尝试读取和写入tun设备时检查tun设备的描述符是否实际上是有效的fd。

希望对您有所帮助。

关于android - Android开发中,来自VPNService.buider的FileDescriptor无法写入和读取,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21770242/

10-12 02:00