1 /*
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
19 // Needs to be included after sys/socket.h
20 #include <linux/vm_sockets.h>
21
22 #include <iostream>
23
24 #include "android-base/file.h"
25 #include "android-base/logging.h"
26 #include "android-base/parseint.h"
27 #include "android-base/unique_fd.h"
28
29 using namespace android::base;
30
main(int argc,const char * argv[])31 int main(int argc, const char *argv[]) {
32 SetLogger(StderrLogger);
33
34 unsigned int cid, port;
35 if (argc != 4 || !ParseUint(argv[1], &cid) || !ParseUint(argv[2], &port)) {
36 LOG(ERROR) << "Usage: " << argv[0] << " <cid> <port> <msg>";
37 return EXIT_FAILURE;
38 }
39 std::string msg(argv[3]);
40
41 unique_fd fd(TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM, 0)));
42 if (fd < 0) {
43 PLOG(ERROR) << "socket";
44 return EXIT_FAILURE;
45 }
46
47 struct sockaddr_vm sa = (struct sockaddr_vm){
48 .svm_family = AF_VSOCK,
49 .svm_port = port,
50 .svm_cid = cid,
51 };
52
53 LOG(INFO) << "Connecting to CID " << cid << " on port " << port << "...";
54 int ret = TEMP_FAILURE_RETRY(connect(fd, (struct sockaddr *)&sa, sizeof(sa)));
55 if (ret < 0) {
56 PLOG(ERROR) << "connect";
57 return EXIT_FAILURE;
58 }
59
60 LOG(INFO) << "Sending message to server...";
61 if (!WriteStringToFd(msg, fd)) {
62 PLOG(ERROR) << "WriteStringToFd";
63 return EXIT_FAILURE;
64 }
65
66 LOG(INFO) << "Exiting...";
67 return EXIT_SUCCESS;
68 }
69