1 //
2 // Copyright (C) 2011 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/payload_consumer/postinstall_runner_action.h"
18 
19 #include <fcntl.h>
20 #include <signal.h>
21 #include <stdlib.h>
22 #include <sys/mount.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 
26 #include <cmath>
27 
28 #include <base/files/file_path.h>
29 #include <base/files/file_util.h>
30 #include <base/logging.h>
31 #include <base/stl_util.h>
32 #include <base/strings/string_split.h>
33 #include <base/strings/string_util.h>
34 
35 #include "update_engine/common/action_processor.h"
36 #include "update_engine/common/boot_control_interface.h"
37 #include "update_engine/common/platform_constants.h"
38 #include "update_engine/common/subprocess.h"
39 #include "update_engine/common/utils.h"
40 
41 namespace {
42 
43 // The file descriptor number from the postinstall program's perspective where
44 // it can report status updates. This can be any number greater than 2 (stderr),
45 // but must be kept in sync with the "bin/postinst_progress" defined in the
46 // sample_images.sh file.
47 const int kPostinstallStatusFd = 3;
48 
49 }  // namespace
50 
51 namespace chromeos_update_engine {
52 
53 using brillo::MessageLoop;
54 using std::string;
55 using std::vector;
56 
PerformAction()57 void PostinstallRunnerAction::PerformAction() {
58   CHECK(HasInputObject());
59   install_plan_ = GetInputObject();
60 
61   // We always powerwash when rolling back, however policy can determine
62   // if this is a full/normal powerwash, or a special rollback powerwash
63   // that retains a small amount of system state such as enrollment and
64   // network configuration. In both cases all user accounts are deleted.
65   if (install_plan_.powerwash_required || install_plan_.is_rollback) {
66     bool save_rollback_data =
67         install_plan_.is_rollback && install_plan_.rollback_data_save_requested;
68     if (hardware_->SchedulePowerwash(save_rollback_data)) {
69       powerwash_scheduled_ = true;
70     } else {
71       return CompletePostinstall(ErrorCode::kPostinstallPowerwashError);
72     }
73   }
74 
75   // Initialize all the partition weights.
76   partition_weight_.resize(install_plan_.partitions.size());
77   total_weight_ = 0;
78   for (size_t i = 0; i < install_plan_.partitions.size(); ++i) {
79     auto& partition = install_plan_.partitions[i];
80     if (!install_plan_.run_post_install && partition.postinstall_optional) {
81       partition.run_postinstall = false;
82       LOG(INFO) << "Skipping optional post-install for partition "
83                 << partition.name << " according to install plan.";
84     }
85 
86     // TODO(deymo): This code sets the weight to all the postinstall commands,
87     // but we could remember how long they took in the past and use those
88     // values.
89     partition_weight_[i] = partition.run_postinstall;
90     total_weight_ += partition_weight_[i];
91   }
92   accumulated_weight_ = 0;
93   ReportProgress(0);
94 
95   PerformPartitionPostinstall();
96 }
97 
PerformPartitionPostinstall()98 void PostinstallRunnerAction::PerformPartitionPostinstall() {
99   if (install_plan_.download_url.empty()) {
100     LOG(INFO) << "Skipping post-install during rollback";
101     return CompletePostinstall(ErrorCode::kSuccess);
102   }
103 
104   // Skip all the partitions that don't have a post-install step.
105   while (current_partition_ < install_plan_.partitions.size() &&
106          !install_plan_.partitions[current_partition_].run_postinstall) {
107     VLOG(1) << "Skipping post-install on partition "
108             << install_plan_.partitions[current_partition_].name;
109     current_partition_++;
110   }
111   if (current_partition_ == install_plan_.partitions.size())
112     return CompletePostinstall(ErrorCode::kSuccess);
113 
114   const InstallPlan::Partition& partition =
115       install_plan_.partitions[current_partition_];
116 
117   const string mountable_device = partition.target_path;
118   if (mountable_device.empty()) {
119     LOG(ERROR) << "Cannot make mountable device from " << partition.target_path;
120     return CompletePostinstall(ErrorCode::kPostinstallRunnerError);
121   }
122 
123   // Perform post-install for the current_partition_ partition. At this point we
124   // need to call CompletePartitionPostinstall to complete the operation and
125   // cleanup.
126 #ifdef __ANDROID__
127   fs_mount_dir_ = "/postinstall";
128 #else   // __ANDROID__
129   base::FilePath temp_dir;
130   TEST_AND_RETURN(base::CreateNewTempDirectory("au_postint_mount", &temp_dir));
131   fs_mount_dir_ = temp_dir.value();
132 #endif  // __ANDROID__
133 
134   // Double check that the fs_mount_dir is not busy with a previous mounted
135   // filesystem from a previous crashed postinstall step.
136   if (utils::IsMountpoint(fs_mount_dir_)) {
137     LOG(INFO) << "Found previously mounted filesystem at " << fs_mount_dir_;
138     utils::UnmountFilesystem(fs_mount_dir_);
139   }
140 
141   base::FilePath postinstall_path(partition.postinstall_path);
142   if (postinstall_path.IsAbsolute()) {
143     LOG(ERROR) << "Invalid absolute path passed to postinstall, use a relative"
144                   "path instead: "
145                << partition.postinstall_path;
146     return CompletePostinstall(ErrorCode::kPostinstallRunnerError);
147   }
148 
149   string abs_path =
150       base::FilePath(fs_mount_dir_).Append(postinstall_path).value();
151   if (!base::StartsWith(
152           abs_path, fs_mount_dir_, base::CompareCase::SENSITIVE)) {
153     LOG(ERROR) << "Invalid relative postinstall path: "
154                << partition.postinstall_path;
155     return CompletePostinstall(ErrorCode::kPostinstallRunnerError);
156   }
157 
158 #ifdef __ANDROID__
159   // In Chromium OS, the postinstall step is allowed to write to the block
160   // device on the target image, so we don't mark it as read-only and should
161   // be read-write since we just wrote to it during the update.
162 
163   // Mark the block device as read-only before mounting for post-install.
164   if (!utils::SetBlockDeviceReadOnly(mountable_device, true)) {
165     return CompletePartitionPostinstall(
166         1, "Error marking the device " + mountable_device + " read only.");
167   }
168 #endif  // __ANDROID__
169 
170   if (!utils::MountFilesystem(mountable_device,
171                               fs_mount_dir_,
172                               MS_RDONLY,
173                               partition.filesystem_type,
174                               constants::kPostinstallMountOptions)) {
175     return CompletePartitionPostinstall(
176         1, "Error mounting the device " + mountable_device);
177   }
178 
179   LOG(INFO) << "Performing postinst (" << partition.postinstall_path << " at "
180             << abs_path << ") installed on device " << partition.target_path
181             << " and mountable device " << mountable_device;
182 
183   // Logs the file format of the postinstall script we are about to run. This
184   // will help debug when the postinstall script doesn't match the architecture
185   // of our build.
186   LOG(INFO) << "Format file for new " << partition.postinstall_path
187             << " is: " << utils::GetFileFormat(abs_path);
188 
189   // Runs the postinstall script asynchronously to free up the main loop while
190   // it's running.
191   vector<string> command = {abs_path};
192 #ifdef __ANDROID__
193   // In Brillo and Android, we pass the slot number and status fd.
194   command.push_back(std::to_string(install_plan_.target_slot));
195   command.push_back(std::to_string(kPostinstallStatusFd));
196 #else
197   // Chrome OS postinstall expects the target rootfs as the first parameter.
198   command.push_back(partition.target_path);
199 #endif  // __ANDROID__
200 
201   current_command_ = Subprocess::Get().ExecFlags(
202       command,
203       Subprocess::kRedirectStderrToStdout,
204       {kPostinstallStatusFd},
205       base::Bind(&PostinstallRunnerAction::CompletePartitionPostinstall,
206                  base::Unretained(this)));
207   // Subprocess::Exec should never return a negative process id.
208   CHECK_GE(current_command_, 0);
209 
210   if (!current_command_) {
211     CompletePartitionPostinstall(1, "Postinstall didn't launch");
212     return;
213   }
214 
215   // Monitor the status file descriptor.
216   progress_fd_ =
217       Subprocess::Get().GetPipeFd(current_command_, kPostinstallStatusFd);
218   int fd_flags = fcntl(progress_fd_, F_GETFL, 0) | O_NONBLOCK;
219   if (HANDLE_EINTR(fcntl(progress_fd_, F_SETFL, fd_flags)) < 0) {
220     PLOG(ERROR) << "Unable to set non-blocking I/O mode on fd " << progress_fd_;
221   }
222 
223   progress_controller_ = base::FileDescriptorWatcher::WatchReadable(
224       progress_fd_,
225       base::BindRepeating(&PostinstallRunnerAction::OnProgressFdReady,
226                           base::Unretained(this)));
227 
228 }
229 
OnProgressFdReady()230 void PostinstallRunnerAction::OnProgressFdReady() {
231   char buf[1024];
232   size_t bytes_read;
233   do {
234     bytes_read = 0;
235     bool eof;
236     bool ok =
237         utils::ReadAll(progress_fd_, buf, base::size(buf), &bytes_read, &eof);
238     progress_buffer_.append(buf, bytes_read);
239     // Process every line.
240     vector<string> lines = base::SplitString(
241         progress_buffer_, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
242     if (!lines.empty()) {
243       progress_buffer_ = lines.back();
244       lines.pop_back();
245       for (const auto& line : lines) {
246         ProcessProgressLine(line);
247       }
248     }
249     if (!ok || eof) {
250       // There was either an error or an EOF condition, so we are done watching
251       // the file descriptor.
252       progress_controller_.reset();
253       return;
254     }
255   } while (bytes_read);
256 }
257 
ProcessProgressLine(const string & line)258 bool PostinstallRunnerAction::ProcessProgressLine(const string& line) {
259   double frac = 0;
260   if (sscanf(line.c_str(), "global_progress %lf", &frac) == 1 &&
261       !std::isnan(frac)) {
262     ReportProgress(frac);
263     return true;
264   }
265 
266   return false;
267 }
268 
ReportProgress(double frac)269 void PostinstallRunnerAction::ReportProgress(double frac) {
270   if (!delegate_)
271     return;
272   if (current_partition_ >= partition_weight_.size() || total_weight_ == 0) {
273     delegate_->ProgressUpdate(1.);
274     return;
275   }
276   if (!std::isfinite(frac) || frac < 0)
277     frac = 0;
278   if (frac > 1)
279     frac = 1;
280   double postinst_action_progress =
281       (accumulated_weight_ + partition_weight_[current_partition_] * frac) /
282       total_weight_;
283   delegate_->ProgressUpdate(postinst_action_progress);
284 }
285 
Cleanup()286 void PostinstallRunnerAction::Cleanup() {
287   utils::UnmountFilesystem(fs_mount_dir_);
288 #ifndef __ANDROID__
289   if (!base::DeleteFile(base::FilePath(fs_mount_dir_), false)) {
290     PLOG(WARNING) << "Not removing temporary mountpoint " << fs_mount_dir_;
291   }
292 #endif  // !__ANDROID__
293   fs_mount_dir_.clear();
294 
295   progress_fd_ = -1;
296   progress_controller_.reset();
297 
298   progress_buffer_.clear();
299 }
300 
CompletePartitionPostinstall(int return_code,const string & output)301 void PostinstallRunnerAction::CompletePartitionPostinstall(
302     int return_code, const string& output) {
303   current_command_ = 0;
304   Cleanup();
305 
306   if (return_code != 0) {
307     LOG(ERROR) << "Postinst command failed with code: " << return_code;
308     ErrorCode error_code = ErrorCode::kPostinstallRunnerError;
309 
310     if (return_code == 3) {
311       // This special return code means that we tried to update firmware,
312       // but couldn't because we booted from FW B, and we need to reboot
313       // to get back to FW A.
314       error_code = ErrorCode::kPostinstallBootedFromFirmwareB;
315     }
316 
317     if (return_code == 4) {
318       // This special return code means that we tried to update firmware,
319       // but couldn't because we booted from FW B, and we need to reboot
320       // to get back to FW A.
321       error_code = ErrorCode::kPostinstallFirmwareRONotUpdatable;
322     }
323 
324     // If postinstall script for this partition is optional we can ignore the
325     // result.
326     if (install_plan_.partitions[current_partition_].postinstall_optional) {
327       LOG(INFO) << "Ignoring postinstall failure since it is optional";
328     } else {
329       return CompletePostinstall(error_code);
330     }
331   }
332   accumulated_weight_ += partition_weight_[current_partition_];
333   current_partition_++;
334   ReportProgress(0);
335 
336   PerformPartitionPostinstall();
337 }
338 
CompletePostinstall(ErrorCode error_code)339 void PostinstallRunnerAction::CompletePostinstall(ErrorCode error_code) {
340   // We only attempt to mark the new slot as active if all the postinstall
341   // steps succeeded.
342   if (error_code == ErrorCode::kSuccess) {
343     if (install_plan_.switch_slot_on_reboot) {
344       if (!boot_control_->GetDynamicPartitionControl()->FinishUpdate(
345               install_plan_.powerwash_required) ||
346           !boot_control_->SetActiveBootSlot(install_plan_.target_slot)) {
347         error_code = ErrorCode::kPostinstallRunnerError;
348       } else {
349         // Schedules warm reset on next reboot, ignores the error.
350         hardware_->SetWarmReset(true);
351       }
352     } else {
353       error_code = ErrorCode::kUpdatedButNotActive;
354     }
355   }
356 
357   ScopedActionCompleter completer(processor_, this);
358   completer.set_code(error_code);
359 
360   if (error_code != ErrorCode::kSuccess &&
361       error_code != ErrorCode::kUpdatedButNotActive) {
362     LOG(ERROR) << "Postinstall action failed.";
363 
364     // Undo any changes done to trigger Powerwash.
365     if (powerwash_scheduled_)
366       hardware_->CancelPowerwash();
367 
368     return;
369   }
370 
371   LOG(INFO) << "All post-install commands succeeded";
372   if (HasOutputPipe()) {
373     SetOutputObject(install_plan_);
374   }
375 }
376 
SuspendAction()377 void PostinstallRunnerAction::SuspendAction() {
378   if (!current_command_)
379     return;
380   if (kill(current_command_, SIGSTOP) != 0) {
381     PLOG(ERROR) << "Couldn't pause child process " << current_command_;
382   } else {
383     is_current_command_suspended_ = true;
384   }
385 }
386 
ResumeAction()387 void PostinstallRunnerAction::ResumeAction() {
388   if (!current_command_)
389     return;
390   if (kill(current_command_, SIGCONT) != 0) {
391     PLOG(ERROR) << "Couldn't resume child process " << current_command_;
392   } else {
393     is_current_command_suspended_ = false;
394   }
395 }
396 
TerminateProcessing()397 void PostinstallRunnerAction::TerminateProcessing() {
398   if (!current_command_)
399     return;
400   // Calling KillExec() will discard the callback we registered and therefore
401   // the unretained reference to this object.
402   Subprocess::Get().KillExec(current_command_);
403 
404   // If the command has been suspended, resume it after KillExec() so that the
405   // process can process the SIGTERM sent by KillExec().
406   if (is_current_command_suspended_) {
407     ResumeAction();
408   }
409 
410   current_command_ = 0;
411   Cleanup();
412 }
413 
414 }  // namespace chromeos_update_engine
415