| /* |
| * Copyright (C) 2020 The Android Open Source Project |
| * |
| * Licensed under the Apache License, Version 2.0 (the "License"); |
| * you may not use this file except in compliance with the License. |
| * You may obtain a copy of the License at |
| * |
| * http://www.apache.org/licenses/LICENSE-2.0 |
| * |
| * Unless required by applicable law or agreed to in writing, software |
| * distributed under the License is distributed on an "AS IS" BASIS, |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| * See the License for the specific language governing permissions and |
| * limitations under the License. |
| */ |
| |
| #include <errno.h> |
| #include <sys/socket.h> |
| #include <unistd.h> |
| |
| #include <linux/vm_sockets.h> |
| |
| #include <cstdlib> |
| #include <cstring> |
| #include <iostream> |
| |
| static constexpr const char LOG_TAG[] = "VsockTest: "; |
| static constexpr int VSOCK_TEST_PORT = 4455; |
| static constexpr int VSOCK_TEST_CID = 42; |
| static constexpr const char VSOCK_TEST_MSG[] = "VsockTestMessage\n"; |
| |
| int VsockServer() { |
| int fd, ret; |
| struct sockaddr_vm sa = (struct sockaddr_vm) { |
| .svm_family = AF_VSOCK, |
| .svm_port = VSOCK_TEST_PORT, |
| .svm_cid = VSOCK_TEST_CID, |
| }; |
| char buf[1024]; |
| size_t buf_used = 0; |
| |
| fd = socket(AF_VSOCK, SOCK_STREAM, 0); |
| if (fd < 0) { |
| std::cerr << "ERROR: socket: " << strerror(errno) << std::endl; |
| return EXIT_FAILURE; |
| } |
| |
| std::cerr << LOG_TAG << "Establishing a vsock connection..." << std::endl; |
| |
| ret = connect(fd, (struct sockaddr*)&sa, sizeof(sa)); |
| if (ret != 0) { |
| std::cerr << "ERROR: connect: " << strerror(errno) << std::endl; |
| close(fd); |
| return EXIT_FAILURE; |
| } |
| |
| std::cerr << LOG_TAG << "Reading message from guest..." << std::endl; |
| |
| while (true) { |
| ssize_t n = read(fd, buf + buf_used, sizeof(buf) - buf_used); |
| |
| if (n == 0) { |
| break; |
| } else if (n < 0) { |
| close(fd); |
| return EXIT_FAILURE; |
| } |
| |
| buf_used += n; |
| } |
| |
| close(fd); |
| |
| std::cerr << LOG_TAG << "Message from guest: " << buf << std::endl; |
| if ((buf_used == sizeof(VSOCK_TEST_MSG)) && |
| memcmp(VSOCK_TEST_MSG, buf, sizeof(VSOCK_TEST_MSG)) == 0) { |
| std::cerr << LOG_TAG << "Message match" << std::endl; |
| return EXIT_SUCCESS; |
| } else { |
| std::cerr << LOG_TAG << "Message mismatch" << std::endl; |
| return EXIT_FAILURE; |
| } |
| } |