1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "chromecast/base/error_codes.h"
6 
7 #include <errno.h>
8 #include <fcntl.h>
9 
10 #include <string>
11 
12 #include "base/files/file_util.h"
13 #include "base/logging.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "chromecast/base/path_utils.h"
16 
17 namespace chromecast {
18 
19 namespace {
20 
21 const char kInitialErrorFile[] = "initial_error";
22 
GetInitialErrorFilePath()23 base::FilePath GetInitialErrorFilePath() {
24   return GetHomePathASCII(kInitialErrorFile);
25 }
26 
27 }  // namespace
28 
GetInitialErrorCode()29 ErrorCode GetInitialErrorCode() {
30   std::string initial_error_code_str;
31   if (!base::ReadFileToString(GetInitialErrorFilePath(),
32                               &initial_error_code_str)) {
33     return NO_ERROR;
34   }
35 
36   int initial_error_code = 0;
37   if (base::StringToInt(initial_error_code_str, &initial_error_code) &&
38       initial_error_code >= NO_ERROR && initial_error_code <= ERROR_UNKNOWN) {
39     DVLOG(1) << "Initial error from " << GetInitialErrorFilePath().value()
40              << ": " << initial_error_code;
41     return static_cast<ErrorCode>(initial_error_code);
42   }
43 
44   LOG(ERROR) << "Unknown initial error code: " << initial_error_code_str;
45   return NO_ERROR;
46 }
47 
SetInitialErrorCode(ErrorCode initial_error_code)48 bool SetInitialErrorCode(ErrorCode initial_error_code) {
49   // Note: Do not use Chromium IO methods in this function. When cast_shell
50   // crashes, this function can be called by any thread.
51   const std::string error_file_path = GetInitialErrorFilePath().value();
52 
53   if (initial_error_code > NO_ERROR && initial_error_code <= ERROR_UNKNOWN) {
54     const std::string initial_error_code_str(
55         base::NumberToString(initial_error_code));
56     int fd = creat(error_file_path.c_str(), 0640);
57     if (fd < 0) {
58       PLOG(ERROR) << "Could not open error code file";
59       return false;
60     }
61 
62     int written =
63         write(fd, initial_error_code_str.data(), initial_error_code_str.size());
64 
65     if (written != static_cast<int>(initial_error_code_str.size())) {
66       PLOG(ERROR) << "Could not write error code to file: written=" << written
67                   << ", expected=" << initial_error_code_str.size();
68       close(fd);
69       return false;
70     }
71 
72     close(fd);
73     return true;
74   }
75 
76   // Remove initial error file if no error.
77   if (unlink(error_file_path.c_str()) == 0 || errno == ENOENT)
78     return true;
79 
80   PLOG(ERROR) << "Failed to remove error file";
81   return false;
82 }
83 
84 }  // namespace chromecast
85