1 /*
2 * Copyright (C) 2018 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 <sysutils/FrameworkCommand.h>
18 #include <sysutils/FrameworkListener.h>
19
20 #include <poll.h>
21 #include <string.h>
22 #include <sys/socket.h>
23 #include <sys/un.h>
24
25 #include <algorithm>
26 #include <memory>
27
28 #include <android-base/file.h>
29 #include <android-base/logging.h>
30 #include <android-base/strings.h>
31 #include <android-base/unique_fd.h>
32 #include <cutils/sockets.h>
33 #include <gtest/gtest.h>
34
35 using android::base::unique_fd;
36
37 namespace {
38
testSocketPath()39 std::string testSocketPath() {
40 const testing::TestInfo* const test_info =
41 testing::UnitTest::GetInstance()->current_test_info();
42 return std::string(ANDROID_SOCKET_DIR "/") + std::string(test_info->test_case_name()) +
43 std::string(".") + std::string(test_info->name());
44 }
45
serverSocket(const std::string & path)46 unique_fd serverSocket(const std::string& path) {
47 unlink(path.c_str());
48
49 unique_fd fd(socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
50 EXPECT_GE(fd.get(), 0);
51
52 struct sockaddr_un addr = {.sun_family = AF_UNIX};
53 strlcpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path));
54
55 EXPECT_EQ(bind(fd.get(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr)), 0)
56 << "bind() to " << path << " failed: " << strerror(errno);
57 EXPECT_EQ(android_get_control_socket(path.c_str()), -1);
58
59 return fd;
60 }
61
clientSocket(const std::string & path)62 unique_fd clientSocket(const std::string& path) {
63 unique_fd fd(socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
64 EXPECT_GE(fd.get(), 0);
65
66 struct sockaddr_un addr = {.sun_family = AF_UNIX};
67 strlcpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path));
68
69 EXPECT_EQ(0, connect(fd.get(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr)))
70 << "connect() to " << path << " failed: " << strerror(errno);
71
72 return fd;
73 }
74
sendCmd(int fd,const char * cmd)75 void sendCmd(int fd, const char* cmd) {
76 EXPECT_TRUE(android::base::WriteFully(fd, cmd, strlen(cmd) + 1))
77 << "write() to socket failed: " << strerror(errno);
78 }
79
recvReply(int fd)80 std::string recvReply(int fd) {
81 pollfd fds = {.fd = fd, .events = POLLIN};
82 int poll_events = poll(&fds, 1, -1);
83 EXPECT_EQ(1, poll_events);
84
85 // Technically, this one-shot read() is incorrect: we should keep on
86 // reading the socket until we get a \0. But this is also how
87 // FrameworkListener::onDataAvailable() reads, and it works because
88 // replies are always send with a single write() call, and clients
89 // always read replies before queueing the next command.
90 char buf[1024];
91 ssize_t len = read(fd, buf, sizeof(buf));
92 EXPECT_GE(len, 0) << "read() from socket failed: " << strerror(errno);
93 return len > 0 ? std::string(buf, buf + len) : "";
94 }
95
96 // Test command which echoes back all its arguments as a comma-separated list.
97 // Always returns error code 42
98 //
99 // TODO: enable testing replies with addErrno=true and useCmdNum=true
100 class TestCommand : public FrameworkCommand {
101 public:
TestCommand()102 TestCommand() : FrameworkCommand("test") {}
~TestCommand()103 ~TestCommand() override {}
104
runCommand(SocketClient * cli,int argc,char ** argv)105 int runCommand(SocketClient* cli, int argc, char** argv) {
106 std::vector<std::string> args(argv, argv + argc);
107 std::string reply = android::base::Join(args, ',');
108 cli->sendMsg(42, reply.c_str(), /*addErrno=*/false, /*useCmdNum=*/false);
109 return 0;
110 }
111 };
112
113 // A test listener with a single command.
114 class TestListener : public FrameworkListener {
115 public:
TestListener(int fd)116 TestListener(int fd) : FrameworkListener(fd) {
117 registerCmd(new TestCommand); // Leaked :-(
118 }
119 };
120
121 } // unnamed namespace
122
123 class FrameworkListenerTest : public testing::Test {
124 public:
FrameworkListenerTest()125 FrameworkListenerTest() {
126 mSocketPath = testSocketPath();
127 mSserverFd = serverSocket(mSocketPath);
128 mListener = std::make_unique<TestListener>(mSserverFd.get());
129 EXPECT_EQ(0, mListener->startListener());
130 }
131
~FrameworkListenerTest()132 ~FrameworkListenerTest() override {
133 EXPECT_EQ(0, mListener->stopListener());
134
135 // Wouldn't it be cool if unique_fd had an option for taking care of this?
136 unlink(mSocketPath.c_str());
137 }
138
testCommand(const char * command,const char * expected)139 void testCommand(const char* command, const char* expected) {
140 unique_fd client_fd = clientSocket(mSocketPath);
141 sendCmd(client_fd.get(), command);
142
143 std::string reply = recvReply(client_fd.get());
144 EXPECT_EQ(std::string(expected) + '\0', reply);
145 }
146
147 protected:
148 std::string mSocketPath;
149 unique_fd mSserverFd;
150 std::unique_ptr<TestListener> mListener;
151 };
152
TEST_F(FrameworkListenerTest,DoesNothing)153 TEST_F(FrameworkListenerTest, DoesNothing) {
154 // Let the test harness start and stop a FrameworkListener
155 // without sending any commands through it.
156 }
157
TEST_F(FrameworkListenerTest,DispatchesValidCommands)158 TEST_F(FrameworkListenerTest, DispatchesValidCommands) {
159 testCommand("test", "42 test");
160 testCommand("test arg1 arg2", "42 test,arg1,arg2");
161 testCommand("test \"arg1 still_arg1\" arg2", "42 test,arg1 still_arg1,arg2");
162 testCommand("test \"escaped quote: '\\\"'\"", "42 test,escaped quote: '\"'");
163
164 // Perhaps this behavior was unintended, but would be good to detect any
165 // changes, in case anyone depends on it.
166 testCommand("test ", "42 test,,,");
167 }
168
TEST_F(FrameworkListenerTest,RejectsInvalidCommands)169 TEST_F(FrameworkListenerTest, RejectsInvalidCommands) {
170 testCommand("unknown arg1 arg2", "500 Command not recognized");
171 testCommand("test \"arg1 arg2", "500 Unclosed quotes error");
172 testCommand("test \\a", "500 Unsupported escape sequence");
173 }
174
TEST_F(FrameworkListenerTest,MultipleClients)175 TEST_F(FrameworkListenerTest, MultipleClients) {
176 unique_fd client1 = clientSocket(mSocketPath);
177 unique_fd client2 = clientSocket(mSocketPath);
178 sendCmd(client1.get(), "test 1");
179 sendCmd(client2.get(), "test 2");
180
181 EXPECT_EQ(std::string("42 test,2") + '\0', recvReply(client2.get()));
182 EXPECT_EQ(std::string("42 test,1") + '\0', recvReply(client1.get()));
183 }
184