1 //
2 // Copyright (C) 2012 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 "update_engine/common/subprocess.h"
18 
19 #include <fcntl.h>
20 #include <poll.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 
24 #include <set>
25 #include <string>
26 #include <vector>
27 
28 #include <base/bind.h>
29 #include <base/files/scoped_temp_dir.h>
30 #include <base/location.h>
31 #include <base/message_loop/message_loop.h>
32 #include <base/strings/string_util.h>
33 #include <base/strings/stringprintf.h>
34 #include <base/time/time.h>
35 #include <brillo/message_loops/base_message_loop.h>
36 #include <brillo/message_loops/message_loop.h>
37 #include <brillo/message_loops/message_loop_utils.h>
38 #include <brillo/strings/string_utils.h>
39 #include <brillo/unittest_utils.h>
40 #include <gtest/gtest.h>
41 
42 #include "update_engine/common/test_utils.h"
43 #include "update_engine/common/utils.h"
44 
45 using base::TimeDelta;
46 using brillo::MessageLoop;
47 using std::string;
48 using std::unique_ptr;
49 using std::vector;
50 
51 namespace {
52 
53 #ifdef __ANDROID__
54 #define kBinPath "/system/bin"
55 #define kUsrBinPath "/system/bin"
56 #else
57 #define kBinPath "/bin"
58 #define kUsrBinPath "/usr/bin"
59 #endif  // __ANDROID__
60 
61 }  // namespace
62 
63 namespace chromeos_update_engine {
64 
65 class SubprocessTest : public ::testing::Test {
66  protected:
SetUp()67   void SetUp() override {
68     loop_.SetAsCurrent();
69     async_signal_handler_.Init();
70     subprocess_.Init(&async_signal_handler_);
71   }
72 
73   base::MessageLoopForIO base_loop_;
74   brillo::BaseMessageLoop loop_{&base_loop_};
75   brillo::AsynchronousSignalHandler async_signal_handler_;
76   Subprocess subprocess_;
77   unique_ptr<base::FileDescriptorWatcher::Controller> watcher_;
78 
79 };
80 
81 namespace {
82 
ExpectedResults(int expected_return_code,const string & expected_output,int return_code,const string & output)83 void ExpectedResults(int expected_return_code,
84                      const string& expected_output,
85                      int return_code,
86                      const string& output) {
87   EXPECT_EQ(expected_return_code, return_code);
88   EXPECT_EQ(expected_output, output);
89   MessageLoop::current()->BreakLoop();
90 }
91 
ExpectedEnvVars(int return_code,const string & output)92 void ExpectedEnvVars(int return_code, const string& output) {
93   EXPECT_EQ(0, return_code);
94   const std::set<string> allowed_envs = {"LD_LIBRARY_PATH", "PATH"};
95   for (const string& key_value : brillo::string_utils::Split(output, "\n")) {
96     auto key_value_pair =
97         brillo::string_utils::SplitAtFirst(key_value, "=", true);
98     EXPECT_NE(allowed_envs.end(), allowed_envs.find(key_value_pair.first));
99   }
100   MessageLoop::current()->BreakLoop();
101 }
102 
ExpectedDataOnPipe(const Subprocess * subprocess,pid_t * pid,int child_fd,const string & child_fd_data,int expected_return_code,int return_code,const string &)103 void ExpectedDataOnPipe(const Subprocess* subprocess,
104                         pid_t* pid,
105                         int child_fd,
106                         const string& child_fd_data,
107                         int expected_return_code,
108                         int return_code,
109                         const string& /* output */) {
110   EXPECT_EQ(expected_return_code, return_code);
111 
112   // Verify that we can read the data from our end of |child_fd|.
113   int fd = subprocess->GetPipeFd(*pid, child_fd);
114   EXPECT_NE(-1, fd);
115   vector<char> buf(child_fd_data.size() + 1);
116   EXPECT_EQ(static_cast<ssize_t>(child_fd_data.size()),
117             HANDLE_EINTR(read(fd, buf.data(), buf.size())));
118   EXPECT_EQ(child_fd_data,
119             string(buf.begin(), buf.begin() + child_fd_data.size()));
120 
121   MessageLoop::current()->BreakLoop();
122 }
123 
124 }  // namespace
125 
TEST_F(SubprocessTest,IsASingleton)126 TEST_F(SubprocessTest, IsASingleton) {
127   EXPECT_EQ(&subprocess_, &Subprocess::Get());
128 }
129 
TEST_F(SubprocessTest,InactiveInstancesDontChangeTheSingleton)130 TEST_F(SubprocessTest, InactiveInstancesDontChangeTheSingleton) {
131   std::unique_ptr<Subprocess> another_subprocess(new Subprocess());
132   EXPECT_EQ(&subprocess_, &Subprocess::Get());
133   another_subprocess.reset();
134   EXPECT_EQ(&subprocess_, &Subprocess::Get());
135 }
136 
TEST_F(SubprocessTest,SimpleTest)137 TEST_F(SubprocessTest, SimpleTest) {
138   EXPECT_TRUE(subprocess_.Exec({kBinPath "/false"},
139                                base::Bind(&ExpectedResults, 1, "")));
140   loop_.Run();
141 }
142 
TEST_F(SubprocessTest,EchoTest)143 TEST_F(SubprocessTest, EchoTest) {
144   EXPECT_TRUE(subprocess_.Exec(
145       {kBinPath "/sh", "-c", "echo this is stdout; echo this is stderr >&2"},
146       base::Bind(&ExpectedResults, 0, "this is stdout\nthis is stderr\n")));
147   loop_.Run();
148 }
149 
TEST_F(SubprocessTest,StderrNotIncludedInOutputTest)150 TEST_F(SubprocessTest, StderrNotIncludedInOutputTest) {
151   EXPECT_TRUE(subprocess_.ExecFlags(
152       {kBinPath "/sh", "-c", "echo on stdout; echo on stderr >&2"},
153       0,
154       {},
155       base::Bind(&ExpectedResults, 0, "on stdout\n")));
156   loop_.Run();
157 }
158 
TEST_F(SubprocessTest,PipeRedirectFdTest)159 TEST_F(SubprocessTest, PipeRedirectFdTest) {
160   pid_t pid;
161   pid = subprocess_.ExecFlags(
162       {kBinPath "/sh", "-c", "echo on pipe >&3"},
163       0,
164       {3},
165       base::Bind(&ExpectedDataOnPipe, &subprocess_, &pid, 3, "on pipe\n", 0));
166   EXPECT_NE(0, pid);
167 
168   // Wrong file descriptor values should return -1.
169   EXPECT_EQ(-1, subprocess_.GetPipeFd(pid, 123));
170   loop_.Run();
171   // Calling GetPipeFd() after the callback runs is invalid.
172   EXPECT_EQ(-1, subprocess_.GetPipeFd(pid, 3));
173 }
174 
175 // Test that a pipe file descriptor open in the parent is not open in the child.
TEST_F(SubprocessTest,PipeClosedWhenNotRedirectedTest)176 TEST_F(SubprocessTest, PipeClosedWhenNotRedirectedTest) {
177   brillo::ScopedPipe pipe;
178 
179   // test_subprocess will return with the errno of fstat, which should be EBADF
180   // if the passed file descriptor is closed in the child.
181   const vector<string> cmd = {
182       test_utils::GetBuildArtifactsPath("test_subprocess"),
183       "fstat",
184       std::to_string(pipe.writer)};
185   EXPECT_TRUE(subprocess_.ExecFlags(
186       cmd, 0, {}, base::Bind(&ExpectedResults, EBADF, "")));
187   loop_.Run();
188 }
189 
TEST_F(SubprocessTest,EnvVarsAreFiltered)190 TEST_F(SubprocessTest, EnvVarsAreFiltered) {
191   EXPECT_TRUE(
192       subprocess_.Exec({kUsrBinPath "/env"}, base::Bind(&ExpectedEnvVars)));
193   loop_.Run();
194 }
195 
TEST_F(SubprocessTest,SynchronousTrueSearchsOnPath)196 TEST_F(SubprocessTest, SynchronousTrueSearchsOnPath) {
197   int rc = -1;
198   EXPECT_TRUE(Subprocess::SynchronousExecFlags(
199       {"true"}, Subprocess::kSearchPath, &rc, nullptr, nullptr));
200   EXPECT_EQ(0, rc);
201 }
202 
TEST_F(SubprocessTest,SynchronousEchoTest)203 TEST_F(SubprocessTest, SynchronousEchoTest) {
204   vector<string> cmd = {
205       kBinPath "/sh", "-c", "echo -n stdout-here; echo -n stderr-there >&2"};
206   int rc = -1;
207   string stdout, stderr;
208   ASSERT_TRUE(Subprocess::SynchronousExec(cmd, &rc, &stdout, &stderr));
209   EXPECT_EQ(0, rc);
210   EXPECT_EQ("stdout-here", stdout);
211   EXPECT_EQ("stderr-there", stderr);
212 }
213 
TEST_F(SubprocessTest,SynchronousEchoNoOutputTest)214 TEST_F(SubprocessTest, SynchronousEchoNoOutputTest) {
215   int rc = -1;
216   ASSERT_TRUE(Subprocess::SynchronousExec(
217       {kBinPath "/sh", "-c", "echo test"}, &rc, nullptr, nullptr));
218   EXPECT_EQ(0, rc);
219 }
220 
221 namespace {
CallbackBad(int return_code,const string & output)222 void CallbackBad(int return_code, const string& output) {
223   ADD_FAILURE() << "should never be called.";
224 }
225 }  // namespace
226 
227 // Test that you can cancel a program that's already running.
TEST_F(SubprocessTest,CancelTest)228 TEST_F(SubprocessTest, CancelTest) {
229   base::ScopedTempDir tempdir;
230   ASSERT_TRUE(tempdir.CreateUniqueTempDir());
231   string fifo_path = tempdir.GetPath().Append("fifo").value();
232   EXPECT_EQ(0, mkfifo(fifo_path.c_str(), 0666));
233 
234   // Start a process, make sure it is running and try to cancel it. We write
235   // two bytes to the fifo, the first one marks that the program is running and
236   // the second one marks that the process waited for a timeout and was not
237   // killed. We should read the first byte but not the second one.
238   vector<string> cmd = {
239       kBinPath "/sh",
240       "-c",
241       base::StringPrintf(
242           // The 'sleep' launched below could be left behind as an orphaned
243           // process when the 'sh' process is terminated by SIGTERM. As a
244           // remedy, trap SIGTERM and kill the 'sleep' process, which requires
245           // launching 'sleep' in background and then waiting for it.
246           "cleanup() { kill \"${sleep_pid}\"; exit 0; }; "
247           "trap cleanup TERM; "
248           "sleep 60 & "
249           "sleep_pid=$!; "
250           "printf X >\"%s\"; "
251           "wait; "
252           "printf Y >\"%s\"; "
253           "exit 1",
254           fifo_path.c_str(),
255           fifo_path.c_str())};
256   uint32_t tag = Subprocess::Get().Exec(cmd, base::Bind(&CallbackBad));
257   EXPECT_NE(0U, tag);
258 
259   int fifo_fd = HANDLE_EINTR(open(fifo_path.c_str(), O_RDONLY));
260   EXPECT_GE(fifo_fd, 0);
261 
262   watcher_ = base::FileDescriptorWatcher::WatchReadable(
263       fifo_fd,
264       base::Bind(
265           [](unique_ptr<base::FileDescriptorWatcher::Controller>* watcher,
266              int fifo_fd,
267              uint32_t tag) {
268             char c;
269             EXPECT_EQ(1, HANDLE_EINTR(read(fifo_fd, &c, 1)));
270             EXPECT_EQ('X', c);
271             LOG(INFO) << "Killing tag " << tag;
272             Subprocess::Get().KillExec(tag);
273             *watcher = nullptr;
274           },
275           // watcher_ is no longer used outside the clousure.
276           base::Unretained(&watcher_),
277           fifo_fd,
278           tag));
279 
280   // This test would leak a callback that runs when the child process exits
281   // unless we wait for it to run.
282   brillo::MessageLoopRunUntil(
283       &loop_, TimeDelta::FromSeconds(20), base::Bind([] {
284         return Subprocess::Get().subprocess_records_.empty();
285       }));
286   EXPECT_TRUE(Subprocess::Get().subprocess_records_.empty());
287   // Check that there isn't anything else to read from the pipe.
288   char c;
289   EXPECT_EQ(0, HANDLE_EINTR(read(fifo_fd, &c, 1)));
290   IGNORE_EINTR(close(fifo_fd));
291 }
292 
293 }  // namespace chromeos_update_engine
294