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