blob: 74e984fe9483bc3c5b7692f765191763015e29ef [file] [log] [blame]
David Brazdil49f8a4d2021-03-04 09:57:33 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <sys/socket.h>
18#include <unistd.h>
19
20// Needs to be included after sys/socket.h
21#include <linux/vm_sockets.h>
22
23#include <iostream>
24
25#include "android-base/file.h"
26#include "android-base/logging.h"
27#include "android-base/parseint.h"
28#include "android-base/unique_fd.h"
29
30#include "virt/VirtualizationTest.h"
31
32using namespace android::base;
33
34namespace virt {
35
36static constexpr int kGuestPort = 45678;
37static constexpr const char kVmConfigPath[] = "/data/local/tmp/virt-test/vsock_config.json";
38static constexpr const char kTestMessage[] = "HelloWorld";
39
40TEST_F(VirtualizationTest, TestVsock) {
41 binder::Status status;
42
43 unique_fd server_fd(TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM, 0)));
44 ASSERT_GE(server_fd, 0) << strerror(errno);
45
46 struct sockaddr_vm server_sa = (struct sockaddr_vm){
47 .svm_family = AF_VSOCK,
48 .svm_port = kGuestPort,
49 .svm_cid = VMADDR_CID_ANY,
50 };
51
52 int ret = TEMP_FAILURE_RETRY(bind(server_fd, (struct sockaddr *)&server_sa, sizeof(server_sa)));
53 ASSERT_EQ(ret, 0) << strerror(errno);
54
55 LOG(INFO) << "Listening on port " << kGuestPort << "...";
56 ret = TEMP_FAILURE_RETRY(listen(server_fd, 1));
57 ASSERT_EQ(ret, 0) << strerror(errno);
58
59 sp<IVirtualMachine> vm;
60 status = mVirtManager->startVm(String16(kVmConfigPath), &vm);
61 ASSERT_TRUE(status.isOk()) << "Error starting VM: " << status;
62
63 int32_t cid;
64 status = vm->getCid(&cid);
65 ASSERT_TRUE(status.isOk()) << "Error getting CID: " << status;
66 LOG(INFO) << "VM starting with CID " << cid;
67
68 LOG(INFO) << "Accepting connection...";
69 struct sockaddr_vm client_sa;
70 socklen_t client_sa_len = sizeof(client_sa);
71 unique_fd client_fd(
72 TEMP_FAILURE_RETRY(accept(server_fd, (struct sockaddr *)&client_sa, &client_sa_len)));
73 ASSERT_GE(client_fd, 0) << strerror(errno);
74 LOG(INFO) << "Connection from CID " << client_sa.svm_cid << " on port " << client_sa.svm_port;
75
76 LOG(INFO) << "Reading message from the client...";
77 std::string msg;
78 ASSERT_TRUE(ReadFdToString(client_fd, &msg));
79
80 LOG(INFO) << "Received message: " << msg;
81 ASSERT_EQ(msg, kTestMessage);
82}
83
84} // namespace virt